-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.js
More file actions
2430 lines (2208 loc) · 88.9 KB
/
Copy pathutils.js
File metadata and controls
2430 lines (2208 loc) · 88.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Mira Translator
* Copyright (C) 2026 David Bai
* Licensed under a custom Source-Available License.
* Unauthorized modification, redistribution, or rebranding is
* prohibited. See LICENSE file or:
* https://github.com/os9sur/MiraTranslator/blob/main/LICENSE
* Contact: mira.studio@proton.me
*/
const IS_DEV = true;
const api = (typeof chrome !== 'undefined' && chrome.runtime?.id)
? (typeof browser !== 'undefined' ? browser : chrome)
: {};
const logger = {
_print: (type, ...args) => {
if (!IS_DEV) return;
const prefix = `[Mira-${type.toUpperCase()}]`;
const styles = {
log: "color: #38bdf8; font-weight: bold;",
warn: "color: #f1c40f; font-weight: bold;",
error: "color: #e74c3c; font-weight: bold;",
group: "color: #a855f7; font-weight: bold;"
};
if (typeof console !== 'undefined') {
if (['log', 'warn', 'group', 'groupCollapsed'].includes(type) && typeof window !== 'undefined') {
console[type](` %c${prefix}`, styles[type] || styles.log, ...args);
} else {
console[type](prefix, ...args);
}
}
},
log: (...args) => logger._print('log', ...args),
warn: (...args) => logger._print('warn', ...args),
group: (...args) => logger._print('group', ...args),
groupCollapsed: (...args) => logger._print('groupCollapsed', ...args),
groupEnd: () => IS_DEV && console.groupEnd(),
error: (...args) => {
try {
if (IS_DEV) {
console.error("[Mira-Error]", ...args);
return;
}
const msg = args.map(a => {
if (!a && a !== 0) return '';
if (a instanceof Error) return a.message || String(a);
if (typeof a === 'string') return a;
try { return JSON.stringify(a); } catch (e) { return String(a); }
}).join(' ');
const benignPatterns = ['Extension context invalidated'];
for (const p of benignPatterns) {
if (msg.includes(p)) return;
}
} catch (e) { }
}
};
const IS_MAIN_WORLD = (typeof chrome === 'undefined' || !chrome.runtime?.id);
(function () {
try {
const test = window.localStorage;
} catch (e) {
if (typeof window !== 'undefined') {
Object.defineProperty(window, 'localStorage', {
get: () => ({ getItem: () => null, setItem: () => null, removeItem: () => null })
});
}
}
})();
const getCleanDomain = (url) => {
try {
const hostname = new URL(url).hostname;
return hostname.replace(/^www\./, '');
} catch (e) {
return "unknown";
}
};
//浏览器语言
const normalizeLang = (lang) => {
if (!lang) return 'en';
const l = lang.toLowerCase();
// 中文逻辑
if (l.startsWith('zh')) {
if (l.includes('hk')) return 'zh-HK';
if (l.includes('sg')) return 'zh-SG';
const isTrad = l.includes('tw') || l.includes('mo') || l.includes('hant');
return isTrad ? 'zh-TW' : 'zh-CN';
}
const specials = {
'en-in': 'en-IN', 'en-gb': 'en-GB', 'en-us': 'en-US', 'en-ca': 'en-CA', 'en-au': 'en-AU',
'en-nz': 'en-NZ', 'en-ie': 'en-IE',
'de-ch': 'de-CH', 'fr-ca': 'fr-CA', 'pt-br': 'pt-BR',
'ar-ae': 'ar-AE', 'ar-sa': 'ar-SA'
};
if (specials[l]) return specials[l];
return l.split('-')[0];
};
const getBrowserLang = () => {
try {
return normalizeLang(
(navigator.languages && navigator.languages[0]) ||
navigator.language ||
'en'
);
} catch (e) {
return 'en';
}
};
const checkRTL = (lang) => {
const rtlSet = new Set(['he', 'ar', 'fa', 'ur', 'yi']);
return lang ? rtlSet.has(lang.toLowerCase().split('-')[0]) : false;
};
// 检测阿拉伯语、希伯来语、波斯语等RTL字符
const isRTLText = (text) => {
if (!text) return false;
return /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/.test(text);
};
const GA_MEASUREMENT_ID = "{{GA_MEASUREMENT_ID}}";
const GA_API_SECRET = "{{GA_API_SECRET}}";
// 公共设备信息
function getDeviceInfo() {
const ua = navigator.userAgent;
return {
browser: ua.includes('Edg/') ? 'edge'
: ua.includes('Firefox/') ? 'firefox'
: 'chrome',
browser_version: (
/Edg\/(\d+)/.exec(ua) ||
/Firefox\/(\d+)/.exec(ua) ||
/Chrome\/(\d+)/.exec(ua)
)?.[1] || 'unknown',
os: ua.includes('Windows') ? 'windows'
: ua.includes('Mac') ? 'mac'
: ua.includes('Linux') ? 'linux'
: 'unknown',
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};
}
// 生成/获取唯一用户ID
async function getClientId() {
const result = await safeGetStorage('ga_client_id', true);
if (result?.ga_client_id) return result.ga_client_id;
const id = crypto.randomUUID();
await safeSetStorage({ ga_client_id: id });
return id;
}
function getReviewUrl() {
const ua = navigator.userAgent;
// Firefox:双重验证
if (typeof browser !== 'undefined' && /Firefox/.test(ua)) {
return "https://addons.mozilla.org/firefox/addon/mira-translator/";
}
// Edge:UA 有专属 Edg/ 标识
if (ua.includes("Edg/")) {
return "https://microsoftedge.microsoft.com/addons/detail/ofhlbeoigddhlpompkgbmbdhpbffmife";
}
// 默认 Chrome
return "https://chromewebstore.google.com/detail/mira-translator-immersive/hmmllfdmkbmmfffjekhmmbhhfhhnocmn";
}
async function safeSendToTab(tabId, message) {
if (!tabId || typeof tabId !== 'number' || !chrome.runtime?.id) return null;
return new Promise((resolve) => {
try {
chrome.tabs.sendMessage(tabId, message, (response) => {
const error = chrome.runtime.lastError;
if (error) {
resolve(null);
} else {
resolve(response);
}
});
} catch (e) {
resolve(null);
}
});
}
// 上报事件
async function trackEvent(eventName, params = {}) {
if (IS_DEV) return;
const clientId = await getClientId();
fetch(
`https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`,
{
method: 'POST',
body: JSON.stringify({
client_id: clientId,
events: [{ name: eventName, params }],
}),
}
).catch(() => { });
}
async function safeSetIcon(tabId, imageData) {
if (!tabId || !imageData || !chrome.runtime?.id) return null;
return new Promise((resolve) => {
try {
chrome.action.setIcon({ imageData: imageData, tabId: tabId }, () => {
const error = chrome.runtime.lastError;
if (error) {
resolve(false);
} else {
resolve(true);
}
});
} catch (e) {
resolve(false);
}
});
}
async function safeCreateTab(url, unique = true) {
const finalUrl = url.startsWith('http') ? url : chrome.runtime.getURL(url);
return new Promise((resolve) => {
if (unique) {
chrome.tabs.query({ url: finalUrl }, (tabs) => {
const err1 = chrome.runtime.lastError;
if (!err1 && tabs && tabs.length > 0) {
chrome.tabs.update(tabs[0].id, { active: true }, (tab) => {
chrome.runtime.lastError;
resolve(tab);
});
chrome.windows.update(tabs[0].windowId, { focused: true });
} else {
chrome.tabs.create({ url: finalUrl }, (tab) => {
chrome.runtime.lastError;
resolve(tab);
});
}
});
} else {
chrome.tabs.create({ url: finalUrl }, (tab) => {
const err = chrome.runtime.lastError;
if (err) logger.warn(`[SafeCreate] 创建失败: ${err.message}`);
resolve(tab);
});
}
});
}
async function getActiveTab() {
return new Promise((resolve) => {
try {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, (tabs) => {
const err = chrome.runtime.lastError;
if (err) {
logger.warn(`[SafeQuery] 查询 Tab 异常: ${err.message}`);
return resolve(null);
}
if (tabs && tabs.length > 0) {
resolve(tabs[0]);
} else {
chrome.tabs.query({ active: true, currentWindow: true }, (fallbackTabs) => {
const err2 = chrome.runtime.lastError;
if (!err2 && fallbackTabs && fallbackTabs.length > 0) {
resolve(fallbackTabs[0]);
} else {
resolve(null);
}
});
}
});
} catch (e) {
logger.error("[SafeQuery] 同步捕获错误:", e);
resolve(null);
}
});
}
const lang = getBrowserLang();
let _defaultEngine = (lang === 'zh-CN') ? 'bing' : 'google';
let _defaultEngineReady = safeGetStorage(['_defaultEngine'], true).then(res => {
if (res && res._defaultEngine) _defaultEngine = res._defaultEngine;
});
async function getInitialActiveConfig() {
await _defaultEngineReady;
return { engine: _defaultEngine, data: {} };
}
function getRuntimeDefaultEngine() {
return _defaultEngine;
}
function getCurrentLang() {
return window.currentConfig?.targetLanguage ||
window.currentTargetL ||
getBrowserLang() ||
'en';
}
const showNotice = false;
let globalDefault_Page = !showNotice;
let globalDefault_Select = !showNotice;
let globalDefault_YT = !showNotice;
let enable_pro_features = false; //是否显示pro模型列表
let cachedSiteSettings = {};
let cachedGlobalConfig = { page: globalDefault_Page, select: globalDefault_Select, yt: globalDefault_YT };
if (typeof chrome !== 'undefined' && chrome.storage) {
safeGetStorage(['siteSettings', 'globalConfig'], true).then(res => {
if (res?.siteSettings) cachedSiteSettings = res.siteSettings;
if (res?.globalConfig) cachedGlobalConfig = res.globalConfig;
});
chrome.storage.onChanged.addListener((changes) => {
if (changes.siteSettings) cachedSiteSettings = changes.siteSettings.newValue;
if (changes.globalConfig) cachedGlobalConfig = changes.globalConfig.newValue;
});
}
function isCurrentSiteActive() {
try {
const fullHost = window.location.hostname.toLowerCase();
const cleanHost = fullHost.replace(/^www\./, '');
const settings = cachedSiteSettings || {};
const global = cachedGlobalConfig;
const siteConfig = settings[fullHost] || settings[cleanHost];
const activeConfig = siteConfig || global;
if (fullHost.includes('youtube.com')) {
return activeConfig.page === true || activeConfig.select === true || activeConfig.yt === true;
}
return activeConfig.page === true || activeConfig.select === true;
} catch (e) {
return false;
}
}
function getSafeMessage(key, defaultMsg) {
try {
return (chrome.i18n && chrome.runtime?.id) ? chrome.i18n.getMessage(key) : defaultMsg;
} catch (e) {
return defaultMsg;
}
}
async function safeSendMessage(message) {
if (typeof chrome === 'undefined' || !chrome.runtime?.id) {
if (typeof isCurrentSiteActive === 'function' && isCurrentSiteActive()) showUpdateNotice();
return null;
}
return new Promise((resolve) => {
try {
chrome.runtime.sendMessage(message, (response) => {
// 立即消费 lastError,防止 Unchecked 警告
const err = chrome.runtime.lastError;
if (err) {
const errorMsg = err.message || '';
if (errorMsg.includes('context invalidated')) {
if (typeof isCurrentSiteActive === 'function' && isCurrentSiteActive()) showUpdateNotice();
}
// "Receiving end does not exist" 是正常情况(background 未就绪),静默处理
resolve(null);
} else {
resolve(response);
}
});
} catch (e) {
if (e.message?.includes('context invalidated') || !chrome.runtime?.id) {
if (typeof isCurrentSiteActive === 'function' && isCurrentSiteActive()) showUpdateNotice();
}
resolve(null);
}
});
}
//自定义prompt
const AI_PROMPT_KEY = 'ai_prompt_settings';
const AI_LLM_WHITE_LIST = [
'openai',
'deepseek',
'claude',
'gemini',
'grok',
'groq',
'siliconflow',
'custom_ai'
];
const TRADITIONAL_ENGINE_LIST = [
'google',
'deepl',
'deeplx',
'bing'
];
const HOST_KEY_MAP = {
'openai': 'oaApiHost',
'deepseek': 'dsHost',
'custom_ai': 'customHost',
'siliconflow': 'siliconflowHost',
'gemini': 'geminiHost',
'claude': 'claudeApiHost',
'grok': 'grokHost',
'groq': 'groqHost',
};
function isLocalModelHost(host) {
const h = (host || '').toLowerCase();
return h.includes('localhost') ||
h.includes('127.0.0.1') ||
h.includes('0.0.0.0') ||
/https?:\/\/192\.168\./.test(h) ||
/https?:\/\/10\./.test(h) ||
/https?:\/\/172\.(1[6-9]|2\d|3[01])\./.test(h);
}
let isNoticeShowing = false;
function showUpdateNotice() {
if (isNoticeShowing || document.getElementById('mira-update-notice')) return;
isNoticeShowing = true;
const div = document.createElement('div');
div.id = 'mira-update-notice';
const finalMsg = t("update_notice") === "update_notice"
? "Mira Translator has been updated. Please click here to refresh the page."
: t("update_notice");
div.style.cssText = `
position: fixed;
bottom: 24px;
right: 24px;
z-index: 10000000;
background: #1f2937;
color: #f3f4f6;
padding: 14px 24px;
border-radius: 12px;
cursor: pointer;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 14px;
border: 1px solid #374151;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
align-items: center;
gap: 10px;
`;
// 用 DOM API 创建 SVG,避免 innerHTML TrustedHTML 限制
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('class', 'mira-refresh-svg');
svg.setAttribute('width', '18');
svg.setAttribute('height', '18');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', 'currentColor');
svg.setAttribute('stroke-width', '2.5');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('stroke-linejoin', 'round');
svg.style.transition = 'transform 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
const path1 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path1.setAttribute('d', 'M23 4v6h-6');
const path2 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path2.setAttribute('d', 'M1 20v-6h6');
const path3 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path3.setAttribute('d', 'M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15');
svg.appendChild(path1);
svg.appendChild(path2);
svg.appendChild(path3);
const span = document.createElement('span');
span.style.marginLeft = '8px';
span.textContent = finalMsg;
div.appendChild(svg);
div.appendChild(span);
div.onmouseenter = () => {
div.style.background = '#374151';
div.style.transform = 'translateY(-2px)';
const svgEl = div.querySelector('.mira-refresh-svg');
if (svgEl) svgEl.style.transform = 'rotate(360deg)';
};
div.onmouseleave = () => {
div.style.background = '#1f2937';
div.style.transform = 'translateY(0)';
const svgEl = div.querySelector('.mira-refresh-svg');
if (svgEl) svgEl.style.transform = 'rotate(0deg)';
};
div.onclick = (e) => {
e.stopPropagation();
isNoticeShowing = true;
div.style.display = 'none';
location.reload();
};
const target = document.body || document.documentElement;
if (target) {
target.appendChild(div);
} else {
isNoticeShowing = false;
}
}
let i18nDict = {};
let isSynced = false;
function syncI18nDict(force = false) {
if (isSynced && !force) return;
const root = typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {});
const dataKeys = ['i18nData', 'i18nContent', 'i18nEngineData', 'i18nStyleData', 'i18nDonateData', 'i18nSyncData', 'i18nCacheData', 'i18nThemeData', 'i18nYTData', 'i18nAttach1', 'i18nAttach2', 'i18nAttach3', 'i18nAttach4', 'i18nAttach5', 'i18nAttach6', 'i18nAttach7', 'i18nAttach8', 'i18nAttach9', 'i18nAttach10', 'i18nAttach11', 'i18nAttach12'];
let foundAny = false;
dataKeys.forEach(key => {
const data = root[key];
if (data) {
foundAny = true;
Object.keys(data).forEach(lang => {
const normLang = lang.replace('_', '-').toLowerCase();
if (!i18nDict[normLang]) i18nDict[normLang] = {};
Object.assign(i18nDict[normLang], data[lang]);
});
}
});
if (foundAny) isSynced = true;
}
function t(key, forcedLang) {
syncI18nDict();
// 本地模型/自定义API相关提示
const localModelTips = {
'timeoutLocalModel': {
'zh': '本地模型响应超时,无独立显卡时速度会非常慢,建议改用云端服务',
'zh-tw': '本地模型回應逾時,建議使用獨立顯卡或雲端服務',
'ja': 'ローカルモデルがタイムアウトしました。専用GPU(独立グラフィックカード)がない場合、速度が非常に遅くなります。クラウドサービスの利用をお勧めします。',
'default': 'Local model timeout. A dedicated GPU is required. Consider using a cloud API instead.'
},
'customApiTip': {
'zh': '<span style="display: block; padding-left: 20px;">兼容 OpenAI API 格式的服务均可使用(云端 or 本地)。</span><br /><span style="display: block; padding-left: 20px;">使用本地模型(Ollama / LM Studio 等)需注意:</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① 需独立显卡,核显/CPU 会严重超时。</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② 需开启跨域:Ollama 设置环境变量 OLLAMA_ORIGINS=*,LM Studio / Jan 在设置页开启 CORS 选项。</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ 本地模型无需 API Key,留空即可。</span>',
'zh-tw': '<span style="display: block; padding-left: 20px;">相容 OpenAI API 格式的服務均可使用(雲端 or 本地)。</span><br /><span style="display: block; padding-left: 20px;">本地模型(Ollama / LM Studio 等)需注意:</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① 需獨立顯示卡,內顯/CPU 會嚴重逾時。</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② 需開啟 CORS:Ollama 設定 OLLAMA_ORIGINS=*,LM Studio / Jan 在設定頁開啟 CORS 選項。</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ 本地模型無需 API Key,留空即可。</span>',
'ja': '<span style="display: block; padding-left: 20px;">OpenAI API 形式に対応したサービスであれば利用可能です(クラウド/ローカル問わず)。</span><br /><span style="display: block; padding-left: 20px;">ローカルモデル(Ollama / LM Studio など)をご利用の場合:</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① 専用 GPU が必要です。内蔵 GPU/CPU のみではタイムアウトが頻発します。</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② CORS の有効化が必要です:Ollama は OLLAMA_ORIGINS=* を環境変数に設定、LM Studio / Jan は設定ページで CORS オプションをオンにしてください。</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ ローカルモデルは API Key 不要です。空欄のままで構いません。</span>',
'en': '<span style="display: block; padding-left: 20px;">Compatible with any OpenAI API format (cloud or local).</span><br /><span style="display: block; padding-left: 20px;">For local models (Ollama / LM Studio etc.):</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① Dedicated GPU required (iGPU/CPU causes severe timeouts).</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② Enable CORS: set OLLAMA_ORIGINS=* for Ollama, or enable CORS in settings for LM Studio / Jan.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ No API key needed for local models — leave it blank.</span>',
'ko': '<span style="display: block; padding-left: 20px;">OpenAI API 형식을 지원하는 모든 서비스(클라우드 또는 로컬)를 사용할 수 있습니다.</span><br /><span style="display: block; padding-left: 20px;">로컬 모델(Ollama / LM Studio 등) 사용 시 주의사항:</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① 외장 그래픽 카드가 필수이며, 내장 그래픽/CPU 사용 시 심각한 시간 초과가 발생할 수 있습니다.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② 교차 출처(CORS) 활성화 필요: Ollama는 환경 변수 OLLAMA_ORIGINS=* 설정, LM Studio / Jan은 설정 페이지에서 CORS 옵션을 켜야 합니다.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ 로컬 모델은 API Key가 필요 없습니다. 비워두면 됩니다.</span>',
'ru': '<span style="display: block; padding-left: 20px;">Совместимо с любыми сервисами в формате OpenAI API (облачными или локальными).</span><br /><span style="display: block; padding-left: 20px;">При использовании локальных моделей (Ollama / LM Studio и др.):</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① Требуется дискретная видеокарта, использование встроенной графики или CPU приведет к серьезным таймаутам.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② Необходимо включить CORS: установите переменную окружения OLLAMA_ORIGINS=* для Ollama или включите CORS в настройках для LM Studio / Jan.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ Для локальных моделей API Key не нужен — оставьте поле пустым.</span>',
'pt-BR': '<span style="display: block; padding-left: 20px;">Compatível com qualquer serviço no formato OpenAI API (em nuvem ou local).</span><br /><span style="display: block; padding-left: 20px;">Para modelos locais (Ollama / LM Studio, etc.), atente-se ao seguinte:</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① É necessária uma placa de vídeo dedicada; o uso de gráficos integrados ou CPU causará tempos limite (timeouts) severos.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② É necessário habilitar o CORS: defina a variável de ambiente OLLAMA_ORIGINS=* para o Ollama ou ative a opção CORS nas configurações do LM Studio / Jan.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ Modelos locais não precisam de API Key — deixe o campo em branco.</span>',
'es': '<span style="display: block; padding-left: 20px;">Compatible con cualquier servicio en formato OpenAI API (en la nube o local).</span><br /><span style="display: block; padding-left: 20px;">Para modelos locales (Ollama / LM Studio, etc.), tenga en cuenta lo siguiente:</span><span style="display: block; padding-left: 20px; margin-top: 4px;">① Se requiere una tarjeta gráfica dedicada; el uso de gráficos integrados o CPU provocará tiempos de espera (timeouts) severos.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">② Es necesario habilitar el CORS: configure la variable de entorno OLLAMA_ORIGINS=* para Ollama o active la opción CORS en los ajustes de LM Studio / Jan.</span><span style="display: block; padding-left: 20px; margin-top: 2px;">③ Los modelos locales no requieren API Key — deje el campo en blanco.</span>',
'ar': '<span style="display: block; padding-right: 20px;">متوافق مع أي تنسيق OpenAI API (سحابي أو محلي).</span><br /><span style="display: block; padding-right: 20px;">للنماذج المحلية (Ollama / LM Studio وغيرها):</span><span style="display: block; padding-right: 20px; margin-top: 4px;">① مطلوب GPU مخصص (iGPU/CPU يسبب انتهاء مهلة شديد).</span><span style="display: block; padding-right: 20px; margin-top: 2px;">② تفعيل CORS: اضبط OLLAMA_ORIGINS=* لـ Ollama، أو فعّل CORS في الإعدادات لـ LM Studio / Jan.</span><span style="display: block; padding-right: 20px; margin-top: 2px;">③ لا يلزم مفتاح API للنماذج المحلية — اتركه فارغًا.</span>',
},
};
if (localModelTips[key]) {
const target = (forcedLang || globalUiLang || 'en').replace('_', '-').toLowerCase();
const short = target.split('-')[0];
const tips = localModelTips[key];
return tips[target] || tips[short] || tips['default'];
}
if (!i18nDict || Object.keys(i18nDict).length === 0) return key;
const root = typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {});
const langEl = typeof document !== 'undefined' ? document.getElementById('targetLang') : null;
let lang = forcedLang
|| root.globalUiLang // 用户手动设置的UI语言
|| getBrowserLang() // 浏览器语言
|| 'en';
const target = lang.replace('_', '-').toLowerCase();
const short = target.split('-')[0];
const dict = i18nDict[target] || i18nDict[short] || i18nDict["en"] || {};
const raw = dict[key] || i18nDict["en"]?.[key] || key;
const replacements = Array.prototype.slice.call(arguments, 2);
return replacements.reduce((s, val, i) => s.replace(`{${i}}`, val), raw);
}
function applyI18n(forcedLang) {
if (typeof document === 'undefined') return;
syncI18nDict();
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
const type = el.getAttribute('data-i18n-type');
const translation = t(key, forcedLang);
if (translation && translation !== key) {
if (type === 'placeholder' || el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
el.placeholder = translation;
} else if (type === 'title' || el.hasAttribute('data-i18n-title')) {
el.title = translation;
} else if (type === 'value') {
el.value = translation;
} else if (type === 'html' || (translation.includes('<') && translation.includes('>'))) {
el.innerHTML = translation;
} else {
el.innerText = translation;
}
}
});
}
let globalUiLang = getBrowserLang();
async function initUILanguage() {
const uiSelect = document.getElementById('uiLangSelect');
if (!uiSelect) return;
const storage = await safeGetStorage(['ui_language'], true);
if (storage?.ui_language) {
uiSelect.value = storage.ui_language;
globalUiLang = storage.ui_language;
} else {
uiSelect.value = globalUiLang;
}
applyI18n(globalUiLang);
}
function standardizeResult(raw, originalText) {
const schema = {
basic: "",
phonetic: "",
dictData: [],
isFallback: false,
engine: ""
};
if (!raw) {
schema.basic = originalText;
schema.isFallback = true;
return schema;
}
if (typeof raw === 'string') {
schema.basic = raw;
} else if (typeof raw === 'object') {
schema.basic = raw.basic || raw.translation || raw.text || originalText;
schema.phonetic = raw.phonetic || "";
schema.dictData = raw.dictData || [];
schema.engine = raw.engine || "";
}
return schema;
}
let toastTimer = null;
function showToast(message, type = 'info', duration = 5000) {
let toast = null;
if (window.shadowHost?.shadowRoot) {
toast = window.shadowHost.shadowRoot.getElementById('toast');
}
if (!toast) toast = document.getElementById('toast');
if (!toast) return;
clearTimeout(toastTimer);
if (type === 'error') toast.style.borderColor = '#f87171';
else if (type === 'success') toast.style.borderColor = '#4ade80';
else toast.style.borderColor = '#475569';
toast.textContent = message;
toast.classList.remove('toast-hidden');
toastTimer = setTimeout(() => {
toast.classList.add('toast-hidden');
}, duration);
}
function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return hash;
}
const hash = (str) => {
let h = 0;
for (let i = 0; i < str.length; i++) {
h = Math.imul(31, h) + str.charCodeAt(i) | 0;
}
return Math.abs(h).toString(16);
};
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
/**
* IndexedDB 基础配置与操作封装
*
* 核心 IDB 模块 - 采用前缀隔离策略
* tr_ : 翻译缓存 (Translation Cache)
* vb_ : 生词本 (Vocabulary Book)
*/
const idb = {
async get(keys) {
return await safeSendMessage({ type: 'IDB_GET', keys });
},
async getAll(prefix = '') {
const res = await safeSendMessage({ type: 'IDB_GET_ALL', prefix });
return res || {};
},
async set(items) {
return await safeSendMessage({ type: 'IDB_SET', items });
},
async remove(key) {
return await safeSendMessage({ type: 'IDB_REMOVE', key });
},
async getSize(prefix) {
return await safeSendMessage({ type: 'IDB_GET_SIZE', prefix });
},
async getCount(prefix) {
return await safeSendMessage({ type: 'IDB_GET_COUNT', prefix });
},
async clearPrefix(prefix) {
return await safeSendMessage({ type: 'IDB_CLEAR_PREFIX', prefix });
},
cache: {
async get(key) {
const isArray = Array.isArray(key);
const keys = isArray ? key : [key];
const fullKeys = keys.map(k => k.startsWith('tr_') ? k : `tr_${k}`);
const res = await idb.get(fullKeys);
if (isArray) return res || {};
return res ? res[fullKeys[0]] : null;
},
async set(key, value) {
const fullKey = key.startsWith('tr_') ? key : `tr_${key}`;
const dataToSet = typeof value === 'object' ? value : { basic: value };
return idb.set({ [fullKey]: { ...dataToSet, ts: Date.now() } });
},
async remove(key) {
const fullKey = key.startsWith('tr_') ? key : `tr_${key}`;
return idb.remove(fullKey);
},
async getCount() {
return idb.getCount('tr_');
},
async getSize() {
return idb.getSize('tr_');
},
async clearAll() {
return idb.clearPrefix('tr_');
}
},
vocabulary: {
async add(word, dataOrEntry) {
const cleanWord = word.trim().toLowerCase();
const fullKey = `vb_${cleanWord}`;
const now = Date.now();
let entry;
if (dataOrEntry && dataOrEntry.id) {
entry = dataOrEntry;
} else {
entry = {
id: crypto.randomUUID(),
word: cleanWord,
trans: dataOrEntry.trans || dataOrEntry.translation || dataOrEntry.basic || dataOrEntry.t || '',
src: dataOrEntry.src || dataOrEntry.url || '',
title: dataOrEntry.title || '',
date: dataOrEntry.date || dataOrEntry.ts || now,
updated: now,
deleted: false,
lv: dataOrEntry.lv || 0
};
}
return idb.set({ [fullKey]: entry });
},
async get(word) {
const fullKey = `vb_${word.trim().toLowerCase()}`;
const res = await idb.get([fullKey]);
return res ? res[fullKey] : null;
},
async getAll() {
const results = await idb.getAll('vb_');
return Object.values(results || {});
},
async remove(word) {
const fullKey = `vb_${word.trim().toLowerCase()}`;
return idb.remove(fullKey);
},
async getCount() {
return idb.getCount('vb_');
},
async getSize() {
return idb.getSize('vb_');
},
async clearAll() {
return idb.clearPrefix('vb_');
}
}
};
// 只和"文本内容 + 目标语言 + 翻译模式"相关,不含引擎信息,方便跨引擎复用/借用缓存时精确匹配
function getContentFingerprint(text, lang, mode = 'context') {
const coreText = text
.replace(/[\s\n\r\t.,!?;:。,!?、・「」]/g, "")
.toLowerCase();
const safeLang = (lang || 'zh-cn').replace('_', '-').toLowerCase();
const modeSuffix = mode === 'dictionary' ? '_dict' : '';
const contentPart = typeof hash === 'function' ? hash(coreText) : coreText.substring(0, 50);
return `${contentPart}_${safeLang}${modeSuffix}`;
}
function getCacheKey(text, engine, lang, mode = 'context', instanceId = null) {
if (!text) return '';
const safeEngine = (engine || getRuntimeDefaultEngine()).toLowerCase();
// 内置引擎(google/bing)全局唯一,id 本身已含引擎类型信息,不需要再拼一次
const isBuiltinInstance = instanceId === 'google_builtin' || instanceId === 'bing_builtin';
const engineIdentifier = (instanceId && !isBuiltinInstance) ? `${safeEngine}-${instanceId}` : safeEngine;
const fingerprint = getContentFingerprint(text, lang, mode);
return `tr_${engineIdentifier}_${fingerprint}`;
}
function esc(str) {
return String(str ?? "")
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/</g, "<")
.replace(/>/g, ">");
}
/**
* 获取详细翻译结果
* 适配多级数据结构:基础译文、音标、详细词典释义
*/
if (typeof pendingRequests === 'undefined') {
pendingRequests = new Set();
}
const NON_LATIN_TARGETS = {
'zh': { remove: /[\u4e00-\u9fa5\u4E00-\u9FFF]/g },
'ja': { remove: /[\u3040-\u30FF\u30FC\p{Script=Han}]/gu },
'ko': { remove: /[\uAC00-\uD7AF]/g },
'th': { remove: /[\u0E00-\u0E7F]/g },
'ar': { remove: /[\u0600-\u06FF]/g },
'fa': { remove: /[\u0600-\u06FF]/g },
'he': { remove: /[\u0590-\u05FF]/g },
'hi': { remove: /[\u0900-\u097F]/g },
'ru': { remove: /[\u0400-\u04FF]/g },
'uk': { remove: /[\u0400-\u04FF]/g },
'el': { remove: /[\u0370-\u03FF]/g },
};
const LANGUAGE_PATTERNS = {
'ko': /\p{Script=Hangul}/u,
'ru': /\p{Script=Cyrillic}/u,
'uk': /\p{Script=Cyrillic}/u,
'bg': /\p{Script=Cyrillic}/u,
'th': /\p{Script=Thai}/u,
'ar': /\p{Script=Arabic}/u,
'fa': /\p{Script=Arabic}/u,
'he': /\p{Script=Hebrew}/u,
'hi': /\p{Script=Devanagari}/u,
'bn': /\p{Script=Bengali}/u,
'el': /\p{Script=Greek}/u,
'vi': /[àáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵĐđ]/i,
'tr': /[ĞğİıŞş]/,
'pl': /[ąćęłńśźżĄĆĘŁŃŚŹŻ]/,
'cs': /[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]/,
'sk': /[áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]/,
'hu': /[őűŐŰ]/,
'ro': /[șțȘȚăĂâÂîÎ]/,
'sl': /[蚞ȊŽćđĆĐ]/,
'hr': /[蚞ȊŽćđĆĐ]/,
'lv': /[āēīūļķģņČčŠšŽž]/,
'lt': /[ąčęėįšųūžĄČĘĖĮŠŲŪŽ]/,
'et': /[äöüõÄÖÜÕšžŠŽ]/,
'sv': /[åäöÅÄÖ]/,
'da': /[åæøÅÆØ]/,
'no': /[åæøÅÆØ]/,
'fi': /[äöÄÖ]/,
'fr': /[àâæçèéêëîïôœùûüÿÀÂÆÇÈÉÊËÎÏÔŒÙÛÜŸ]/,
'de': /[äöüßÄÖÜ]/,
'es': /[áéíóúüñÁÉÍÓÚÜÑ]/,
'pt': /[ãõçâêôÃÕÇÂÊÔáéíóúÁÉÍÓÚàÀ]/,
'it': /[àèéìòùÀÈÉÌÒÙ]/,
'nl': /[éëïóöüÉËÏÓÖÜ]/,
};
const LATIN_BASED_LANGS = new Set([
'en', 'fr', 'de', 'es', 'it', 'nl', 'pt', 'sv', 'da', 'no', 'fi',
'tr', 'pl', 'cs', 'sk', 'hu', 'ro', 'sl', 'hr', 'lv', 'lt', 'et', 'vi'
]);
function detectLatinLanguage(cleanText, cleanChars, targetPrefix) {
const targetPattern = LANGUAGE_PATTERNS[targetPrefix];
if (targetPattern) {
if (targetPattern.test(cleanText)) {
return true;
}
const hasOtherFeature = Object.entries(LANGUAGE_PATTERNS).some(([lang, pattern]) =>
LATIN_BASED_LANGS.has(lang) && lang !== targetPrefix && pattern.test(cleanText)
);
if (hasOtherFeature) return false;
}
return false;
}
function detectIsAlreadyTarget(text, targetLang) {
if (!text) return true;
if (/^\s*[\d.,\s\-+%$€¥£#@!?]+\s*$/.test(text)) return true;
const textWithoutUrls = text.replace(/https?:\/\/[^\s]+/g, '');
const hasCJK = /[\u4e00-\u9fa5\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/.test(textWithoutUrls);
if (textWithoutUrls.length > 12 && /[\d*]/.test(textWithoutUrls) && !/\s/.test(textWithoutUrls) && !hasCJK) return true;
const cleanChars = Array.from(textWithoutUrls).filter(char =>
/\p{L}/u.test(char) &&
!/[\s\n\r\t\u00A0\u2000-\u200a\u2028\u2029\u3000\ufeff]/u.test(char) &&
!/\p{P}|\p{S}/u.test(char)
);
if (cleanChars.length === 0) return true;
const cleanText = cleanChars.join('');
const prefix = (targetLang || 'en').toLowerCase().slice(0, 2);
if (prefix === 'en') {
const hasNonEnglishLatin = cleanChars.some(char =>
/[äöüßÄÖÜàâæçéèêëîïôœùûüÿáéíóúñãõîêôû]/i.test(char)
);
if (hasNonEnglishLatin) return false;
return false;
}
if (prefix === 'ja') {
const hasKana = /[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(cleanText);
if (!hasKana) return false;
const jaCount = cleanChars.filter(char =>
/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(char) ||
/[\u30FC\u30A0\u30FB\u30FD\u30FE]/.test(char)
).length;
return jaCount / cleanChars.length >= 0.7;
}
if (prefix === 'zh') {
const hasKana = cleanChars.some(c => /\p{Script=Hiragana}|\p{Script=Katakana}/u.test(c));
if (hasKana) return false;
const hanCount = cleanChars.filter(c => /\p{Script=Han}/u.test(c)).length;
const latinCount = cleanChars.filter(c => /[a-zA-Z]/.test(c)).length;
const totalCount = cleanChars.length;
if (hanCount === 0) return false;
if (totalCount <= 15) {
// 短文本:汉字数量 >= 拉丁字母数量,认为主体是中文
return hanCount >= latinCount;
}
// 长文本:汉字绝对数量足够且占优
if (hanCount >= 10 && hanCount >= latinCount * 0.6) return true;
return hanCount / totalCount >= 0.8;
}
if (LANGUAGE_PATTERNS[prefix] && !LATIN_BASED_LANGS.has(prefix)) {
const scriptPattern = LANGUAGE_PATTERNS[prefix];
const scriptCount = cleanChars.filter(c => scriptPattern.test(c)).length;
const latinCount = cleanChars.filter(c => /[a-zA-Z]/.test(c)).length;
const totalCount = cleanChars.length;
if (scriptCount === 0) return false;
if (totalCount <= 15) {
// 短文本:目标文字数量 >= 拉丁字母数量
return scriptCount >= latinCount;
}
// 长文本:目标文字数量足够且占优
if (scriptCount >= 8 && scriptCount >= latinCount * 0.6) return true;
return scriptCount / totalCount >= 0.7;
}
if (LATIN_BASED_LANGS.has(prefix)) {
return detectLatinLanguage(cleanText, cleanChars, prefix);
}
return false;
}
const POS_MAP = {
'名词': {
'zh-cn': '名词', 'zh-tw': '名詞', 'ja': '名詞', 'ko': '명사',
'en': 'n.', 'fr': 'n.', 'de': 'Subst.'
},
'动词': {
'zh-cn': '动词', 'zh-tw': '動詞', 'ja': '動詞', 'ko': '동사',
'en': 'v.', 'fr': 'v.', 'de': 'V.'
},
'形容词': {
'zh-cn': '形容词', 'zh-tw': '形容詞', 'ja': '形容詞', 'ko': '형용사',
'en': 'adj.', 'fr': 'adj.', 'de': 'Adj.'
},
'副词': {
'zh-cn': '副词', 'zh-tw': '副詞', 'ja': '副詞', 'ko': '부사',
'en': 'adv.', 'fr': 'adv.', 'de': 'Adv.'
},
'介词': {
'zh-cn': '介词', 'zh-tw': '介系詞', 'ja': '前置詞', 'ko': '전치사',
'en': 'prep.', 'fr': 'prép.', 'de': 'Präp.'
},
'连词': {
'zh-cn': '连词', 'zh-tw': '連接詞', 'ja': '接続詞', 'ko': '접속사',
'en': 'conj.', 'fr': 'conj.', 'de': 'Konj.'
},
'代词': {
'zh-cn': '代词', 'zh-tw': '代名詞', 'ja': '代名詞', 'ko': '대명사',
'en': 'pron.', 'fr': 'pron.', 'de': 'Pron.'
},
'冠词': {
'zh-cn': '冠词', 'zh-tw': '冠詞', 'ja': '冠詞', 'ko': '관사',
'en': 'art.', 'fr': 'art.', 'de': 'Art.'
},
'感叹词': {