@cindifind/java-bridge 0.0.0-stage → 1.0.0

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.
package/lib/bridge.js ADDED
@@ -0,0 +1,368 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { EventEmitter } from 'node:events';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { JniErrorCode, isRequest, isNotification, isResponse } from './protocol.js';
6
+ /**
7
+ * Java 插件桥接器
8
+ *
9
+ * 通过子进程方式启动 Java 主程序,使用 NDJSON(换行分隔 JSON)进行双向通信:
10
+ * - stdin :Node → Java 的请求 / 通知
11
+ * - stdout :Java → Node 的响应 / 通知(每行一条 JSON)
12
+ * - stderr :Java 侧原始日志,转发到 logger
13
+ *
14
+ * 所有调用以 JSON-RPC 2.0 request/response 模式进行,支持超时与并发。
15
+ */
16
+ export class JniBridge extends EventEmitter {
17
+ options;
18
+ process = null;
19
+ seq = 0;
20
+ pending = new Map();
21
+ stdoutBuffer = '';
22
+ starting = null;
23
+ destroyed = false;
24
+ constructor(options) {
25
+ super();
26
+ this.options = options;
27
+ }
28
+ /** Java 进程是否正在运行 */
29
+ get running() {
30
+ return this.process !== null && !this.process.killed && this.process.exitCode === null;
31
+ }
32
+ /**
33
+ * 启动 Java 桥接进程
34
+ */
35
+ async start() {
36
+ if (this.destroyed) {
37
+ throw new Error('[JavaBridge] Bridge has been destroyed');
38
+ }
39
+ if (this.running) {
40
+ return;
41
+ }
42
+ if (this.starting) {
43
+ return this.starting;
44
+ }
45
+ this.starting = this.doStart();
46
+ try {
47
+ await this.starting;
48
+ }
49
+ finally {
50
+ this.starting = null;
51
+ }
52
+ }
53
+ async doStart() {
54
+ const { javaPath, bridgeJar, classpath, logger } = this.options;
55
+ // 防御性转换:jvmArgs 可能是字符串(来自 WebUI 配置)
56
+ const jvmArgs = Array.isArray(this.options.jvmArgs)
57
+ ? this.options.jvmArgs
58
+ : String(this.options.jvmArgs).split(/\s+/).filter(s => s.length > 0);
59
+ if (!bridgeJar || !fs.existsSync(bridgeJar)) {
60
+ throw new Error(`[JavaBridge] Bridge jar not found: ${bridgeJar}`);
61
+ }
62
+ // 构建 classpath
63
+ const cp = [path.dirname(bridgeJar), ...classpath].join(path.delimiter);
64
+ const args = [
65
+ ...jvmArgs,
66
+ '-cp',
67
+ cp,
68
+ '-jar',
69
+ bridgeJar,
70
+ ];
71
+ logger.info(`[JavaBridge] Starting Java bridge: ${javaPath} ${args.join(' ')}`);
72
+ const child = spawn(javaPath, args, {
73
+ stdio: ['pipe', 'pipe', 'pipe'],
74
+ windowsHide: true,
75
+ env: {
76
+ ...process.env,
77
+ // 标记通信模式,便于 Java 侧识别
78
+ NAPCAT_JNI_MODE: 'ndjson',
79
+ },
80
+ });
81
+ this.process = child;
82
+ child.stdout?.setEncoding('utf-8');
83
+ child.stdout?.on('data', (chunk) => this.handleStdout(chunk));
84
+ child.stderr?.setEncoding('utf-8');
85
+ child.stderr?.on('data', (chunk) => this.handleStderr(chunk));
86
+ child.on('exit', (code, signal) => {
87
+ logger.warn(`[JavaBridge] Java process exited (code=${code}, signal=${signal})`);
88
+ this.cleanupPending(new Error(`Java process exited (code=${code}, signal=${signal})`));
89
+ this.process = null;
90
+ this.emit('exit', code, signal);
91
+ });
92
+ child.on('error', (err) => {
93
+ logger.error('[JavaBridge] Failed to spawn Java process:', err);
94
+ this.cleanupPending(err);
95
+ this.process = null;
96
+ // No 'exit' follows a spawn error, so start() would otherwise wait out the whole ready timeout
97
+ this.emit('failed', err);
98
+ });
99
+ // 等待 Java 侧的 ready 通知
100
+ await this.waitForReady();
101
+ }
102
+ /** 等待 Java 侧发出 ready 通知 */
103
+ waitForReady() {
104
+ return new Promise((resolve, reject) => {
105
+ const timeout = setTimeout(() => {
106
+ cleanup();
107
+ reject(new Error('[JavaBridge] Timed out waiting for Java bridge ready'));
108
+ }, 30_000);
109
+ const onReady = () => {
110
+ cleanup();
111
+ resolve();
112
+ };
113
+ const onExit = (code, signal) => {
114
+ cleanup();
115
+ reject(new Error(`[JavaBridge] Java process exited before ready (code=${code}, signal=${signal})`));
116
+ };
117
+ const onFailed = (error) => {
118
+ cleanup();
119
+ reject(error);
120
+ };
121
+ const cleanup = () => {
122
+ clearTimeout(timeout);
123
+ this.off('ready', onReady);
124
+ this.off('exit', onExit);
125
+ this.off('failed', onFailed);
126
+ };
127
+ this.once('ready', onReady);
128
+ this.once('exit', onExit);
129
+ this.once('failed', onFailed);
130
+ });
131
+ }
132
+ handleStdout(chunk) {
133
+ this.stdoutBuffer += chunk;
134
+ let idx;
135
+ while ((idx = this.stdoutBuffer.indexOf('\n')) >= 0) {
136
+ const line = this.stdoutBuffer.slice(0, idx).trim();
137
+ this.stdoutBuffer = this.stdoutBuffer.slice(idx + 1);
138
+ if (!line)
139
+ continue;
140
+ this.handleMessage(line);
141
+ }
142
+ }
143
+ handleStderr(chunk) {
144
+ // Java 侧原始日志直接转发
145
+ const text = chunk.toString();
146
+ for (const line of text.split(/\r?\n/)) {
147
+ if (line.trim()) {
148
+ this.options.logger.info(`[Java] ${line}`);
149
+ }
150
+ }
151
+ }
152
+ handleMessage(line) {
153
+ let msg;
154
+ try {
155
+ msg = JSON.parse(line);
156
+ }
157
+ catch {
158
+ this.options.logger.warn(`[JavaBridge] Failed to parse stdout line: ${line}`);
159
+ return;
160
+ }
161
+ // 响应:匹配 pending 请求
162
+ if (isResponse(msg)) {
163
+ const id = msg.id;
164
+ if (id === null) {
165
+ this.options.logger.warn('[JavaBridge] Received response with null id, ignored');
166
+ return;
167
+ }
168
+ const pending = this.pending.get(id);
169
+ if (!pending) {
170
+ this.options.logger.warn(`[JavaBridge] Received response with unknown id: ${id}`);
171
+ return;
172
+ }
173
+ clearTimeout(pending.timer);
174
+ this.pending.delete(id);
175
+ if ('error' in msg) {
176
+ pending.reject(new Error(`${msg.error.message} (code=${msg.error.code})`));
177
+ }
178
+ else {
179
+ pending.resolve(msg.result);
180
+ }
181
+ return;
182
+ }
183
+ // 通知:分发到事件
184
+ if (isNotification(msg)) {
185
+ this.handleNotification(msg);
186
+ return;
187
+ }
188
+ // Java → Node 的请求(例如 Java 主动调用 Action 时也用请求模式)
189
+ if (isRequest(msg)) {
190
+ // 这里只处理一种特殊请求:ready 信号
191
+ const req = msg;
192
+ if (req.method === 'ready') {
193
+ this.emit('ready');
194
+ // 无需响应(按通知处理)
195
+ }
196
+ return;
197
+ }
198
+ }
199
+ handleNotification(msg) {
200
+ switch (msg.method) {
201
+ case 'ready':
202
+ this.emit('ready');
203
+ break;
204
+ case 'log': {
205
+ const params = (msg.params ?? {});
206
+ const args = params.args ?? [];
207
+ switch (params.level) {
208
+ case 'debug':
209
+ this.options.logger.debug(`[Java] ${params.message}`, ...args);
210
+ break;
211
+ case 'info':
212
+ this.options.logger.info(`[Java] ${params.message}`, ...args);
213
+ break;
214
+ case 'warn':
215
+ this.options.logger.warn(`[Java] ${params.message}`, ...args);
216
+ break;
217
+ case 'error':
218
+ this.options.logger.error(`[Java] ${params.message}`, ...args);
219
+ break;
220
+ default: this.options.logger.info(`[Java] ${params.message}`, ...args);
221
+ }
222
+ break;
223
+ }
224
+ case 'action': {
225
+ const params = (msg.params ?? {});
226
+ this.emit('action', params);
227
+ break;
228
+ }
229
+ case 'event': {
230
+ const params = (msg.params ?? {});
231
+ this.emit('event', params.event);
232
+ break;
233
+ }
234
+ default:
235
+ this.options.logger.debug(`[JavaBridge] Unknown notification: ${msg.method}`);
236
+ }
237
+ }
238
+ /**
239
+ * 发送 JSON-RPC 请求并等待响应
240
+ */
241
+ call(method, params, timeout) {
242
+ return new Promise((resolve, reject) => {
243
+ if (!this.running) {
244
+ reject(new Error(`[JavaBridge] Bridge not running (call: ${method})`));
245
+ return;
246
+ }
247
+ const id = ++this.seq;
248
+ const req = { jsonrpc: '2.0', id, method, params };
249
+ const ttl = timeout ?? this.options.callTimeout;
250
+ const timer = setTimeout(() => {
251
+ if (this.pending.has(id)) {
252
+ this.pending.delete(id);
253
+ reject(new Error(`[JavaBridge] Call '${method}' timed out after ${ttl}ms`));
254
+ }
255
+ }, ttl);
256
+ this.pending.set(id, { resolve: resolve, reject, timer });
257
+ try {
258
+ this.writeLine(JSON.stringify(req));
259
+ }
260
+ catch (e) {
261
+ clearTimeout(timer);
262
+ this.pending.delete(id);
263
+ reject(e);
264
+ }
265
+ });
266
+ }
267
+ /**
268
+ * 发送通知(无需响应)
269
+ */
270
+ notify(method, params) {
271
+ if (!this.running) {
272
+ this.options.logger.warn(`[JavaBridge] Bridge not running, notify '${method}' dropped`);
273
+ return;
274
+ }
275
+ const msg = { jsonrpc: '2.0', method, params };
276
+ try {
277
+ this.writeLine(JSON.stringify(msg));
278
+ }
279
+ catch (e) {
280
+ this.options.logger.error(`[JavaBridge] Failed to send notification '${method}':`, e);
281
+ }
282
+ }
283
+ /**
284
+ * 向 Java 回传 Action 调用结果
285
+ */
286
+ replyAction(requestId, ok, data, error) {
287
+ this.notify('action_result', { requestId, ok, data, error });
288
+ }
289
+ writeLine(line) {
290
+ if (!this.process?.stdin) {
291
+ throw new Error('[JavaBridge] stdin not available');
292
+ }
293
+ this.process.stdin.write(line + '\n');
294
+ }
295
+ /** 清理所有 pending 请求 */
296
+ cleanupPending(err) {
297
+ for (const [id, pending] of this.pending) {
298
+ clearTimeout(pending.timer);
299
+ pending.reject(err);
300
+ this.pending.delete(id);
301
+ }
302
+ }
303
+ /**
304
+ * 停止 Java 进程
305
+ */
306
+ async stop(timeout = 5000) {
307
+ if (!this.process)
308
+ return;
309
+ // 通知 Java 侧优雅退出
310
+ try {
311
+ await this.call('cleanup', {}, Math.min(timeout, 3000)).catch(() => void 0);
312
+ }
313
+ catch {
314
+ // 忽略清理调用失败
315
+ }
316
+ const child = this.process;
317
+ if (!child)
318
+ return;
319
+ await new Promise((resolve) => {
320
+ const killer = setTimeout(() => {
321
+ if (this.process) {
322
+ this.process.kill('SIGKILL');
323
+ }
324
+ resolve();
325
+ }, timeout);
326
+ child.once('exit', () => {
327
+ clearTimeout(killer);
328
+ resolve();
329
+ });
330
+ try {
331
+ child.stdin?.end();
332
+ }
333
+ catch {
334
+ // 忽略
335
+ }
336
+ try {
337
+ child.kill('SIGTERM');
338
+ }
339
+ catch {
340
+ // 忽略
341
+ }
342
+ });
343
+ this.process = null;
344
+ this.cleanupPending(new Error('[JavaBridge] Bridge stopped'));
345
+ }
346
+ /**
347
+ * 销毁桥接器(不可再使用)
348
+ */
349
+ async destroy() {
350
+ this.destroyed = true;
351
+ await this.stop();
352
+ this.removeAllListeners();
353
+ }
354
+ }
355
+ /**
356
+ * 创建并启动 Java 桥接器,完成初始化握手
357
+ */
358
+ export async function createJniBridge(options, initParams) {
359
+ const bridge = new JniBridge(options);
360
+ await bridge.start();
361
+ const info = await bridge.call('init', initParams);
362
+ return { bridge, info };
363
+ }
364
+ /** 默认桥接 JAR 文件名 */
365
+ export const DEFAULT_BRIDGE_JAR = 'onebot-bridge.jar';
366
+ /** 默认 Java 插件目录名 */
367
+ export const DEFAULT_JAVA_PLUGIN_DIR = 'java-plugins';
368
+ export { JniErrorCode };
package/lib/convert.js ADDED
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Turns a neutral event (what `ctx.on('bot/session')` hands out) into the OneBot 11 shape a Java plugin
3
+ * expects. Events without an OneBot counterpart — reactions, internal platform events — are skipped.
4
+ */
5
+ export function toOneBotEvent(session, options = {}) {
6
+ const selfId = toId(session.selfId);
7
+ const time = Math.floor(session.timestamp / 1000);
8
+ const userId = toId(session.userId);
9
+ const messageId = session.messageId ? resolveMessageId(session.messageId, options) : undefined;
10
+ switch (session.type) {
11
+ case 'message-created':
12
+ return messageEvent(session, selfId, time, messageId, userId);
13
+ case 'message-deleted':
14
+ return recallEvent(session, selfId, time, messageId, userId);
15
+ case 'guild-member-added':
16
+ case 'guild-member-removed':
17
+ return memberEvent(session, selfId, time, userId);
18
+ case 'friend-added':
19
+ return {
20
+ post_type: 'notice',
21
+ notice_type: 'friend_add',
22
+ self_id: selfId,
23
+ user_id: userId,
24
+ time,
25
+ };
26
+ case 'friend-request':
27
+ return {
28
+ post_type: 'request',
29
+ request_type: 'friend',
30
+ self_id: selfId,
31
+ user_id: userId,
32
+ comment: session.event.message?.content ?? '',
33
+ // OneBot 的 flag 要原样回传;中立事件的 message.id 正是 internal 认得的那个
34
+ flag: session.messageId ?? '',
35
+ time,
36
+ };
37
+ case 'guild-request':
38
+ case 'guild-member-request':
39
+ return {
40
+ post_type: 'request',
41
+ request_type: 'group',
42
+ sub_type: session.type === 'guild-request' ? 'invite' : 'add',
43
+ self_id: selfId,
44
+ group_id: toId(session.guildId),
45
+ user_id: userId,
46
+ comment: session.event.message?.content ?? '',
47
+ flag: session.messageId ?? '',
48
+ time,
49
+ };
50
+ default:
51
+ return;
52
+ }
53
+ }
54
+ function messageEvent(session, selfId, time, messageId, userId) {
55
+ const segments = toSegments(session.elements);
56
+ const messageType = session.isDirect ? 'private' : 'group';
57
+ const groupId = messageType === 'group' ? toId(session.guildId ?? session.channelId) : undefined;
58
+ const self = isSelf(session);
59
+ const sender = {
60
+ user_id: userId,
61
+ nickname: session.event.user?.name ?? '',
62
+ };
63
+ if (messageType === 'group') {
64
+ sender.card = session.event.member?.nick ?? '';
65
+ sender.role = roleOf(session.event.member?.roles);
66
+ }
67
+ const event = {
68
+ post_type: self ? 'message_sent' : 'message',
69
+ self_id: selfId,
70
+ message_type: messageType,
71
+ sub_type: messageType === 'group' ? 'normal' : 'friend',
72
+ message_id: messageId,
73
+ message_seq: seqOf(session.messageId),
74
+ user_id: userId,
75
+ message: segments,
76
+ message_format: 'array',
77
+ raw_message: toCQCode(segments),
78
+ font: 14,
79
+ sender,
80
+ time,
81
+ };
82
+ if (groupId != null) {
83
+ event.group_id = groupId;
84
+ }
85
+ if (self) {
86
+ // What OneBot calls the other end of a message one sent: the group, or the friend's uin
87
+ event.target_id = groupId ?? toId(String(session.channelId ?? '').replace(/^private:/, ''));
88
+ }
89
+ return event;
90
+ }
91
+ function recallEvent(session, selfId, time, messageId, userId) {
92
+ const groupId = toId(session.guildId);
93
+ if (groupId != null) {
94
+ return {
95
+ post_type: 'notice',
96
+ notice_type: 'group_recall',
97
+ self_id: selfId,
98
+ group_id: groupId,
99
+ user_id: userId,
100
+ operator_id: toId(session.event.operator?.id) ?? userId,
101
+ message_id: messageId,
102
+ time,
103
+ };
104
+ }
105
+ return {
106
+ post_type: 'notice',
107
+ notice_type: 'friend_recall',
108
+ self_id: selfId,
109
+ user_id: userId,
110
+ message_id: messageId,
111
+ time,
112
+ };
113
+ }
114
+ function memberEvent(session, selfId, time, userId) {
115
+ const increase = session.type === 'guild-member-added';
116
+ return {
117
+ post_type: 'notice',
118
+ notice_type: increase ? 'group_increase' : 'group_decrease',
119
+ // No operator means the member left by themselves; otherwise someone removed them
120
+ sub_type: increase ? 'approve' : (session.event.operator ? 'kick' : 'leave'),
121
+ self_id: selfId,
122
+ group_id: toId(session.guildId),
123
+ user_id: userId,
124
+ operator_id: toId(session.event.operator?.id),
125
+ time,
126
+ };
127
+ }
128
+ /** `<chatType>|<peerUid>|<msgSeq>` as OneBot knows a message, without the host's short id. */
129
+ function seqOf(raw) {
130
+ if (!raw)
131
+ return;
132
+ const seq = Number(raw.includes('|') ? raw.split('|')[2] : raw);
133
+ return Number.isSafeInteger(seq) ? seq : undefined;
134
+ }
135
+ function resolveMessageId(raw, options) {
136
+ const resolved = options.messageId?.(raw);
137
+ return resolved != null ? resolved : seqOf(raw);
138
+ }
139
+ function toId(value) {
140
+ if (value == null || value === '')
141
+ return;
142
+ const id = Number(value);
143
+ return Number.isSafeInteger(id) ? id : String(value);
144
+ }
145
+ function isSelf(session) {
146
+ const sender = session.event.user?.id;
147
+ return sender != null && String(sender) === String(session.event.self_id ?? session.selfId);
148
+ }
149
+ function roleOf(roles) {
150
+ const names = (roles ?? []).map(role => role.name ?? role.id);
151
+ if (names.includes('owner'))
152
+ return 'owner';
153
+ if (names.includes('admin'))
154
+ return 'admin';
155
+ return 'member';
156
+ }
157
+ /** OneBot 11 message segments, in the native type names a Java plugin reads. */
158
+ export function toSegments(elements) {
159
+ const segments = [];
160
+ for (const element of elements)
161
+ segments.push(...elementToSegments(element));
162
+ return segments;
163
+ }
164
+ function elementToSegments(element) {
165
+ const attrs = (element.attrs ?? {});
166
+ const children = (element.children ?? []);
167
+ switch (element.type) {
168
+ case 'text':
169
+ return [textSegment(String(attrs.content ?? ''))];
170
+ case 'at':
171
+ return [{ type: 'at', data: { qq: attrs.type === 'all' ? 'all' : String(attrs.id ?? '') } }];
172
+ case 'img':
173
+ case 'image':
174
+ return [{ type: 'image', data: { file: attrs.src, url: attrs.src } }];
175
+ case 'audio':
176
+ return [{ type: 'record', data: { file: attrs.src, url: attrs.src } }];
177
+ case 'video':
178
+ return [{ type: 'video', data: { file: attrs.src, url: attrs.src } }];
179
+ case 'file':
180
+ return [{ type: 'file', data: { file: attrs.src, url: attrs.src, name: attrs.name } }];
181
+ case 'face':
182
+ return [{ type: 'face', data: { id: String(attrs.id ?? '') } }];
183
+ case 'quote':
184
+ return [{ type: 'reply', data: { id: String(attrs.id ?? '') } }];
185
+ case 'br':
186
+ return [textSegment('\n')];
187
+ case 'p':
188
+ return [...toSegments(children), textSegment('\n')];
189
+ case 'markdown':
190
+ return [{ type: 'markdown', data: { content: textOf(element) } }];
191
+ case 'button':
192
+ return [textSegment(String(attrs.text ?? textOf(element)))];
193
+ case 'button-group':
194
+ return toSegments(children);
195
+ default:
196
+ // Platform cards, market faces and anything newer keep what their text says
197
+ return [textSegment(String(attrs.summary ?? textOf(element)))];
198
+ }
199
+ }
200
+ function textSegment(text) {
201
+ return { type: 'text', data: { text } };
202
+ }
203
+ function textOf(element) {
204
+ if (element.type === 'text')
205
+ return String(element.attrs?.content ?? '');
206
+ return (element.children ?? []).map(textOf).join('');
207
+ }
208
+ /** The CQ code form, for plugins that read `raw_message` instead of the segments. */
209
+ export function toCQCode(segments) {
210
+ return segments.map(segment => {
211
+ if (segment.type === 'text')
212
+ return cqEscape(String(segment.data.text ?? ''));
213
+ const params = Object.entries(segment.data)
214
+ .filter(([, value]) => value != null && value !== '')
215
+ .map(([key, value]) => `${key}=${cqEscape(String(value))}`)
216
+ .join(',');
217
+ return `[CQ:${segment.type}${params ? ',' + params : ''}]`;
218
+ }).join('');
219
+ }
220
+ function cqEscape(text) {
221
+ return text
222
+ .replace(/&/g, '&amp;')
223
+ .replace(/\[/g, '&#91;')
224
+ .replace(/\]/g, '&#93;')
225
+ .replace(/,/g, '&#44;');
226
+ }
227
+ /** `set_group_card` as setGroupCard, `_send_group_notice` as sendGroupNotice — bot.internal's keys. */
228
+ export function toInternalMethod(action) {
229
+ return action.replace(/^[._]+/, '').replace(/_([a-z0-9])/g, (_, char) => char.toUpperCase());
230
+ }
package/lib/index.js ADDED
@@ -0,0 +1,22 @@
1
+ import { createJavaBridgeRoutes } from './routes.js';
2
+ import { JavaBridgeRuntime } from './runtime.js';
3
+ import { Config } from './settings.js';
4
+ export { Config };
5
+ export const name = 'java-bridge';
6
+ export const inject = ['bots'];
7
+ /**
8
+ * Java 插件桥接:把自己的 Java 插件(.jar)放进 data/java-plugins,插件启动时拉起一个 Java 进程,
9
+ * 把 QQ 账号收到的 OneBot 11 事件推给它,Java 插件也能反向调用 OneBot 11 的 API。
10
+ */
11
+ export function apply(ctx, config) {
12
+ const runtime = new JavaBridgeRuntime(ctx, config);
13
+ ctx.effect(() => {
14
+ void runtime.start();
15
+ return () => runtime.dispose();
16
+ });
17
+ ctx.on('bot/session', session => runtime.handleSession(session));
18
+ // The WebUI half is optional: on a headless bot the bridge still runs
19
+ ctx.inject(['webuiServer'], (ctx) => {
20
+ ctx.webuiServer.route('/api/java-bridge', createJavaBridgeRoutes(runtime));
21
+ });
22
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Java 插件桥接的通信协议类型
3
+ *
4
+ * 通信方式:以换行符分隔的 JSON(NDJSON),每行一条消息
5
+ * 协议基于 JSON-RPC 2.0,并扩展了双向通知(notification)以支持 Java 侧主动调用 OneBot 能力
6
+ *
7
+ * Node.js → Java :请求(request) / 通知(notification)
8
+ * Java → Node.js:响应(response) / 通知(notification,例如日志、调用 OneBot API)
9
+ */
10
+ // ==================== 错误码 ====================
11
+ export var JniErrorCode;
12
+ (function (JniErrorCode) {
13
+ JniErrorCode[JniErrorCode["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
14
+ JniErrorCode[JniErrorCode["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
15
+ JniErrorCode[JniErrorCode["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
16
+ JniErrorCode[JniErrorCode["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
17
+ JniErrorCode[JniErrorCode["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
18
+ /** Java 进程未启动 / 已退出 */
19
+ JniErrorCode[JniErrorCode["BRIDGE_NOT_RUNNING"] = -32001] = "BRIDGE_NOT_RUNNING";
20
+ /** 调用超时 */
21
+ JniErrorCode[JniErrorCode["CALL_TIMEOUT"] = -32002] = "CALL_TIMEOUT";
22
+ /** Java 插件加载失败 */
23
+ JniErrorCode[JniErrorCode["PLUGIN_LOAD_FAILED"] = -32003] = "PLUGIN_LOAD_FAILED";
24
+ })(JniErrorCode || (JniErrorCode = {}));
25
+ // ==================== 协议辅助 ====================
26
+ /** 判断消息是否为 JSON-RPC 请求 */
27
+ export function isRequest(msg) {
28
+ return msg?.jsonrpc === '2.0' && typeof msg.method === 'string' && msg.id !== undefined && msg.id !== null;
29
+ }
30
+ /** 判断消息是否为 JSON-RPC 通知 */
31
+ export function isNotification(msg) {
32
+ return msg?.jsonrpc === '2.0' && typeof msg.method === 'string' && (msg.id === undefined || msg.id === null);
33
+ }
34
+ /** 判断消息是否为 JSON-RPC 响应 */
35
+ export function isResponse(msg) {
36
+ return msg?.jsonrpc === '2.0' && msg.id !== undefined && msg.id !== null && ('result' in msg || 'error' in msg);
37
+ }
package/lib/routes.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `/api/java-bridge/*`, the API the WebUI page calls: `status`, `reload`, `plugins/load`, `plugins/unload`.
3
+ * Answers in the WebUI's `{ success, data, message }` shape.
4
+ */
5
+ export function createJavaBridgeRoutes(runtime) {
6
+ return {
7
+ async fetch(request) {
8
+ const { pathname } = new URL(request.url);
9
+ const action = pathname.replace(/^\/api\/java-bridge\/?/, '').replace(/\/+$/, '');
10
+ try {
11
+ switch (action) {
12
+ case '':
13
+ case 'status':
14
+ return reply(true, runtime.status());
15
+ case 'reload':
16
+ return reply(true, await runtime.reload());
17
+ case 'plugins':
18
+ return reply(true, await runtime.listPlugins());
19
+ case 'plugins/load': {
20
+ const body = await readJson(request);
21
+ return reply(true, await runtime.loadPlugin(String(body.id ?? '')));
22
+ }
23
+ case 'plugins/unload': {
24
+ const body = await readJson(request);
25
+ return reply(true, await runtime.unloadPlugin(String(body.id ?? '')));
26
+ }
27
+ default:
28
+ return Response.json({ success: false, message: '接口不存在' }, { status: 404 });
29
+ }
30
+ }
31
+ catch (e) {
32
+ return Response.json({ success: false, message: e instanceof Error ? e.message : String(e) }, { status: 500 });
33
+ }
34
+ },
35
+ };
36
+ }
37
+ function reply(success, data) {
38
+ return Response.json({ success, data });
39
+ }
40
+ async function readJson(request) {
41
+ try {
42
+ return (await request.json());
43
+ }
44
+ catch {
45
+ return {};
46
+ }
47
+ }
package/lib/runtime.js ADDED
@@ -0,0 +1,341 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { DEFAULT_BRIDGE_JAR, DEFAULT_JAVA_PLUGIN_DIR, JniBridge } from './bridge.js';
5
+ import { toInternalMethod, toOneBotEvent } from './convert.js';
6
+ /**
7
+ * Runs the Java process and feeds it OneBot 11: events come from `bot/session` (converted in convert.ts),
8
+ * actions go back through the bot's `internal`, which is the OneBot 11 action set of the QQ account.
9
+ */
10
+ export class JavaBridgeRuntime {
11
+ ctx;
12
+ config;
13
+ bridge = null;
14
+ plugins = [];
15
+ starting = null;
16
+ error = '';
17
+ disposed = false;
18
+ constructor(ctx, config) {
19
+ this.ctx = ctx;
20
+ this.config = config;
21
+ }
22
+ get running() {
23
+ return this.bridge?.running ?? false;
24
+ }
25
+ /** The bot's data directory: where `data/java-plugins` and the Java plugins' own files live. */
26
+ get dataPath() {
27
+ return path.resolve('data');
28
+ }
29
+ /** The bridge jar: a configured path, else the copy shipped beside lib/ in this package. */
30
+ get bridgeJar() {
31
+ const name = this.config.bridgeJar?.trim() || DEFAULT_BRIDGE_JAR;
32
+ if (path.isAbsolute(name))
33
+ return name;
34
+ const base = path.dirname(fileURLToPath(import.meta.url));
35
+ const candidates = [
36
+ path.join(base, name),
37
+ path.join(base, '..', name),
38
+ path.resolve(name),
39
+ ];
40
+ return candidates.find(candidate => fs.existsSync(candidate)) ?? candidates[0];
41
+ }
42
+ /** The Java plugin directory: an absolute path, else relative to the data directory. */
43
+ get javaPluginDir() {
44
+ const configured = this.config.javaPluginDir?.trim() || DEFAULT_JAVA_PLUGIN_DIR;
45
+ return path.isAbsolute(configured) ? configured : path.resolve(this.dataPath, configured);
46
+ }
47
+ status() {
48
+ const jar = this.bridgeJar;
49
+ return {
50
+ running: this.running,
51
+ starting: this.starting != null,
52
+ error: this.error,
53
+ javaPath: this.config.javaPath?.trim() || 'java',
54
+ bridgeJar: jar,
55
+ bridgeJarExists: fs.existsSync(jar),
56
+ javaPluginDir: this.javaPluginDir,
57
+ dataPath: this.dataPath,
58
+ plugins: this.plugins,
59
+ bots: this.accounts(),
60
+ };
61
+ }
62
+ /** Starts the Java process and hands it the plugin directory; a failure is kept for the WebUI page. */
63
+ async start() {
64
+ if (this.disposed)
65
+ return;
66
+ if (this.running)
67
+ return;
68
+ if (this.starting)
69
+ return this.starting;
70
+ this.starting = this.doStart();
71
+ try {
72
+ await this.starting;
73
+ this.error = '';
74
+ }
75
+ catch (e) {
76
+ this.error = errorMessage(e);
77
+ this.ctx.logger.error(`[java-bridge] ${this.error}`);
78
+ }
79
+ finally {
80
+ this.starting = null;
81
+ }
82
+ }
83
+ async doStart() {
84
+ const jar = this.bridgeJar;
85
+ if (!fs.existsSync(jar)) {
86
+ throw new Error(`找不到桥接 JAR:${jar}(把 onebot-bridge.jar 放回插件目录,或在设置里写绝对路径)`);
87
+ }
88
+ const pluginDir = this.javaPluginDir;
89
+ fs.mkdirSync(pluginDir, { recursive: true });
90
+ const javaPath = this.config.javaPath?.trim() || 'java';
91
+ const jvmArgs = listOf(this.config.jvmArgs);
92
+ const classpath = listOf(this.config.classpath)
93
+ .map(entry => (path.isAbsolute(entry) ? entry : path.resolve(entry)));
94
+ const logger = this.ctx.logger('java-bridge');
95
+ const bridge = new JniBridge({
96
+ javaPath,
97
+ jvmArgs,
98
+ bridgeJar: jar,
99
+ classpath,
100
+ callTimeout: Number(this.config.callTimeout) || 30_000,
101
+ logger,
102
+ });
103
+ bridge.on('action', (params) => { void this.handleAction(bridge, params); });
104
+ bridge.on('event', event => logger.debug('Java plugin emitted an event, ignored:', event));
105
+ bridge.on('exit', (code, signal) => {
106
+ if (this.bridge !== bridge)
107
+ return;
108
+ this.bridge = null;
109
+ this.plugins = [];
110
+ this.error = `Java 进程已退出(code=${code}, signal=${signal})`;
111
+ logger.warn(this.error);
112
+ });
113
+ this.bridge = bridge;
114
+ try {
115
+ await bridge.start();
116
+ if (this.disposed) {
117
+ await bridge.destroy();
118
+ return;
119
+ }
120
+ const initParams = {
121
+ dataPath: this.dataPath,
122
+ javaPluginPath: pluginDir,
123
+ adapterName: 'luckylillia-java-bridge',
124
+ javaPath,
125
+ jvmArgs,
126
+ bridgeJar: jar,
127
+ classpath,
128
+ };
129
+ const info = await bridge.call('init', initParams);
130
+ this.plugins = info?.plugins ?? [];
131
+ logger.info(`Java 插件桥接已就绪,已加载 ${this.plugins.length} 个 Java 插件`);
132
+ }
133
+ catch (e) {
134
+ if (this.bridge === bridge)
135
+ this.bridge = null;
136
+ this.plugins = [];
137
+ await bridge.destroy().catch(() => void 0);
138
+ throw e;
139
+ }
140
+ }
141
+ async stop() {
142
+ const bridge = this.bridge;
143
+ this.bridge = null;
144
+ this.plugins = [];
145
+ if (!bridge)
146
+ return;
147
+ try {
148
+ await bridge.destroy();
149
+ }
150
+ catch (e) {
151
+ this.ctx.logger.warn('[java-bridge] 停止 Java 进程时出错:', e);
152
+ }
153
+ }
154
+ async dispose() {
155
+ this.disposed = true;
156
+ await this.stop();
157
+ }
158
+ /** Stops the Java process and starts it again: rescans the plugin directory. */
159
+ async reload() {
160
+ if (this.disposed)
161
+ return this.status();
162
+ // A start still in flight would otherwise be joined instead of replaced
163
+ if (this.starting)
164
+ await this.starting.catch(() => void 0);
165
+ await this.stop();
166
+ await this.start();
167
+ return this.status();
168
+ }
169
+ /** Rescans the Java plugin directory. */
170
+ async listPlugins() {
171
+ if (!this.bridge?.running)
172
+ return this.plugins;
173
+ const info = await this.bridge.call('listPlugins', {});
174
+ this.plugins = info?.plugins ?? this.plugins;
175
+ return this.plugins;
176
+ }
177
+ async loadPlugin(pluginId) {
178
+ const bridge = this.requireBridge();
179
+ await bridge.call('loadPlugin', { pluginId });
180
+ return this.listPlugins();
181
+ }
182
+ async unloadPlugin(pluginId) {
183
+ const bridge = this.requireBridge();
184
+ await bridge.call('unloadPlugin', { pluginId });
185
+ return this.listPlugins();
186
+ }
187
+ /** The account actions go through: the configured one, else the first QQ account logged in. */
188
+ defaultBot() {
189
+ const bots = this.ctx.bots;
190
+ const sid = this.config.botSid?.trim();
191
+ if (sid)
192
+ return bots.get(sid) ?? bots.get(normalizeSid(sid));
193
+ for (const bot of bots) {
194
+ if (isNtqq(bot.platform))
195
+ return bot;
196
+ }
197
+ return;
198
+ }
199
+ /** `bot/session`: every neutral event, turned into the OneBot 11 shapes a Java plugin reads. */
200
+ handleSession(session) {
201
+ const bridge = this.bridge;
202
+ if (!bridge?.running) {
203
+ this.ctx.logger.debug(`[java-bridge] Java 桥接进程未运行,已忽略 ${session.type} 事件`);
204
+ return;
205
+ }
206
+ if (!isNtqq(session.platform)) {
207
+ this.ctx.logger.debug(`[java-bridge] 平台 ${session.platform} 不是 QQ 账号,已忽略 ${session.type} 事件`);
208
+ return;
209
+ }
210
+ // One Java process serves one account: the action calls it makes have no account to carry
211
+ if (session.bot.sid !== this.defaultBot()?.sid) {
212
+ this.ctx.logger.debug(`[java-bridge] 账号 ${session.bot.sid} 不是桥接账号,已忽略 ${session.type} 事件`);
213
+ return;
214
+ }
215
+ if (!this.config.reportSelfMessage && isSelf(session))
216
+ return;
217
+ let event;
218
+ try {
219
+ event = toOneBotEvent(session, { messageId: raw => this.messageShortId(raw) });
220
+ }
221
+ catch (e) {
222
+ this.ctx.logger.warn('[java-bridge] 转换中立事件时出错:', e);
223
+ return;
224
+ }
225
+ if (!event)
226
+ return;
227
+ try {
228
+ if (event.post_type === 'message' || event.post_type === 'message_sent') {
229
+ // A message with nothing in it (a recalled card and the like) is of no use to a Java plugin
230
+ if (!Array.isArray(event.message) || event.message.length === 0)
231
+ return;
232
+ this.ctx.logger.debug(`[java-bridge] 收到消息:${messageSummary(event)}`);
233
+ bridge.notify('onMessage', { event });
234
+ }
235
+ else {
236
+ bridge.notify('onEvent', { event });
237
+ }
238
+ }
239
+ catch (e) {
240
+ this.ctx.logger.warn('[java-bridge] 转发事件到 Java 失败:', e);
241
+ }
242
+ }
243
+ /** An action a Java plugin asked for, run as the OneBot 11 action of the same name. */
244
+ async handleAction(bridge, params) {
245
+ const { requestId, action } = params;
246
+ try {
247
+ const bot = this.defaultBot();
248
+ if (!bot)
249
+ throw new Error('没有已登录的 QQ 账号,Java 插件暂时无法调用 OneBot API');
250
+ const internal = ntqqInternal(bot);
251
+ if (!internal)
252
+ throw new Error(`账号 ${bot.sid} 不是 QQ 账号`);
253
+ const method = toInternalMethod(String(action ?? ''));
254
+ const handler = internal[method];
255
+ if (typeof handler !== 'function')
256
+ throw new Error(`不支持的 OneBot Action:${action}`);
257
+ const data = await handler.call(internal, params.params ?? {});
258
+ bridge.replyAction(requestId, true, data);
259
+ }
260
+ catch (e) {
261
+ bridge.replyAction(requestId, false, undefined, errorMessage(e));
262
+ }
263
+ }
264
+ /** `<chatType>|<peerUid>|<msgSeq>` as the short id OneBot 11 events carry. */
265
+ messageShortId(raw) {
266
+ if (!raw.includes('|'))
267
+ return;
268
+ const [, peerUid, seq] = raw.split('|');
269
+ const store = this.store();
270
+ const message = store?.getMsgBySeq?.(peerUid, Number(seq));
271
+ if (!message)
272
+ return;
273
+ try {
274
+ return store?.createMsgShortId?.(message);
275
+ }
276
+ catch {
277
+ return;
278
+ }
279
+ }
280
+ store() {
281
+ try {
282
+ return this.ctx.store;
283
+ }
284
+ catch {
285
+ return;
286
+ }
287
+ }
288
+ requireBridge() {
289
+ if (!this.bridge?.running)
290
+ throw new Error('Java 桥接进程未运行,先重载 Java 进程');
291
+ return this.bridge;
292
+ }
293
+ accounts() {
294
+ const accounts = [];
295
+ try {
296
+ for (const bot of this.ctx.bots) {
297
+ if (!isNtqq(bot.platform))
298
+ continue;
299
+ accounts.push({ sid: bot.sid, platform: bot.platform, selfId: bot.selfId, name: bot.user?.name });
300
+ }
301
+ }
302
+ catch {
303
+ // bots not ready yet
304
+ }
305
+ return accounts;
306
+ }
307
+ }
308
+ /** 「群 123456,发送者 10001」加 CQ 码内容;过长的截断,免得 debug 日志刷屏。 */
309
+ function messageSummary(event) {
310
+ const scope = event.message_type === 'group'
311
+ ? `群 ${event.group_id},发送者 ${event.user_id}`
312
+ : `私聊 ${event.user_id}`;
313
+ const raw = String(event.raw_message ?? '');
314
+ return `${scope}:${raw.length > 200 ? `${raw.slice(0, 200)}…` : raw}`;
315
+ }
316
+ function isSelf(session) {
317
+ const sender = session.event.user?.id;
318
+ return sender != null && String(sender) === String(session.selfId);
319
+ }
320
+ /** NTQQ 的平台名是 ntqq;luckylillia 是它改名前的旧键,宿主仍按 ntqq 处理。 */
321
+ function isNtqq(platform) {
322
+ return platform === 'ntqq' || platform === 'luckylillia';
323
+ }
324
+ /** `luckylillia:12345` 是旧写法,换成 `ntqq:12345` 再查一次。 */
325
+ function normalizeSid(sid) {
326
+ return sid.startsWith('luckylillia:') ? `ntqq:${sid.slice('luckylillia:'.length)}` : sid;
327
+ }
328
+ /** QQ 账号(ntqq,旧键 luckylillia)的 OneBot 11 接口;其它平台没有。 */
329
+ function ntqqInternal(bot) {
330
+ return isNtqq(bot.platform) ? bot.internal : undefined;
331
+ }
332
+ function listOf(value) {
333
+ if (Array.isArray(value))
334
+ return value.map(String).filter(entry => entry.length > 0);
335
+ if (typeof value === 'string')
336
+ return value.split(/\s+/).filter(entry => entry.length > 0);
337
+ return [];
338
+ }
339
+ function errorMessage(error) {
340
+ return error instanceof Error ? error.message : String(error);
341
+ }
@@ -0,0 +1,25 @@
1
+ import { Schema } from '@luckylillia/plugin-sdk';
2
+ export const DEFAULT_CONFIG = {
3
+ javaPath: 'java',
4
+ jvmArgs: ['-Xmx256m'],
5
+ bridgeJar: 'onebot-bridge.jar',
6
+ javaPluginDir: 'java-plugins',
7
+ classpath: [],
8
+ callTimeout: 30_000,
9
+ reportSelfMessage: false,
10
+ botSid: '',
11
+ };
12
+ // Mirrors what the bridge used to be as part of the OneBot adapter's settings (`ob11.jni`): the Java plugin
13
+ // directory stays under the bot's data directory, so an upgrade finds the jars where they always were
14
+ export const Config = Schema.object({
15
+ javaPath: Schema.string().default('java').description('java 可执行文件的路径,装了 JDK / JRE 且加进了 PATH 就留 java'),
16
+ jvmArgs: Schema.array(Schema.string()).default(['-Xmx256m']).description('JVM 启动参数'),
17
+ bridgeJar: Schema.string().default('onebot-bridge.jar')
18
+ .description('桥接 JAR:相对路径先找插件目录、再找 Bot 的运行目录;留空就是自带的那份'),
19
+ javaPluginDir: Schema.string().default('java-plugins')
20
+ .description('Java 插件(.jar)目录:相对路径基于 data 目录;留空就是 data/java-plugins'),
21
+ classpath: Schema.array(Schema.string()).default([]).description('额外的 classpath(目录或 jar)'),
22
+ callTimeout: Schema.natural().role('ms').min(1).default(30_000).description('单次调用的超时时间'),
23
+ reportSelfMessage: Schema.boolean().default(false).description('把自己发送的消息也发给 Java 插件'),
24
+ botSid: Schema.string().default('').description('只桥接这个账号(ntqq:QQ号;旧写法 luckylillia:QQ号 也认);留空用第一个已登录的 QQ 账号,也只桥接它'),
25
+ });
Binary file
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@cindifind/java-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Runs Java plugins in their own process over OneBot 11 events and actions",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "files": [
8
+ "lib",
9
+ "webui",
10
+ "onebot-bridge.jar"
11
+ ],
12
+ "keywords": [
13
+ "luckylillia-plugin",
14
+ "onebot",
15
+ "onebot11",
16
+ "java",
17
+ "qq"
18
+ ],
19
+ "author": "Cindifind",
20
+ "license": "GPL-2.0",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/Cindifind/birdge-java.git"
24
+ },
25
+ "homepage": "https://github.com/Cindifind/birdge-java",
26
+ "bugs": {
27
+ "url": "https://github.com/Cindifind/birdge-java/issues"
28
+ },
29
+ "engines": {
30
+ "node": ">=22.15"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "registry": "https://registry.npmjs.org/"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p .",
38
+ "dev": "tsc -p . --watch",
39
+ "test": "vitest run",
40
+ "prepack": "npm run build"
41
+ },
42
+ "peerDependencies": {
43
+ "@luckylillia/plugin-sdk": "^1.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@luckylillia/plugin-sdk": "file:../LuckyLilliaBot/packages/plugin-sdk",
47
+ "@satorijs/element": "^3.2.0",
48
+ "@satorijs/protocol": "^1.7.0",
49
+ "@types/node": "^24.0.0",
50
+ "cordis": "4.0.0-rc.11",
51
+ "schemastery": "^3.18.0",
52
+ "typescript": "^7.0.2",
53
+ "vitest": "^4.1.11"
54
+ },
55
+ "llbot": {
56
+ "title": "Java 插件桥接",
57
+ "description": {
58
+ "zh": "让 Java 写的插件跑在独立的 Java 进程里,收发 OneBot 11 的事件、调用 OneBot 11 的 API",
59
+ "en": "Runs Java plugins in their own process over OneBot 11 events and actions"
60
+ },
61
+ "category": "tool",
62
+ "icon": "terminal",
63
+ "service": {
64
+ "required": [
65
+ "bots"
66
+ ],
67
+ "optional": [
68
+ "webuiServer"
69
+ ]
70
+ },
71
+ "webui": "webui/index.js"
72
+ }
73
+ }
package/webui/index.js ADDED
@@ -0,0 +1,145 @@
1
+ // Plain ES module, no build step: react and the SDK come from the WebUI's import map.
2
+ // The page keeps the settings form the WebUI generates from Config, plus what the Java process is doing.
3
+ import { createElement as h, useCallback, useEffect, useState } from 'react'
4
+ import { SchemaSettings, usePluginContext } from '@luckylillia/plugin-sdk/webui'
5
+
6
+ const api = '/api/java-bridge'
7
+
8
+ function useStatus() {
9
+ const ctx = usePluginContext()
10
+ const [status, setStatus] = useState(null)
11
+ const load = useCallback(() => {
12
+ return ctx.api(`${api}/status`)
13
+ .then(setStatus)
14
+ .catch(error => ctx.toast(error.message, 'error'))
15
+ }, [ctx])
16
+ useEffect(() => {
17
+ load()
18
+ const timer = setInterval(load, 5000)
19
+ return () => clearInterval(timer)
20
+ }, [load])
21
+ return [status, load]
22
+ }
23
+
24
+ function useAction(done) {
25
+ const ctx = usePluginContext()
26
+ const [busy, setBusy] = useState('')
27
+ const run = useCallback((key, path, body) => {
28
+ setBusy(key)
29
+ return ctx.api(path, { method: 'POST', body })
30
+ .then(() => done())
31
+ .catch(error => ctx.toast(error.message, 'error'))
32
+ .finally(() => setBusy(''))
33
+ }, [ctx, done])
34
+ return [busy, run]
35
+ }
36
+
37
+ function Row({ label, children }) {
38
+ return h('div', { style: { display: 'grid', gridTemplateColumns: '7em 1fr', gap: 12, alignItems: 'baseline', fontSize: 13 } },
39
+ h('span', { className: 'text-theme-muted' }, label),
40
+ h('div', { className: 'text-theme', style: { overflowWrap: 'anywhere', minWidth: 0 } }, children),
41
+ )
42
+ }
43
+
44
+ function button(label, onClick, disabled) {
45
+ return h('button', {
46
+ type: 'button',
47
+ className: 'btn-glass',
48
+ disabled,
49
+ onClick,
50
+ style: { padding: '6px 14px', fontSize: 13, fontWeight: 500 },
51
+ }, label)
52
+ }
53
+
54
+ function PluginRow({ plugin, busy, run }) {
55
+ const toggle = () => run(plugin.enabled ? `unload:${plugin.id}` : `load:${plugin.id}`,
56
+ `${api}/plugins/${plugin.enabled ? 'unload' : 'load'}`, { id: plugin.id })
57
+ return h('div', {
58
+ style: {
59
+ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0',
60
+ borderTop: '1px solid var(--hairline)',
61
+ },
62
+ },
63
+ h('div', { style: { flex: 1, minWidth: 0 } },
64
+ h('div', { className: 'text-theme', style: { fontSize: 14, fontWeight: 500 } },
65
+ plugin.name || plugin.id,
66
+ plugin.version && h('span', { className: 'text-theme-muted', style: { fontSize: 12, marginLeft: 8 } }, `v${plugin.version}`)),
67
+ h('div', { className: 'text-theme-secondary', style: { fontSize: 12, marginTop: 2 } },
68
+ plugin.description || plugin.id),
69
+ ),
70
+ h('span', {
71
+ className: 'text-theme-muted',
72
+ style: { fontSize: 12 },
73
+ }, plugin.enabled ? '已加载' : '未加载'),
74
+ button(plugin.enabled ? '卸载' : '加载', toggle, Boolean(busy)),
75
+ )
76
+ }
77
+
78
+ function RuntimeCard({ status, busy, run }) {
79
+ if (!status) {
80
+ return h('div', { className: 'card', style: { padding: 24 } }, h('span', { className: 'text-theme-secondary' }, '加载中…'))
81
+ }
82
+
83
+ const state = status.running ? '运行中' : status.starting ? '启动中…' : '未运行'
84
+ const accounts = status.bots.length
85
+ ? status.bots.map(bot => `${bot.name || bot.selfId}(${bot.sid})`).join('、')
86
+ : '没有已登录的账号'
87
+
88
+ return h('div', { className: 'card', style: { padding: 24, display: 'grid', gap: 16 } },
89
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
90
+ h('h3', { className: 'text-theme', style: { flex: 1, margin: 0, fontSize: 17, fontWeight: 600 } }, 'Java 进程'),
91
+ button('刷新', () => run('status', `${api}/status`), Boolean(busy)),
92
+ button('重载 Java 进程', () => run('reload', `${api}/reload`), Boolean(busy)),
93
+ ),
94
+ status.error && h('div', {
95
+ style: {
96
+ fontSize: 13, padding: '10px 12px', borderRadius: 10,
97
+ background: 'rgb(239 68 68 / 0.1)', color: 'rgb(248 113 113)',
98
+ },
99
+ }, status.error),
100
+ h(Row, { label: '状态' }, state),
101
+ h(Row, { label: '桥接 JAR' },
102
+ h('code', null, status.bridgeJar),
103
+ status.bridgeJarExists ? null : h('span', { style: { color: 'rgb(248 113 113)', marginLeft: 8 } }, '(文件不存在)')),
104
+ h(Row, { label: '插件目录' },
105
+ h('code', null, status.javaPluginDir),
106
+ h('div', { className: 'text-theme-muted', style: { fontSize: 12, marginTop: 4 } },
107
+ '把 Java 插件的 .jar 放进这个目录,再点「重载 Java 进程」')),
108
+ h(Row, { label: 'Java' }, h('code', null, status.javaPath)),
109
+ h(Row, { label: 'QQ 账号' }, accounts),
110
+ h('div', null,
111
+ h('div', { className: 'text-theme-secondary', style: { fontSize: 13, fontWeight: 500, marginBottom: 4 } },
112
+ `Java 插件(${status.plugins.length})`),
113
+ status.plugins.length
114
+ ? status.plugins.map(plugin => h(PluginRow, { key: plugin.id, plugin, busy, run }))
115
+ : h('div', { className: 'text-theme-muted', style: { fontSize: 13, paddingTop: 8 } },
116
+ status.running ? '目录里还没有 Java 插件' : 'Java 进程没有运行,插件列表不可用'),
117
+ ),
118
+ )
119
+ }
120
+
121
+ function JavaBridgePage() {
122
+ const [status, load] = useStatus()
123
+ const [busy, run] = useAction(load)
124
+ return h('div', { style: { display: 'grid', gap: 16 } },
125
+ h(SchemaSettings, {
126
+ sections: [
127
+ { title: '进程', fields: ['javaPath', 'jvmArgs', 'callTimeout'] },
128
+ { title: '文件', fields: ['bridgeJar', 'javaPluginDir', 'classpath'], collapsed: true },
129
+ { title: '事件', fields: ['botSid', 'reportSelfMessage'], collapsed: true },
130
+ ],
131
+ }),
132
+ h(RuntimeCard, { status, busy, run }),
133
+ )
134
+ }
135
+
136
+ export default function apply(ctx) {
137
+ ctx.page({
138
+ id: 'java-bridge',
139
+ title: 'Java 插件桥接',
140
+ icon: 'terminal',
141
+ component: JavaBridgePage,
142
+ order: 15,
143
+ settings: true,
144
+ })
145
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.