@sonicloud/dsh-sonicloud-device 0.0.0-stage → 0.1.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/CHANGELOG.md +29 -0
- package/CHANGELOG.zh.md +29 -0
- package/LICENSE +25 -0
- package/README.md +134 -2
- package/cordis.patch.yml +3 -0
- package/dist/build.json +5 -0
- package/dist/client.js +20621 -0
- package/docs/contributing/development.md +200 -0
- package/docs/specs/ci-cd.md +126 -0
- package/docs/specs/mouse-settings.md +255 -0
- package/docs/specs/smart-mouse-plugin.md +239 -0
- package/native/COPYING.LGPLv2.1 +502 -0
- package/native/LICENSE.hidapi-bsd +26 -0
- package/native/README.md +15 -0
- package/native/SOURCE.json +16 -0
- package/native/THIRD_PARTY_LICENSES.txt +69 -0
- package/native/darwin-arm64/README.md +71 -0
- package/native/darwin-arm64/libavcodec.62.28.102.dylib +0 -0
- package/native/darwin-arm64/libavcodec.62.dylib +0 -0
- package/native/darwin-arm64/libavutil.60.26.102.dylib +0 -0
- package/native/darwin-arm64/libavutil.60.dylib +0 -0
- package/native/darwin-arm64/libuMouseSdk.0.4.20.dylib +0 -0
- package/native/darwin-arm64/libuMouseSdk.0.dylib +0 -0
- package/native/darwin-arm64/libuMouseSdk.dylib +0 -0
- package/native/desktop/CompatibilityPolicy.swift +17 -0
- package/native/desktop/VoicePanel.cs +197 -0
- package/native/desktop/VoicePanel.swift +322 -0
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/Info.plist +10 -0
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
- package/native/desktop/windows.ps1 +9 -0
- package/native/win32-x64/README.md +70 -0
- package/native/win32-x64/avcodec-58.dll +0 -0
- package/native/win32-x64/avutil-56.dll +0 -0
- package/native/win32-x64/msvcp140.dll +0 -0
- package/native/win32-x64/uMouseSdk.dll +0 -0
- package/native/win32-x64/vcruntime140.dll +0 -0
- package/native/win32-x64/vcruntime140_1.dll +0 -0
- package/package.json +74 -4
- package/src/asr/auth.mjs +80 -0
- package/src/asr/config.mjs +6 -0
- package/src/asr/languages.mjs +28 -0
- package/src/asr/stream.mjs +149 -0
- package/src/client/assets/contact-wechat.jpg +0 -0
- package/src/client/assets/sonicloud.png +0 -0
- package/src/client/assets/sonicloud.svg +3 -0
- package/src/desktop/presentation.mjs +87 -0
- package/src/devices/actions.mjs +46 -0
- package/src/devices/config.mjs +9 -0
- package/src/devices/diagnostics.mjs +52 -0
- package/src/devices/manager.mjs +335 -0
- package/src/devices/native-worker.mjs +64 -0
- package/src/devices/native.mjs +86 -0
- package/src/devices/queue.mjs +32 -0
- package/src/devices/recognition.mjs +23 -0
- package/src/devices/store.mjs +44 -0
- package/src/devices/translate.mjs +44 -0
- package/src/host/ai-conversation.mjs +83 -0
- package/src/host/index.mjs +96 -0
- package/src/host/store.mjs +24 -0
- package/src/shared/devices.mjs +69 -0
- package/src/shared/languages.mjs +111 -0
- package/src/shared/mouse-settings.mjs +22 -0
- package/src/shared/remote.mjs +55 -0
- package/src/shared/transcript.mjs +16 -0
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { AsyncQueue, PcmPackets } from './queue.mjs';
|
|
3
|
+
import { DeviceStore } from './store.mjs';
|
|
4
|
+
import { isStableSn, languageKey, searchAddress } from '../shared/devices.mjs';
|
|
5
|
+
import { recognitionQuery, formatTranscript, DEFAULT_LANGUAGES } from './recognition.mjs';
|
|
6
|
+
import { Transcript } from '../shared/transcript.mjs';
|
|
7
|
+
import { MouseSdk } from './native.mjs';
|
|
8
|
+
import { systemAction } from './actions.mjs';
|
|
9
|
+
import { translateText } from './translate.mjs';
|
|
10
|
+
|
|
11
|
+
const VOICE = new Set(['voice_input', 'translate', 'speechSearch', 'ai_input']);
|
|
12
|
+
export class DeviceManager {
|
|
13
|
+
constructor({ credentials, recognize, prepare = async () => undefined, sdk = new MouseSdk(), action = systemAction, translate = translateText, desktop, aiConversation, config = {} }) {
|
|
14
|
+
Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, aiConversation, config });
|
|
15
|
+
this.store = new DeviceStore(credentials);
|
|
16
|
+
this.devices = new Map(); this.clients = new Set(); this.pressed = new Map(); this.pending = Promise.resolve();
|
|
17
|
+
this.status = '尚未连接 SDK'; this.disposed = false;
|
|
18
|
+
this.languages = config.recognitionLanguages ?? DEFAULT_LANGUAGES;
|
|
19
|
+
this.dpiLevels = config.dpiLevels ?? { '800': 21, '1200': 32, '1600': 42, '2400': 63 };
|
|
20
|
+
this.dpiReportLevels = config.dpiReportLevels ?? { '800': 0, '1200': 1, '1600': 2, '2400': 3 };
|
|
21
|
+
this.onEvent = event => {
|
|
22
|
+
// Audio is copied in the worker. Process it synchronously in IPC order; commands are serialized separately.
|
|
23
|
+
if (event.type === 'audio') { this.audio(event); return; }
|
|
24
|
+
this.pending = this.pending.then(() => this.event(event)).catch(() => this.publish({ type: 'notice', message: '设备事件处理失败,请重连设备' }));
|
|
25
|
+
};
|
|
26
|
+
this.onFault = message => {
|
|
27
|
+
this.status = message; this.cancel();
|
|
28
|
+
this.devices.clear(); this.pressed.clear(); this.snapshot();
|
|
29
|
+
};
|
|
30
|
+
if (desktop) {
|
|
31
|
+
desktop.onCancel = id => this.cancel(id);
|
|
32
|
+
desktop.onFault = () => this.cancel(undefined, '桌面语音浮层已断开,请重新触发');
|
|
33
|
+
}
|
|
34
|
+
sdk.on('event', this.onEvent); sdk.on('fault', this.onFault);
|
|
35
|
+
}
|
|
36
|
+
async start() {
|
|
37
|
+
if (this.started) return this.started;
|
|
38
|
+
this.started = (async () => {
|
|
39
|
+
try { this.desktop?.start?.(); } catch { /* Key press reports unsupported native presentation. */ }
|
|
40
|
+
try { await this.sdk.start(); this.status = this.devices.size ? '设备已连接' : '设备服务已启动,正在查找智能鼠标…'; }
|
|
41
|
+
catch (error) { this.status = error.message; }
|
|
42
|
+
this.snapshot();
|
|
43
|
+
})();
|
|
44
|
+
return this.started;
|
|
45
|
+
}
|
|
46
|
+
publish(event) {
|
|
47
|
+
this.desktop?.event(event);
|
|
48
|
+
if (this.desktop && !['devices', 'notice'].includes(event.type)) return;
|
|
49
|
+
for (const queue of this.clients) {
|
|
50
|
+
try { queue.push(event); } catch { queue.end(true); this.clients.delete(queue); if (!this.desktop) this.cancel(); }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
view() {
|
|
54
|
+
return {
|
|
55
|
+
status: this.status,
|
|
56
|
+
devices: [...this.devices.values()].map(({ connectionId, ...device }) => structuredClone(device)),
|
|
57
|
+
recognitionLanguages: this.languages.map(languageKey), translationReady: true,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
snapshot() { this.publish({ type: 'devices', ...this.view() }); }
|
|
61
|
+
async *watch(clientId, signal) {
|
|
62
|
+
if (!this.desktop && this.owner) { yield { type: 'notice', message: '智能鼠标已由另一个窗口接管' }; return; }
|
|
63
|
+
const queue = new AsyncQueue(256); if (!this.desktop) this.owner = clientId; this.clients.add(queue);
|
|
64
|
+
const abort = () => queue.end(true);
|
|
65
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
66
|
+
try {
|
|
67
|
+
signal.throwIfAborted(); await this.start();
|
|
68
|
+
queue.push({ type: 'devices', ...this.view() });
|
|
69
|
+
yield* queue;
|
|
70
|
+
} finally {
|
|
71
|
+
signal.removeEventListener('abort', abort); queue.end(true); this.clients.delete(queue);
|
|
72
|
+
if (this.owner === clientId) { this.owner = undefined; this.cancel(); }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async event(event) {
|
|
76
|
+
if (this.disposed) return;
|
|
77
|
+
const id = event.id;
|
|
78
|
+
if (event.type === 'diagnostic') {
|
|
79
|
+
if (!this.devices.size) { this.status = event.message; this.snapshot(); }
|
|
80
|
+
} else if (event.type === 'connected') {
|
|
81
|
+
const previous = this.devices.get(id);
|
|
82
|
+
if (previous) this.cancelFor(id);
|
|
83
|
+
const stable = isStableSn(id);
|
|
84
|
+
const category = event.deviceType ?? 'smart-mouse';
|
|
85
|
+
const saved = stable && category === 'smart-mouse' ? await this.store.get(id) : null;
|
|
86
|
+
this.devices.set(id, { id, sn: stable ? id : '', type: category, name: event.name || (category === 'smart-mouse' ? '智能鼠标' : '设备'),
|
|
87
|
+
connection: event.mode === 1 ? 'ble' : 'usb', connectionId: randomUUID(), battery: null,
|
|
88
|
+
identityConfirmed: stable, dpiState: 'unknown', ...saved });
|
|
89
|
+
this.clearPressed(id);
|
|
90
|
+
this.status = '设备已连接';
|
|
91
|
+
if (saved?.revision > 0) await this.applyDpi(this.devices.get(id));
|
|
92
|
+
this.snapshot();
|
|
93
|
+
} else if (event.type === 'disconnected') {
|
|
94
|
+
const device = this.devices.get(id);
|
|
95
|
+
if (!device || device.connection !== (event.mode === 1 ? 'ble' : 'usb')) return;
|
|
96
|
+
this.cancelFor(id, '设备已断开,语音已取消'); this.devices.delete(id); this.clearPressed(id);
|
|
97
|
+
if (!this.devices.size) this.status = '设备已断开,正在重新查找智能鼠标…';
|
|
98
|
+
this.snapshot();
|
|
99
|
+
} else if (event.type === 'overflow') this.cancelFor(id, '鼠标音频处理过慢,本次识别已停止');
|
|
100
|
+
else if (event.type === 'warning') this.publish({ type: 'notice', message: event.message });
|
|
101
|
+
else if (event.type === 'message') {
|
|
102
|
+
const device = this.devices.get(id), message = event.message;
|
|
103
|
+
if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || '鼠标连接异常' }); return; }
|
|
104
|
+
if (message.type === 'queueOverflow') { this.cancel(undefined, '鼠标音频丢失,请重新录音'); return; }
|
|
105
|
+
if (!device) return;
|
|
106
|
+
if (message.type === 'deviceInfo') {
|
|
107
|
+
if (isStableSn(message.sn) && message.sn !== device.sn) {
|
|
108
|
+
// Re-key only a temporary identity, never merge two real devices.
|
|
109
|
+
if (device.identityConfirmed || this.devices.has(message.sn)) {
|
|
110
|
+
device.identityConfirmed = false; this.cancelFor(id, '设备 SN 冲突,请重连');
|
|
111
|
+
} else {
|
|
112
|
+
this.devices.delete(id); device.sn = message.sn; device.identityConfirmed = true;
|
|
113
|
+
if (device.type === 'smart-mouse') Object.assign(device, await this.store.get(message.sn)); this.devices.set(id, device);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (Number.isFinite(message.battery) && message.battery >= 0 && message.battery <= 100) device.battery = message.battery;
|
|
117
|
+
this.snapshot();
|
|
118
|
+
} else if (message.type === 'dpiChanged') {
|
|
119
|
+
if (!Number.isInteger(message.level) || message.level < 0 || message.level > 255) return;
|
|
120
|
+
device.dpiRaw = message.level;
|
|
121
|
+
// Hardware broadcasts use a separate mapping from software command bytes.
|
|
122
|
+
const matches = Object.entries(this.dpiReportLevels).filter(([, level]) => level === message.level);
|
|
123
|
+
if (matches.length === 1 && device.type === 'smart-mouse' && device.identityConfirmed) {
|
|
124
|
+
Object.assign(device, await this.store.reportDpi(device.sn, matches[0][0]));
|
|
125
|
+
device.dpiState = 'reported';
|
|
126
|
+
} else if (device.dpiState === 'reported') device.dpiState = 'unknown';
|
|
127
|
+
this.snapshot();
|
|
128
|
+
} else if (message.type === 'keyEvent') await this.key(device, message);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
clearPressed(id) { for (const key of this.pressed.keys()) if (key.startsWith(id + ':')) this.pressed.delete(key); }
|
|
132
|
+
save(sn, revision, preferences) {
|
|
133
|
+
// Keep UI saves and hardware reports in order so neither overwrites newer state.
|
|
134
|
+
const saving = this.pending.then(() => this.savePreferences(sn, revision, preferences));
|
|
135
|
+
this.pending = saving.catch(() => {});
|
|
136
|
+
return saving;
|
|
137
|
+
}
|
|
138
|
+
async savePreferences(sn, revision, preferences) {
|
|
139
|
+
const device = [...this.devices.values()].find(item => item.sn === sn && item.identityConfirmed);
|
|
140
|
+
if (!device || device.type !== 'smart-mouse') throw new Error('设备已离线、SN 未确认或不支持此配置');
|
|
141
|
+
const connectionId = device.connectionId;
|
|
142
|
+
const dpiChanged = preferences.dpi !== device.preferences.dpi || device.dpiState === 'failed';
|
|
143
|
+
const saved = await this.store.save(sn, revision, preferences);
|
|
144
|
+
if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: '配置已保存,设备离线后需重连应用' }; }
|
|
145
|
+
Object.assign(device, saved);
|
|
146
|
+
let message = '已保存';
|
|
147
|
+
if (dpiChanged) {
|
|
148
|
+
message = '配置已保存,' + await this.applyDpi(device);
|
|
149
|
+
}
|
|
150
|
+
this.snapshot(); return { ...saved, message };
|
|
151
|
+
}
|
|
152
|
+
async applyDpi(device) {
|
|
153
|
+
const level = this.dpiLevels[device.preferences.dpi];
|
|
154
|
+
try {
|
|
155
|
+
if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error('此固件未配置 DPI 档位映射');
|
|
156
|
+
if (await this.sdk.dpi(device.id, level) !== 1) throw new Error('DPI 下发失败');
|
|
157
|
+
device.dpiState = 'sent'; return 'DPI 指令已下发(设备不返回生效确认)';
|
|
158
|
+
} catch (error) { device.dpiState = 'failed'; return error.message; }
|
|
159
|
+
}
|
|
160
|
+
async key(device, event) {
|
|
161
|
+
if (device.type !== 'smart-mouse' || (!this.owner && !this.desktop)) return;
|
|
162
|
+
if (!device.identityConfirmed) {
|
|
163
|
+
if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: '设备身份未确认,请重新连接鼠标' });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const key = `${device.id}:${event.key}:${event.index ?? 0}`;
|
|
167
|
+
if (event.action === 'up') {
|
|
168
|
+
const pressed = this.pressed.get(key); this.pressed.delete(key);
|
|
169
|
+
if (this.run?.key === key) this.release(this.run);
|
|
170
|
+
else if (pressed && event.key === 'm' && !VOICE.has(pressed.mAction)) {
|
|
171
|
+
void this.execute(pressed.mAction, pressed.linkUrl);
|
|
172
|
+
}
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
// Click/hold follow the same physical press and must not create another conversation.
|
|
176
|
+
if (event.action !== 'down' || !['speech', 'translation', 'm', 'ai'].includes(event.key) || this.pressed.has(key)) return;
|
|
177
|
+
this.pressed.set(key, structuredClone(device.preferences));
|
|
178
|
+
const action = event.key === 'ai' ? 'ai_input' : event.key === 'm' ? device.preferences.mAction : event.key === 'translation' ? 'translate' : device.preferences.speechAction;
|
|
179
|
+
if (!VOICE.has(action)) return;
|
|
180
|
+
if (this.run) { this.publish({ type: 'notice', message: '其他语音会话正在进行,请稍后重试' }); return; }
|
|
181
|
+
let query;
|
|
182
|
+
try {
|
|
183
|
+
query = recognitionQuery(device.preferences, action, this.languages);
|
|
184
|
+
} catch (error) { this.publish({ type: 'notice', message: error.message }); return; }
|
|
185
|
+
const run = {
|
|
186
|
+
id: randomUUID(), sn: device.sn, deviceId: device.id, connectionId: device.connectionId,
|
|
187
|
+
key, action, preferences: structuredClone(device.preferences), query, queue: new AsyncQueue(100),
|
|
188
|
+
lifetime: new AbortController(), transcript: new Transcript(), released: false, started: false, bytes: 0,
|
|
189
|
+
};
|
|
190
|
+
run.packets = new PcmPackets(chunk => run.queue.push(chunk));
|
|
191
|
+
this.run = run;
|
|
192
|
+
if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, '界面未响应,请重新打开宿主窗口'), 5000);
|
|
193
|
+
run.durationTimer = setTimeout(() => this.release(run), 600000);
|
|
194
|
+
// Opening the app/client must not block key-up or device-disconnect events.
|
|
195
|
+
if (action === 'ai_input') void this.begin(run, device);
|
|
196
|
+
else await this.begin(run, device);
|
|
197
|
+
}
|
|
198
|
+
async prepareAi(run) {
|
|
199
|
+
try {
|
|
200
|
+
if (!this.aiConversation || !this.desktop) throw new Error('AI 对话功能不可用,请重新加载插件');
|
|
201
|
+
await this.action('openAi');
|
|
202
|
+
run.lifetime.signal.throwIfAborted();
|
|
203
|
+
await this.aiConversation.prepare(run);
|
|
204
|
+
return {};
|
|
205
|
+
} catch (error) { return { error }; }
|
|
206
|
+
}
|
|
207
|
+
async begin(run, device) {
|
|
208
|
+
try {
|
|
209
|
+
if (run.action === 'ai_input') run.aiReady = this.prepareAi(run);
|
|
210
|
+
if (run.action === 'ai_input' && !this.desktop) throw new Error('AI 对话需要桌面语音浮层');
|
|
211
|
+
if (this.desktop) await this.desktop.begin(run);
|
|
212
|
+
if (this.run !== run || run.closing) return;
|
|
213
|
+
run.service = await this.prepare();
|
|
214
|
+
if (this.run !== run || run.closing) return;
|
|
215
|
+
if (await this.sdk.source(device.id) !== 1) throw new Error('无法选定鼠标音频源');
|
|
216
|
+
if (this.run !== run || run.closing) return;
|
|
217
|
+
if (this.desktop) { run.started = true; void this.process(run); }
|
|
218
|
+
else this.publish({ type: 'request', sessionId: run.id, sn: run.sn, action: run.action });
|
|
219
|
+
} catch (error) { this.fail(run, error.message); }
|
|
220
|
+
}
|
|
221
|
+
async execute(action, value) {
|
|
222
|
+
try { await this.action(action === 'openWebUrl' ? 'openUrl' : action, value); }
|
|
223
|
+
catch (error) { this.publish({ type: 'notice', message: error.message }); }
|
|
224
|
+
}
|
|
225
|
+
audio(event) {
|
|
226
|
+
const run = this.run;
|
|
227
|
+
if (!run || run.deviceId !== event.id || run.audioEnded || this.devices.get(event.id)?.connectionId !== run.connectionId) return;
|
|
228
|
+
try {
|
|
229
|
+
const buffer = Buffer.from(event.data, 'base64');
|
|
230
|
+
if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error('鼠标音频数据无效');
|
|
231
|
+
run.bytes += buffer.length;
|
|
232
|
+
if (!run.ready && run.bytes > 320000) throw new Error('连接等待的鼠标音频超过 10 秒,请重试');
|
|
233
|
+
run.packets.write(buffer);
|
|
234
|
+
} catch (error) { this.fail(run, error.message); }
|
|
235
|
+
}
|
|
236
|
+
accept(clientId, sessionId) {
|
|
237
|
+
this.assertOwner(clientId);
|
|
238
|
+
const run = this.run;
|
|
239
|
+
if (!run || run.closing || run.id !== sessionId || run.started) return false;
|
|
240
|
+
run.started = true; clearTimeout(run.captureTimer);
|
|
241
|
+
void this.process(run); return true;
|
|
242
|
+
}
|
|
243
|
+
assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error('此窗口未接管智能鼠标'); }
|
|
244
|
+
release(run) {
|
|
245
|
+
if (this.run !== run || run.released) return;
|
|
246
|
+
run.released = true;
|
|
247
|
+
this.publish({ type: 'phase', sessionId: run.id, phase: 'finishing' });
|
|
248
|
+
// Allow the SDK's decoded tail to arrive; the owner remains locked throughout.
|
|
249
|
+
run.tailTimer = setTimeout(() => {
|
|
250
|
+
if (this.run !== run || run.closing) return;
|
|
251
|
+
try { run.audioEnded = true; run.packets.flush(); run.queue.end(); }
|
|
252
|
+
catch (error) { this.fail(run, error.message); }
|
|
253
|
+
}, this.config.tailMs ?? 150);
|
|
254
|
+
run.uploadTimer = setTimeout(() => this.fail(run, '音频上传结束超时'), 15000);
|
|
255
|
+
}
|
|
256
|
+
async process(run) {
|
|
257
|
+
try {
|
|
258
|
+
const events = this.recognize({ sn: run.sn, service: run.service, query: run.query, uplink: run.queue, signal: run.lifetime.signal });
|
|
259
|
+
let complete = false;
|
|
260
|
+
for await (const event of events) {
|
|
261
|
+
if (this.run !== run || run.closing) return;
|
|
262
|
+
if (event.type === 'error') throw new Error(event.message);
|
|
263
|
+
if (event.type === 'ready') { run.ready = true; this.publish({ type: 'phase', sessionId: run.id, phase: run.released ? 'finishing' : 'recording' }); }
|
|
264
|
+
if (event.type === 'finishing') clearTimeout(run.uploadTimer);
|
|
265
|
+
if (event.type === 'warning') this.publish({ type: 'notice', message: event.message });
|
|
266
|
+
if (event.type === 'transcript') {
|
|
267
|
+
run.transcript.update(event);
|
|
268
|
+
this.publish({ type: 'preview', sessionId: run.id, text: formatTranscript(run.transcript.preview(), run.preferences, run.action) });
|
|
269
|
+
}
|
|
270
|
+
if (event.type === 'complete') { complete = true; break; }
|
|
271
|
+
}
|
|
272
|
+
if (this.run !== run || run.closing) return;
|
|
273
|
+
if (!complete || !run.released) throw new Error('ASR 连接中断,识别结果未完成');
|
|
274
|
+
let text = formatTranscript(run.transcript.finalText(), run.preferences, run.action);
|
|
275
|
+
if (!text.trim()) {
|
|
276
|
+
this.publish({ type: 'finished', sessionId: run.id });
|
|
277
|
+
await this.finish(run);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (run.action === 'translate') {
|
|
281
|
+
this.publish({ type: 'phase', sessionId: run.id, phase: 'translating' });
|
|
282
|
+
text = await this.translate({ sn: run.sn, service: run.service, text, from: run.preferences.from, to: run.preferences.to, signal: run.lifetime.signal, config: this.config.translation });
|
|
283
|
+
}
|
|
284
|
+
if (this.run !== run || run.closing) return;
|
|
285
|
+
if (run.action === 'ai_input') {
|
|
286
|
+
const prepared = await run.aiReady;
|
|
287
|
+
if (this.run !== run || run.closing) return;
|
|
288
|
+
// Keep the complete text available in the native panel if target preparation/insertion fails.
|
|
289
|
+
this.publish({ type: 'preview', sessionId: run.id, text });
|
|
290
|
+
if (prepared.error) throw prepared.error;
|
|
291
|
+
await this.aiConversation.insert(run, text);
|
|
292
|
+
if (this.run !== run || run.closing) return;
|
|
293
|
+
this.publish({ type: 'finished', sessionId: run.id });
|
|
294
|
+
} else if (run.action === 'speechSearch') {
|
|
295
|
+
await this.action('openUrl', searchAddress(run.preferences.searchUrl, text));
|
|
296
|
+
if (this.run !== run || run.closing) return;
|
|
297
|
+
this.publish({ type: 'finished', sessionId: run.id });
|
|
298
|
+
} else if (this.desktop) {
|
|
299
|
+
await this.desktop.complete(run, text);
|
|
300
|
+
} else this.publish({ type: 'result', sessionId: run.id, text });
|
|
301
|
+
await this.finish(run);
|
|
302
|
+
} catch (error) { this.fail(run, error.message || '语音处理失败,请重试'); }
|
|
303
|
+
}
|
|
304
|
+
fail(run, message) {
|
|
305
|
+
if (this.run !== run || run.closing) return;
|
|
306
|
+
this.publish({ type: 'failed', sessionId: run.id, message });
|
|
307
|
+
void this.finish(run);
|
|
308
|
+
}
|
|
309
|
+
cancel(sessionId, message) {
|
|
310
|
+
const run = this.run;
|
|
311
|
+
if (!run || run.closing || (sessionId && run.id !== sessionId)) return;
|
|
312
|
+
this.publish({ type: message ? 'failed' : 'cancelled', sessionId: run.id, ...(message ? { message } : {}) });
|
|
313
|
+
void this.finish(run);
|
|
314
|
+
}
|
|
315
|
+
cancelFor(deviceId, message) { if (this.run?.deviceId === deviceId) this.cancel(this.run.id, message); }
|
|
316
|
+
async finish(run) {
|
|
317
|
+
if (this.run !== run || run.closing) return;
|
|
318
|
+
run.closing = true; run.audioEnded = true;
|
|
319
|
+
for (const name of ['captureTimer', 'durationTimer', 'tailTimer', 'uploadTimer']) clearTimeout(run[name]);
|
|
320
|
+
run.lifetime.abort(); run.queue.end(true);
|
|
321
|
+
if (run.action === 'ai_input') this.aiConversation?.release(run.id);
|
|
322
|
+
try { await this.sdk.source(''); } catch { /* SDK may already be offline. */ }
|
|
323
|
+
if (this.run === run) this.run = undefined;
|
|
324
|
+
}
|
|
325
|
+
async close() {
|
|
326
|
+
this.disposed = true;
|
|
327
|
+
if (this.run) await this.finish(this.run);
|
|
328
|
+
for (const queue of this.clients) queue.end(true);
|
|
329
|
+
this.clients.clear(); this.owner = undefined;
|
|
330
|
+
this.sdk.off('event', this.onEvent); this.sdk.off('fault', this.onFault);
|
|
331
|
+
this.aiConversation?.close();
|
|
332
|
+
await this.desktop?.close();
|
|
333
|
+
await this.sdk.close();
|
|
334
|
+
}
|
|
335
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import koffi from 'koffi';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
const path = process.argv[2];
|
|
4
|
+
if (process.platform === 'win32') process.env.PATH = dirname(path) + ';' + process.env.PATH;
|
|
5
|
+
let library, api, shuttingDown = false, queued = 0;
|
|
6
|
+
const callbacks = [];
|
|
7
|
+
const notify = message => {
|
|
8
|
+
if (!process.connected || shuttingDown) return;
|
|
9
|
+
if (message.type === 'audio' && queued > 100) return;
|
|
10
|
+
queued++;
|
|
11
|
+
process.send(message, () => { queued--; });
|
|
12
|
+
};
|
|
13
|
+
function bind(name, declaration, callback) {
|
|
14
|
+
const proto = koffi.proto(declaration);
|
|
15
|
+
const pointer = koffi.register(callback, koffi.pointer(proto)); callbacks.push(pointer);
|
|
16
|
+
library.func(`void ${name}(void *callback)`)(pointer);
|
|
17
|
+
}
|
|
18
|
+
const asyncCall = (fn, ...args) => new Promise((resolve, reject) => fn.async(...args, (error, value) => error ? reject(error) : resolve(value)));
|
|
19
|
+
try {
|
|
20
|
+
library = koffi.load(path);
|
|
21
|
+
api = {
|
|
22
|
+
init: library.func('void um_sdk_init(int debug)'), close: library.func('void um_sdk_close(void)'),
|
|
23
|
+
source: library.func('int um_set_audio_source(const char *device_id)'),
|
|
24
|
+
dpi: library.func('int um_set_dpi(const char *device_id, int level)'),
|
|
25
|
+
};
|
|
26
|
+
library.func('void um_enable_crash_report(int enable)')(0);
|
|
27
|
+
library.func('int um_set_audio_output_mode(int mode)')(0);
|
|
28
|
+
library.func('int um_set_device_limit(const char *rule_id, int max_devices)')('', 4);
|
|
29
|
+
bind('um_register_connected', 'void MouseConnected(const char *id, int mode)', (id, mode) => notify({ type: 'connected', id, mode }));
|
|
30
|
+
bind('um_register_disconnected', 'void MouseDisconnected(const char *id, int mode)', (id, mode) => notify({ type: 'disconnected', id, mode }));
|
|
31
|
+
bind('um_register_message', 'void MouseMessage(const char *id, const char *json)', (id, json) => {
|
|
32
|
+
try { notify({ type: 'message', id, message: JSON.parse(json) }); } catch { notify({ type: 'warning', message: '鼠标返回无效设备信息' }); }
|
|
33
|
+
});
|
|
34
|
+
bind('um_register_audio', 'void MouseAudio(const char *id, const void *pcm, int len)', (id, pcm, len) => {
|
|
35
|
+
if (len <= 0 || len > 320000 || len % 2) { notify({ type: 'warning', message: '鼠标音频格式无效' }); return; }
|
|
36
|
+
// The SDK buffer expires as soon as this callback returns.
|
|
37
|
+
const audio = Buffer.from(koffi.decode(pcm, 'uint8_t', len));
|
|
38
|
+
if (queued > 100) { notify({ type: 'overflow', id }); return; }
|
|
39
|
+
notify({ type: 'audio', id, data: audio.toString('base64') });
|
|
40
|
+
});
|
|
41
|
+
process.on('message', async message => {
|
|
42
|
+
if (shuttingDown) return;
|
|
43
|
+
if (message.command === 'close') { await close(); return; }
|
|
44
|
+
try {
|
|
45
|
+
const result = message.command === 'source' ? api.source(message.sn || '')
|
|
46
|
+
: message.command === 'dpi' ? api.dpi(message.sn, message.level) : 0;
|
|
47
|
+
notify({ type: 'reply', requestId: message.requestId, result });
|
|
48
|
+
} catch { notify({ type: 'reply', requestId: message.requestId, result: 0 }); }
|
|
49
|
+
});
|
|
50
|
+
process.on('disconnect', () => { void close(); });
|
|
51
|
+
await asyncCall(api.init, 0);
|
|
52
|
+
notify({ type: 'ready', version: library.func('const char *um_sdk_version(void)')() });
|
|
53
|
+
} catch {
|
|
54
|
+
notify({ type: 'fatal', message: '鼠标 SDK 加载失败,请检查系统架构、动态库和运行依赖' });
|
|
55
|
+
process.exitCode = 1; setTimeout(() => process.exit(1), 50);
|
|
56
|
+
}
|
|
57
|
+
async function close() {
|
|
58
|
+
if (shuttingDown) return;
|
|
59
|
+
shuttingDown = true;
|
|
60
|
+
try { if (api) await asyncCall(api.close); } finally {
|
|
61
|
+
callbacks.forEach(callback => koffi.unregister(callback));
|
|
62
|
+
process.disconnect?.(); process.exit(0);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { fork } from 'node:child_process';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { diagnoseUsb } from './diagnostics.mjs';
|
|
6
|
+
export class MouseSdk extends EventEmitter {
|
|
7
|
+
constructor(config = {}) { super(); this.config = config; this.pending = new Map(); this.serial = 0; }
|
|
8
|
+
async start() {
|
|
9
|
+
if (this.child) return this.starting;
|
|
10
|
+
const target = `${process.platform}-${process.arch}`;
|
|
11
|
+
const filename = process.platform === 'win32' ? 'uMouseSdk.dll' : 'libuMouseSdk.dylib';
|
|
12
|
+
const path = this.config.libraryPath ?? fileURLToPath(new URL(`../../native/${target}/${filename}`, import.meta.url));
|
|
13
|
+
if (!existsSync(path)) throw new Error(`当前平台 ${target} 缺少鼠标 SDK,请配置匹配的动态库`);
|
|
14
|
+
const child = fork(fileURLToPath(new URL('./native-worker.mjs', import.meta.url)), [path], {
|
|
15
|
+
stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [],
|
|
16
|
+
});
|
|
17
|
+
this.child = child;
|
|
18
|
+
const connected = new Set();
|
|
19
|
+
let diagnosing = false;
|
|
20
|
+
const diagnose = async () => {
|
|
21
|
+
if (diagnosing || connected.size || this.stopping || this.child !== child) return;
|
|
22
|
+
diagnosing = true;
|
|
23
|
+
try {
|
|
24
|
+
const message = await diagnoseUsb(child.pid);
|
|
25
|
+
if (message && !connected.size && !this.stopping && this.child === child) this.emit('event', { type: 'diagnostic', message });
|
|
26
|
+
} catch { /* Diagnosis must never interrupt SDK discovery. */ }
|
|
27
|
+
finally { diagnosing = false; }
|
|
28
|
+
};
|
|
29
|
+
this.starting = new Promise((resolve, reject) => {
|
|
30
|
+
const timer = setTimeout(() => { child.kill(); reject(new Error('鼠标 SDK 启动超时')); }, 15000);
|
|
31
|
+
child.on('message', message => {
|
|
32
|
+
if (message.type === 'ready') {
|
|
33
|
+
clearTimeout(timer); resolve(message.version);
|
|
34
|
+
if (process.platform === 'darwin') {
|
|
35
|
+
this.diagnosticTimer = setInterval(diagnose, 5000); this.diagnosticTimer.unref(); void diagnose();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else if (message.type === 'fatal') { clearTimeout(timer); reject(new Error(message.message)); this.emit('fault', message.message); }
|
|
39
|
+
else if (message.type === 'reply') {
|
|
40
|
+
const pending = this.pending.get(message.requestId);
|
|
41
|
+
if (pending) { clearTimeout(pending.timer); this.pending.delete(message.requestId); pending.resolve(message.result); }
|
|
42
|
+
} else {
|
|
43
|
+
if (message.type === 'connected') connected.add(message.id);
|
|
44
|
+
if (message.type === 'disconnected') connected.delete(message.id);
|
|
45
|
+
this.emit('event', message);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
const failed = () => {
|
|
49
|
+
clearInterval(this.diagnosticTimer);
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
if (this.child === child) this.child = undefined;
|
|
52
|
+
for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error('鼠标 SDK 已停止')); }
|
|
53
|
+
this.pending.clear();
|
|
54
|
+
reject(new Error('鼠标 SDK 未能启动'));
|
|
55
|
+
if (!this.stopping) this.emit('fault', '鼠标 SDK 已停止,请重新启用插件');
|
|
56
|
+
};
|
|
57
|
+
child.once('exit', failed); child.once('error', failed);
|
|
58
|
+
});
|
|
59
|
+
return this.starting;
|
|
60
|
+
}
|
|
61
|
+
command(command, fields = {}) {
|
|
62
|
+
if (!this.child?.connected) return Promise.reject(new Error('鼠标 SDK 未连接'));
|
|
63
|
+
const requestId = ++this.serial;
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const timer = setTimeout(() => { this.pending.delete(requestId); reject(new Error('鼠标指令超时')); }, 3000);
|
|
66
|
+
this.pending.set(requestId, { resolve, reject, timer });
|
|
67
|
+
this.child.send({ command, requestId, ...fields }, error => {
|
|
68
|
+
if (error) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error('鼠标指令发送失败')); }
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
source(sn) { return this.command('source', { sn }); }
|
|
73
|
+
dpi(sn, level) { return this.command('dpi', { sn, level }); }
|
|
74
|
+
async close() {
|
|
75
|
+
this.stopping = true;
|
|
76
|
+
clearInterval(this.diagnosticTimer);
|
|
77
|
+
const child = this.child;
|
|
78
|
+
if (!child) return;
|
|
79
|
+
await new Promise(resolve => {
|
|
80
|
+
const timer = setTimeout(() => { child.kill(); resolve(); }, 3000);
|
|
81
|
+
child.once('exit', () => { clearTimeout(timer); resolve(); });
|
|
82
|
+
if (child.connected) child.send({ command: 'close' }, () => {}); else { clearTimeout(timer); resolve(); }
|
|
83
|
+
});
|
|
84
|
+
this.child = undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export class AsyncQueue {
|
|
2
|
+
constructor(limit = 256) { this.limit = limit; this.items = []; this.ended = false; }
|
|
3
|
+
push(value) {
|
|
4
|
+
if (this.ended) return false;
|
|
5
|
+
if (this.items.length >= this.limit) throw new Error('数据处理过慢,请重新录音');
|
|
6
|
+
this.items.push(value); this.wake?.(); return true;
|
|
7
|
+
}
|
|
8
|
+
end(clear = false) { if (clear) this.items = []; this.ended = true; this.wake?.(); }
|
|
9
|
+
async *[Symbol.asyncIterator]() {
|
|
10
|
+
while (true) {
|
|
11
|
+
if (this.items.length) yield this.items.shift();
|
|
12
|
+
else if (this.ended) return;
|
|
13
|
+
else await new Promise(resolve => { this.wake = resolve; });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export class PcmPackets {
|
|
18
|
+
constructor(output) { this.output = output; this.tail = Buffer.alloc(0); this.bytes = 0; }
|
|
19
|
+
write(buffer) {
|
|
20
|
+
if (buffer.length % 2) throw new Error('鼠标音频格式无效');
|
|
21
|
+
this.bytes += buffer.length;
|
|
22
|
+
if (this.bytes > 19_200_000) throw new Error('单次录音最长 10 分钟');
|
|
23
|
+
const bytes = Buffer.concat([this.tail, buffer]);
|
|
24
|
+
let offset = 0;
|
|
25
|
+
while (offset + 3200 <= bytes.length) { this.output(bytes.subarray(offset, offset + 3200).toString('base64')); offset += 3200; }
|
|
26
|
+
this.tail = Buffer.from(bytes.subarray(offset));
|
|
27
|
+
}
|
|
28
|
+
flush() {
|
|
29
|
+
if (this.tail.length) { const tail = Buffer.alloc(Math.max(82, this.tail.length)); this.tail.copy(tail); this.output(tail.toString('base64')); }
|
|
30
|
+
this.tail = Buffer.alloc(0);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { sourceRecognitionLanguage, languageKey, REC_LANG_LIST, TRANS_FROM_LANG_LIST, TRANS_TO_LANG_LIST } from '../shared/devices.mjs';
|
|
2
|
+
import { DEFAULT_LANGUAGES } from '../asr/languages.mjs';
|
|
3
|
+
export { DEFAULT_LANGUAGES };
|
|
4
|
+
export function recognitionQuery(preferences, action, mappings = DEFAULT_LANGUAGES) {
|
|
5
|
+
let selected = preferences.recognition;
|
|
6
|
+
if (action === 'translate') {
|
|
7
|
+
if (!TRANS_FROM_LANG_LIST.some(item => item.value === preferences.from) || !TRANS_TO_LANG_LIST.some(item => item.value === preferences.to)) {
|
|
8
|
+
throw new Error('原翻译语言已不再支持,请在设备设置中重新选择');
|
|
9
|
+
}
|
|
10
|
+
selected = sourceRecognitionLanguage(preferences.from);
|
|
11
|
+
}
|
|
12
|
+
if (!selected || !REC_LANG_LIST.some(item => languageKey(item) === languageKey(selected))) throw new Error('原识别语言已不再支持,请在设备设置中重新选择');
|
|
13
|
+
const mapping = selected && mappings.find(item => languageKey(item) === languageKey(selected));
|
|
14
|
+
if (!mapping?.query) throw new Error('当前 ASR 尚未配置此语言的接口映射,请选择已支持的语言');
|
|
15
|
+
const query = {};
|
|
16
|
+
for (const [key, value] of Object.entries(mapping.query)) {
|
|
17
|
+
if (!['lid', 'lanid', 'role', 'language', 'accent', 'rlang'].includes(key) || !['string', 'number'].includes(typeof value)) throw new Error('ASR 语言映射配置无效');
|
|
18
|
+
query[key] = String(value);
|
|
19
|
+
}
|
|
20
|
+
return query;
|
|
21
|
+
}
|
|
22
|
+
export const formatTranscript = (text, preferences, action) => action !== 'translate' && !preferences.punctuation
|
|
23
|
+
? text.replace(/\p{P}/gu, '') : text;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { defaultPreferences, preferencesSchema, storedPreferencesSchema, snSchema } from '../shared/devices.mjs';
|
|
2
|
+
// 保留旧存储键,继续读取重命名前保存的配置。
|
|
3
|
+
const KEY = 'dsh-asr/devices';
|
|
4
|
+
export class DeviceStore {
|
|
5
|
+
constructor(credentials) { this.credentials = credentials; }
|
|
6
|
+
async state() {
|
|
7
|
+
let record = await this.credentials.readRecord(KEY);
|
|
8
|
+
if (!record) record = await this.credentials.modifyRecord(KEY, current => current ?? { kind: 'grant', payload: { version: 1, devices: {} } });
|
|
9
|
+
if (record?.kind !== 'grant' || record.payload?.version !== 1 || !record.payload.devices) throw new Error('设备配置无法读取');
|
|
10
|
+
return structuredClone(record.payload);
|
|
11
|
+
}
|
|
12
|
+
async get(sn) {
|
|
13
|
+
snSchema.parse(sn);
|
|
14
|
+
const saved = (await this.state()).devices[sn];
|
|
15
|
+
return { revision: saved?.revision ?? 0, preferences: storedPreferencesSchema.parse({ ...defaultPreferences(), ...saved?.preferences }) };
|
|
16
|
+
}
|
|
17
|
+
async reportDpi(sn, dpi) {
|
|
18
|
+
snSchema.parse(sn);
|
|
19
|
+
await this.state();
|
|
20
|
+
await this.credentials.modifyRecord(KEY, record => {
|
|
21
|
+
const state = structuredClone(record.payload);
|
|
22
|
+
const saved = state.devices[sn];
|
|
23
|
+
const preferences = storedPreferencesSchema.parse({ ...defaultPreferences(), ...saved?.preferences, dpi });
|
|
24
|
+
if (saved?.preferences.dpi === dpi) return record;
|
|
25
|
+
state.devices[sn] = { revision: (saved?.revision ?? 0) + 1, preferences };
|
|
26
|
+
return { kind: 'grant', payload: state };
|
|
27
|
+
});
|
|
28
|
+
return this.get(sn);
|
|
29
|
+
}
|
|
30
|
+
async save(sn, revision, input) {
|
|
31
|
+
snSchema.parse(sn);
|
|
32
|
+
const preferences = preferencesSchema.parse(input);
|
|
33
|
+
preferences.linkUrl = preferences.linkUrl.trim();
|
|
34
|
+
await this.state();
|
|
35
|
+
await this.credentials.modifyRecord(KEY, record => {
|
|
36
|
+
const state = structuredClone(record.payload);
|
|
37
|
+
const saved = state.devices[sn];
|
|
38
|
+
if ((saved?.revision ?? 0) !== revision) throw new Error('设备配置已变更,请刷新后重试');
|
|
39
|
+
state.devices[sn] = { revision: revision + 1, preferences };
|
|
40
|
+
return { kind: 'grant', payload: state };
|
|
41
|
+
});
|
|
42
|
+
return this.get(sn);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { BUILTIN_ASR } from '../asr/config.mjs';
|
|
2
|
+
import { TRANS_FROM_LANG_LIST, TRANS_TO_LANG_LIST } from '../shared/languages.mjs';
|
|
3
|
+
|
|
4
|
+
export const TRANSLATE_URL = BUILTIN_ASR.translateUrl;
|
|
5
|
+
|
|
6
|
+
export async function translateText({ text, from, to, signal, getToken, userId, config = {}, fetchImpl = globalThis.fetch, url = TRANSLATE_URL }) {
|
|
7
|
+
signal.throwIfAborted();
|
|
8
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('没有可翻译的文本');
|
|
9
|
+
if ([...text].length > 5000) throw new Error('翻译文本超过 5000 字符,可复制原文');
|
|
10
|
+
if (!TRANS_FROM_LANG_LIST.some(item => item.value === from) || !TRANS_TO_LANG_LIST.some(item => item.value === to)) throw new Error('翻译语言无效,请重新选择');
|
|
11
|
+
const payload = { text, from: from === 'cn' ? 'zh' : from, to: to === 'cn' ? 'zh' : to };
|
|
12
|
+
if (payload.from === payload.to) throw new Error('翻译源语言与目标语言不能相同');
|
|
13
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
14
|
+
const token = await getToken(signal);
|
|
15
|
+
signal.throwIfAborted();
|
|
16
|
+
const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(config.timeoutMs ?? 15000)]);
|
|
17
|
+
let response, body;
|
|
18
|
+
try {
|
|
19
|
+
response = await fetchImpl(url, {
|
|
20
|
+
method: 'POST', redirect: 'error', signal: requestSignal,
|
|
21
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8', 'X-SC-Authorization': token, 'X-SC-User-Id': userId },
|
|
22
|
+
body: JSON.stringify(payload),
|
|
23
|
+
});
|
|
24
|
+
body = await response.json();
|
|
25
|
+
requestSignal.throwIfAborted();
|
|
26
|
+
} catch {
|
|
27
|
+
signal.throwIfAborted();
|
|
28
|
+
throw new Error('翻译请求失败或响应无效,可复制原文后重试');
|
|
29
|
+
}
|
|
30
|
+
if (String(body?.code) === '1004') {
|
|
31
|
+
getToken.invalidate(token);
|
|
32
|
+
if (attempt === 0) continue;
|
|
33
|
+
throw new Error('翻译认证失败,请稍后重试');
|
|
34
|
+
}
|
|
35
|
+
if (!response.ok || body?.code !== 0) {
|
|
36
|
+
const messages = { 1001: '翻译参数错误', 1003: '翻译额度不足', 1005: '翻译请求过于频繁',
|
|
37
|
+
1006: '翻译应用不可用', 1007: '翻译应用已下线', 3005: '翻译请求超时' };
|
|
38
|
+
throw new Error((messages[body?.code] ?? '翻译服务调用失败') + ',可复制原文后重试');
|
|
39
|
+
}
|
|
40
|
+
const result = body.data?.resultText;
|
|
41
|
+
if (typeof result !== 'string' || !result.trim() || result.length > 65536) throw new Error('翻译未返回有效译文,可复制原文后重试');
|
|
42
|
+
signal.throwIfAborted(); return result;
|
|
43
|
+
}
|
|
44
|
+
}
|