Repository navigation
Expand file tree
/
Copy pathbuild.js
More file actions
1746 lines (1646 loc) · 107 KB
/
Copy pathbuild.js
File metadata and controls
1746 lines (1646 loc) · 107 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
#!/usr/bin/env node
// build.js — Build and package the extension
// Usage:
// node build.js → Chrome/Safari build, GLOBAL flavor (dist/)
// node build.js --flavor china → Chrome/Safari build, CHINA flavor (dist-china/)
// node build.js firefox → Firefox build (dist-firefox/)
//
// Flavor: GLOBAL ships Google/OpenAI/Claude/DeepSeek/GLM/Qwen/Kimi + custom.
// CHINA ships domestic only (DeepSeek/GLM/Qwen/Kimi + brand-free custom endpoints)
// and MUST contain no OpenAI/ChatGPT/Claude brand strings or api.openai.com /
// api.anthropic.com endpoints (App Store Guideline 5). Enforced by the compliance
// gate below. Provider set is the single source of truth in build/providers.config.js.
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const argv = process.argv.slice(2);
const TARGET = argv.includes('firefox') ? 'firefox' : 'chrome';
// CI package smoke is a BUILD-ONLY flag, not an environment string. It is an
// exact argv token (no trim, no case folding, no near-match) and it only opts
// into the placeholder gate so a runner without backend secrets can exercise
// the manifest / compliance gates. It is never shippable: the build forces
// SKIP_ZIP and writes .not-shippable into dist and dist-app*.
// releaseReason() still refuses a plain CI build; the raw-exact ci-package-smoke
// context is the only CI allowance it carries.
const CI_PACKAGE_SMOKE = argv.includes('--ci-package-smoke');
function envTruthy(v) {
return typeof v === 'string' && v.trim() !== '' && !/^(0|false|no|off)$/i.test(v.trim());
}
if (CI_PACKAGE_SMOKE) {
if (process.env.MT_RELEASE === '1') {
err('--ci-package-smoke refused: MT_RELEASE=1 is a release build');
process.exit(1);
}
if (!envTruthy(process.env.CI)) {
err('--ci-package-smoke is CI-only: process.env.CI must be truthy');
process.exit(1);
}
}
function readFlavor() {
const i = argv.findIndex((a) => a === '--flavor');
if (i >= 0 && argv[i + 1]) return argv[i + 1];
const kv = argv.find((a) => a.startsWith('--flavor='));
return kv ? kv.split('=')[1] : 'global';
}
const FLAVOR = readFlavor() === 'china' ? 'china' : 'global';
const ROOT = __dirname;
const SRC = path.join(ROOT, 'extension');
const DIST = path.join(ROOT,
TARGET === 'firefox' ? 'dist-firefox' : (FLAVOR === 'china' ? 'dist-china' : 'dist'));
const ZIP = path.join(ROOT,
TARGET === 'firefox' ? 'belliedmonkeytranslator-firefox.xpi'
: (FLAVOR === 'china' ? 'belliedmonkeytranslator-china.zip' : 'belliedmonkeytranslator.zip'));
// The host-app bundle is a second emission path (BEL-197). Its directory name is
// needed by the BEL-259 marker writer as well as by the app-bundle block below.
const APP_OUT_NAME = FLAVOR === 'china' ? 'dist-app-china' : 'dist-app';
// BEL-172 (P0 scrub): backend host / anon key are build-time values. The source carries
// inert placeholders; this installs the injected config into the require cache so every
// registry generated below sees the same values. With no env/`.local/backend.env`, the
// build still succeeds but deliberately points at *.invalid — it cannot reach a real
// backend, and `log` says so below.
const backendInject = require('./build/backend-inject.js');
const sentryInject = require('./build/sentry-inject.js');
const backendInjection = backendInject.install(ROOT);
// BEL-280: TEST-BUILD-ONLY relay 400 probe. Exact enum or the build fails (see
// build/test400.js); unset ⇒ every emitted bundle gets the sentinels replaced by ''.
const test400 = require('./build/test400.js');
const TEST400_REASON = test400.reasonFromEnv(process.env);
// 免费额度三档的模型名:与三张注册表、中继 /spec 同源(BEL-236 单源)。
const GRANT_MODELS = require('./build/grant-models.config.js');
// Set to a reason string when the build is deliberately NOT shippable. dist/ is
// still written (so it can be loaded unpacked for testing) but the packaged
// artifact is withheld — see the Gate B escape hatch in validateManifest().
let SKIP_ZIP = null;
// BEL-280: the relay 400 probe is a TEST-BUILD-ONLY affordance. Setting the flag
// makes the tree explicitly non-shippable (marker + no zip) and the independent
// marker scan in scripts/check-shippable.js refuses it again before archive/upload.
if (TEST400_REASON) {
SKIP_ZIP = `test-only relay 400 probe (MT_TEST_400=${TEST400_REASON})`;
log(`\x1b[33mMT_TEST_400=${TEST400_REASON} — TEST BUILD ONLY; zip withheld, .not-shippable written\x1b[0m`);
}
// BEL-259: local-preview escape hatch. Exactly the string "1"; refused in any
// release-like context. When it is on, SKIP_ZIP is forced and .not-shippable is
// written into BOTH dist and dist-app*. See backendInject.placeholderMode().
// --ci-package-smoke is the separate BUILD-ONLY opt-in for CI: it is validated
// above, forces its own non-shippable marker, and does not change releaseReason().
const PLACEHOLDER = backendInject.placeholderMode(process.env);
if (!CI_PACKAGE_SMOKE && PLACEHOLDER.enabled && PLACEHOLDER.refused) {
err(`MT_ALLOW_PLACEHOLDER_BACKEND=1 is local-preview only, but this looks like a release build (${PLACEHOLDER.refused})`);
process.exit(1);
}
const ALLOW_PLACEHOLDER = CI_PACKAGE_SMOKE || PLACEHOLDER.enabled;
// RETIRED as of Gate B (v1.4.0, 2026-08-09): the source switch is now true, so
// `MT_SYNC=on` is a no-op kept only so old muscle memory / scripts don't fail.
// It used to flip the OUTPUT's `enabled` while the source stayed false — the
// self-use TestFlight channel for builds 14–23.
const SYNC_ON = process.env.MT_SYNC === 'on';
// Single-occurrence flip of the shipping switch inside a module's TEXT.
// Refuses to guess: zero or multiple matches fail the build, so a reshaped
// backend.config.js cannot be silently half-flipped. Since Gate B this runs in
// the OPPOSITE direction, for the CHINA flavor only: the China app is
// unreleased and its data-export compliance (PIPL, cross-border) has not been
// evaluated, so its artifact ships with sync OFF until that is its own gated
// release decision.
function flipSyncFlag(text, what, direction) {
const on = direction === 'on';
// **缩进是判据的一部分**(2026-09-08)。原来用的是裸子串 `enabled: true,`,
// 而免费额度那个块里也有一个 `enabled`(四格缩进)—— 今天它是 false 所以碰巧
// 只命中一处;G6 把它翻成 true 的那一刻,中国版构建会当场以「expected exactly one」
// 死掉,而报错指向的是同步开关,跟真正的原因隔着十万八千里。
// 顶层那个同步开关是**两格缩进**,只认它。
const re = on ? /^ {2}enabled: false,/m : /^ {2}enabled: true,/m;
const all = text.match(new RegExp(re.source, 'gm')) || [];
if (all.length !== 1) {
console.error(`✗ sync flip: expected exactly one top-level \`${re.source}\` in ${what}, got ${all.length}`);
process.exit(1);
}
return text.replace(re, on
? ' enabled: true, // flipped at build time — NOT SHIPPABLE'
: ' enabled: false, // CHINA build: sync off until its own compliance gate (build.js)');
}
// 中国版只提供 Apple 登录(2026-09-03 用户裁定)。
//
// Google 在中国大陆连不上。留着那个按钮,对绝大多数中国版用户就是一个点了转圈然后
// 失败的东西 —— 与这一轮反复在修的「点了没反应」是同一类,只是原因在网络那一侧。
// 而「能不能连上」是**用户所在网络的事实**,客户端猜不出来,只能由 flavor 决定。
//
// 判据同 flipSyncFlag:**恰好一处**,多一处或没有都退出 —— 静默改错一处的代价是
// 中国版包里留着一个死按钮,而拆包 grep 之前没人看得见。
// ── 中国版的境内后端(§C)────────────────────────────────────────────────
//
// 读**源码树**那一份,不是产物 —— 判据要在改写之前就定下来,否则会读到自己刚写的值。
function chinaBackend() {
const cfg = require('./extension/learn/backend.config.js');
return (cfg && cfg.china) || { ready: false, url: '', anonKey: '' };
}
function chinaBackendReady() {
const cn = chinaBackend();
return cn.ready === true && !!cn.url && !!cn.anonKey;
}
// 中国版额度的境内中继(方案 C,learning-design §8.10.1)。未就绪 → null(今天的值,
// 产物与从前逐字相同)。**就绪却配错就让构建失败**,不静默退回 null —— 「以为发了额度、
// 其实没有」与「以为原文在境内、其实在东京」都是看不出来的谎。
function chinaGrant() {
const cfg = require('./extension/learn/backend.config.js');
const cn = (cfg.grant && cfg.grant.china) || {};
if (cn.ready !== true) return null;
const bad = (why) => { err('grant.china.ready=true 但 ' + why + ' —— 修好配置或把 ready 改回 false'); process.exit(1); };
if (!cfg.grant.enabled) bad('grant.enabled 是 false');
let u; try { u = new URL(cn.relayUrl); } catch (_) { bad('relayUrl 不是合法地址(' + JSON.stringify(cn.relayUrl) + ')'); }
if (u.protocol !== 'https:') bad('relayUrl 不是 https');
if (/\.supabase\.co$/i.test(u.hostname)) bad('relayUrl 在 *.supabase.co(那是东京,原文会出境)');
return { relayUrl: String(cn.relayUrl).replace(/\/+$/, ''), host: u.hostname,
vendor: cn.vendor || 'dashscope',
// 披露里的名字取注册表(一处真相):qwen 条目的中国区 label。
vendorLabel: (() => { const q = require('./build/providers.config.js').find((p) => p.id === 'qwen');
return (q && q.label && (q.label.china || q.label)) || 'dashscope'; })() };
}
// 把产物里的 url / anonKey 换成境内那一套。
//
// 与 flipSyncFlag / limitProviders 同一条纪律:**恰好一处**,否则 exit(1)。
// 一个静默的 0 处替换会产出一个「说自己是中国版、其实还在打东京」的包 ——
// 那是这个仓库最贵的那类谎,而它在产物里完全看不出来。
function switchBackend(text, what, cn) {
// 切之前的地址留在产物里(previousUrl):bindCorpus 靠它认出「主库是在旧后端认领的」
// (learning-design §8.4.3「后端换了」)—— 否则老用户在新后端一登录,本机的卡就挂到一个再也登不上的身份下。
//
// BEL-260:空 previousUrl 是**禁止项**,不是「等同于当前后端」。priorBackend() 会把它
// 退成 CN,于是老会话/无记录的主库被误判成本机 CN 主库,CN 账号拿到空库,旧卡看不见
// (2026-09-22 的形状)。这里 fail closed,防止上游源码被改成空 url 后静默写出空哨兵。
const prev = (/^ url: '([^']*)',/m.exec(text) || [])[1] || '';
if (!prev) {
console.error(`✗ backend switch: ${what} 的顶层 url 为空 —— 不能写入空的 previousUrl(BEL-260)`);
process.exit(1);
}
text = text.replace(/^( url: '[^']*',.*)$/m, `$1\n previousUrl: '${prev}', // CHINA build: 切后端之前的地址(build.js)`);
const out = [['url', cn.url], ['anonKey', cn.anonKey]].reduce((acc, [key, val]) => {
// 只匹配**顶层**那一条(行首两个空格),不碰 china 块里的同名键(四个空格)。
const RE = new RegExp(`^ ${key}: '[^']*',`, 'm');
const hits = acc.match(new RegExp(RE.source, 'gm')) || [];
if (hits.length !== 1) {
console.error(`✗ backend switch: expected exactly one top-level \`${key}\` in ${what}, got ${hits.length}`);
process.exit(1);
}
return acc.replace(RE, ` ${key}: '${val}', // CHINA build: 境内后端(build.js)`);
}, text);
// 产物里不该再留着那个块 —— 它只是源码里的一个决策记录,进了包就是第二个可信来源。
return out.replace(/\n china: \{[\s\S]*?\n \},\n/, '\n');
}
function limitProviders(text, what, list) {
const NEEDLE = "providers: ['apple', 'google'],";
const first = text.indexOf(NEEDLE);
if (first < 0 || text.indexOf(NEEDLE, first + 1) >= 0) {
console.error(`✗ providers: expected exactly one \`${NEEDLE}\` in ${what}`);
process.exit(1);
}
return text.replace(NEEDLE,
`providers: ${JSON.stringify(list).replace(/"/g, "'")}, // CHINA build: Google 在大陆连不上(build.js)`);
}
// 默认引擎必须是**本 flavor 注册表里存在**的 id。
//
// 2026-08-22 实测:中国版出货包的默认是 `provider: 'google'`,而 google 的 flavors 是
// ['global'],于是它在中国版注册表里根本不存在。运行时 `providerById` 返回 null,
// `callProvider` 的 `!p` 分支静默落到 translate.googleapis.com —— 一份刚装好、没填
// 任何 Key 的中国版,真的把 38 段译文翻了出来,输出与直接打 Google 的返回逐字相同。
//
// 而设置页的 <select> 里没有 google 这个选项,浏览器把它强制显示成第一项(DeepSeek),
// 于是**界面写着 DeepSeek,实际发的是 Google**。国内用户那条地址还不通,一段段等到
// 20 秒超时——就是「翻译中…」不动的形状。静默兜底 + 界面与运行时不一致,两样都占。
function rewriteDefaultProvider(text, what, providerId) {
const NEEDLE = "provider: 'google',";
const first = text.indexOf(NEEDLE);
if (first < 0 || text.indexOf(NEEDLE, first + 1) >= 0) {
console.error(`✗ default provider rewrite: expected exactly one \`${NEEDLE}\` in ${what}`);
process.exit(1);
}
return text.replace(NEEDLE, `provider: '${providerId}', // CHINA build: google is not in this flavor's registry (build.js)`);
}
// 门禁:两个 flavor 都查。**一个 flavor 的默认值指向它自己注册表里没有的引擎,是错误**,
// 而这种错误在构建期完全看得见——上面那个 bug 出货了才被真机发现,不该再有第二次。
function defaultProviderGate(dir, label, flavor) {
const bg = fs.readFileSync(path.join(dir, 'background.js'), 'utf8');
const m = /provider:\s*'([a-z_]+)'/.exec(bg);
if (!m) { err(`${label}: 在 background.js 里找不到默认 provider`); return; }
const want = m[1];
const reg = require('./build/providers.config.js');
const ids = reg.filter((p) => p.flavors.includes(flavor)).map((p) => p.id);
if (!ids.includes(want)) {
err(`${label}: 默认引擎 '${want}' 不在 ${flavor} 注册表里(${ids.join(', ')})`
+ ' —— 运行时会静默落到 translateGoogle');
}
}
// ─── Helpers ──────────────────────────────────────────────────────────────
function copyDir(src, dst) {
fs.mkdirSync(dst, { recursive: true });
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const srcPath = path.join(src, entry.name);
const dstPath = path.join(dst, entry.name);
if (entry.isDirectory()) copyDir(srcPath, dstPath);
else if (entry.name.endsWith('.jsx')) continue; // bundle 源码(domain-design §10)不进 dist
else fs.copyFileSync(srcPath, dstPath);
}
}
function log(msg) { console.log(`\x1b[32m✓\x1b[0m ${msg}`); }
function err(msg) { console.error(`\x1b[31m✗\x1b[0m ${msg}`); }
if (FLAVOR === 'china' && TARGET === 'firefox') { err('--flavor china is only for the Chrome/Safari build'); process.exit(1); }
// ─── i18n bundle ────────────────────────────────────────────────────────────
// chrome.i18n.getMessage is locked to the browser/OS locale and can't be switched
// at runtime. To support a user-selectable UI language we ship a synchronous JS
// table of all locale messages, consulted by t() before falling back to
// chrome.i18n. Generated from _locales/ so it never drifts.
// Chrome resolves `_locales/<dir>` ONLY for names on its supported-locale list, and it
// fails silently: an unsupported directory is simply never read, so `__MSG_*` in the
// manifest falls back to default_locale and the Chrome Web Store does not even offer that
// language for a store listing. Nothing in the repo can tell you — `_locales/pt` shipped a
// complete, key-identical, JSON-valid messages.json for three releases while Chrome ignored
// every byte of it, and it was only caught by noticing the store dashboard said 10 languages
// where the package had 11 (issue #65).
//
// So the directory names are a build gate, like version drift and data_collection_permissions.
// List per https://developer.chrome.com/docs/extensions/reference/api/i18n — note there is no
// bare `pt` (only pt_BR / pt_PT) and no bare `en_*` shortcuts beyond the ones below.
const CHROME_LOCALES = new Set([
'am', 'ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'en_GB', 'en_US', 'es',
'es_419', 'et', 'fa', 'fi', 'fil', 'fr', 'gu', 'he', 'hi', 'hr', 'hu', 'id', 'it',
'ja', 'kn', 'ko', 'lt', 'lv', 'ml', 'mr', 'ms', 'nl', 'no', 'pl', 'pt_BR', 'pt_PT',
'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'sw', 'ta', 'te', 'th', 'tr', 'uk', 'vi',
'zh_CN', 'zh_TW',
]);
function generateI18nMessages(dir) {
const localesDir = path.join(dir, '_locales');
const out = {};
for (const loc of fs.readdirSync(localesDir)) {
const f = path.join(localesDir, loc, 'messages.json');
if (!fs.existsSync(f)) continue;
if (!CHROME_LOCALES.has(loc)) {
err(`_locales/${loc} is not a locale Chrome recognises — it would be silently ignored ` +
`(no bare "pt": use pt_BR / pt_PT). See issue #65.`);
process.exit(1);
}
let raw;
try { raw = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { err(`Bad JSON in _locales/${loc}/messages.json`); process.exit(1); }
const flat = {};
for (const [k, v] of Object.entries(raw)) { if (v && typeof v.message === 'string') flat[k] = v.message; }
out[loc] = flat;
}
const banner = '// AUTO-GENERATED by build.js from _locales/*/messages.json — do not edit by hand.\n';
const body = 'window.MT_I18N_MESSAGES = ' + JSON.stringify(out) + ';\n';
fs.writeFileSync(path.join(dir, 'content', 'i18n-messages.js'), banner + body);
log(`Generated content/i18n-messages.js (${Object.keys(out).length} locales)`);
}
// ─── Provider registry bundle (per flavor) ──────────────────────────────────
// build/providers.config.js is the single source of truth. Filter it by flavor,
// resolve per-flavor defaultBase/label to single values, and emit providers.gen.js
// (window.MT_FLAVOR + window.MT_PROVIDERS) read by translation-api / options / popup.
// Per-flavor resolution, shared by all three registry emitters. An authored value is
// either a plain value or a { china, global } map; the map form is a WRITING
// convenience, never something the runtime should see — domain-design §7's rule is
// that region is decided at build time and never branches per request.
function pickFlavor(flavor) {
return (v) => (v && typeof v === 'object' && !Array.isArray(v)) ? (v[flavor] ?? null) : (v ?? null);
}
function generateProviders(dir, flavor) {
const CONFIG = require('./build/providers.config.js');
const pick = pickFlavor(flavor);
const providers = CONFIG
.filter((p) => p.flavors.includes(flavor))
.map((p) => ({
id: p.id, type: p.type, label: pick(p.label), labelKey: p.labelKey || null,
defaultEndpoint: pick(p.defaultEndpoint), placeholder: p.placeholder || null,
// 跟 label / defaultEndpoint 一样支持 { china, global } 映射。原来它漏了 pick,
// 于是两个 flavor 只能共用一个模型名 —— 而同一家厂商的国内外平台完全可能上下架
// 不同的模型(实测 2026-08-21:moonshot 国际站已经没有 moonshot-v1-8k 了)。
defaultModel: pick(p.defaultModel) || '',
needsKey: !!p.needsKey, supportsBaseUrl: !!p.supportsBaseUrl,
supportsModel: !!p.supportsModel, requiresEndpoint: !!p.requiresEndpoint, hintKey: p.hintKey || null,
// §8.10:免费额度那一档。运行时靠它把中继排除出一键配置与所有下拉 ——
// 它没有可粘的 key(令牌是登录之后系统发的),出现在选择器里就是一个必然
// 配不成功的选项。生成器漏掉这个字段的话,运行时那道判断永远读到 undefined。
grantOnly: !!p.grantOnly,
// 「去哪儿申请这把 key」。按 flavor 取,同 defaultEndpoint / label。
keyUrl: pick(p.keyUrl) || null,
// 识图能力(§9.7):true / false / 缺省=未知。缺省时不发这个键。
...(p.vision === undefined ? {} : { vision: !!p.vision }),
// 一键卡是否列出这个平台(1.23.4,BEL-236)。缺省 true;只有显式 false 才发键,
// 生成物因此不会因为加了一个字段而整体变样。运行时读 undefined = true。
...(p.oneClick === false ? { oneClick: false } : {}),
}));
// The model-parameter table rides this same file rather than getting one of its own.
// providers.gen.js is already on every surface that resolves an endpoint (both
// content_scripts blocks, options, popup, review, and the app bundle), so riding it
// costs ZERO load-site edits — and a load site missed is the worst failure this table
// has: the runtime would silently see an empty table, fall back to minimal bodies
// everywhere, and never报错. (`palette.gen.js` is the precedent for one emitter
// carrying more than one global.)
//
// It inherits the flavor filter for free, which it needs: `api.openai.com`,
// `api.anthropic.com` and the bare id `openai` are the three strings in this table
// that the China compliance grep would hit.
//
// The output field list is an ALLOWLIST, same discipline as the providers map above —
// a field added to the config but not named here silently never reaches the runtime.
// Two deliberate omissions:
// · `note` — maintainer evidence, not runtime data, and the field most likely to
// carry a vendor's error prose verbatim. Keeping it out shrinks the brand surface
// to `id` / `hosts` / `models`.
// · `!!` coercion — `temperature` and `budget` are THREE-state (true / false /
// absent). `!!e.temperature` would flatten "we don't know" into "not supported",
// which is exactly the distinction this table exists to carry. JSON.stringify
// drops `undefined` keys, which is precisely the encoding we want.
const PARAMS = require('./build/model-params.config.js');
const params = PARAMS
.filter((e) => e.flavors.includes(flavor))
.map((e) => ({
id: e.id,
hosts: (e.hosts || []).map((h) => String(h).toLowerCase()),
models: (e.models || []).map((m) => String(m).toLowerCase()),
temperature: 'temperature' in e ? e.temperature : undefined,
budget: 'budget' in e ? e.budget : undefined,
systemRole: e.systemRole || undefined,
reasoning: e.reasoning || undefined,
}));
const banner = '// AUTO-GENERATED by build.js from build/providers.config.js '
+ '+ build/model-params.config.js — do not edit by hand.\n';
// 「这个构建编进同步了吗」。内容脚本要它 —— 官网试翻页上的交接块会说「登录之后
// 卡片才到 App」,而中国版扩展的登录入口是被整节 remove 掉的,那句话对他就是死路。
//
// 为什么不直接在内容脚本里加载 backend.config.js:那个文件带着后端地址与 anon key,
// 而内容脚本会注入到**每一个页面**。判据搭已经在场的 providers.gen.js 的车,只发
// 一个布尔值,凭证一个字节都不扩散。
//
// 判据取自 backend.config.js 的 enabled 本身(**按值,不按 flavor 名**)——
// 中国版那个 false 是 build 期翻的,所以这里读的是翻过之后的值,与
// onboard.js 的 syncOn、options.js 的 remove 分支永远一致。
// ⚠️ 行首锚定,且**必须恰好命中一次**。第一版写的是 /enabled:\s*true/,它把文件
// 第 25 行注释里的「enabled:true, sign-in included」也算了进去 —— 于是中国版包里
// 这个布尔值是 true,而它决定要不要对用户说「登录之后卡片才到 App」。
// 匹配不到就硬失败:一个静默取错的布尔值,比构建红一次贵得多。
const cfgSrc = fs.readFileSync(path.join(dir, 'learn', 'backend.config.js'), 'utf8');
// 缩进也是判据的一部分(2026-09-08):免费额度那个块里也有一个 `enabled`
// (四格缩进),而这里要的是**顶层那一个同步开关**(两格)。原来的 `^\s*` 把两个
// 都吃了进来,于是加一个无关的嵌套开关就会让构建红 —— 更坏的是,如果哪天顺序反了,
// 它会安静地读到嵌套那一个,而这个布尔值决定要不要对用户说「登录之后卡片才到 App」。
const on = cfgSrc.match(/^ {2}enabled:\s*true,/gm) || [];
const off = cfgSrc.match(/^ {2}enabled:\s*false,/gm) || [];
if (on.length + off.length !== 1) {
console.error(`✗ MT_SYNC_ENABLED: ${dir}/learn/backend.config.js 里 enabled 声明有 `
+ `${on.length + off.length} 处,期望恰好 1 处`);
process.exit(1);
}
const syncOn = on.length === 1;
// 默认目标语言。唯一来源是 translation-core.js 的 DEFAULT_TARGET_LANG,这里只是
// 把它搭 providers.gen.js 的车发给**没加载 translation-core.js 的面**(设置页、
// 引导页 —— 它们要用它决定「打开示例页面」去哪一页)。
// 匹配不到就硬失败,理由同上:一个静默取错的默认语言会把人送到语言不对的示例页。
const coreSrc = fs.readFileSync(path.join(dir, 'content', 'translation-core.js'), 'utf8');
const dtl = coreSrc.match(/DEFAULT_TARGET_LANG\s*=\s*'([\w-]+)'/);
if (!dtl) {
console.error('✗ MT_DEFAULT_TARGET_LANG: translation-core.js 里读不到 DEFAULT_TARGET_LANG');
process.exit(1);
}
// 匿名用量事件(docs/telemetry-design.md §4):端点 + 白名单一起搭这辆车 —— 内容
// 脚本已经加载 providers.gen.js,而它们不能加载 backend.config.js(anon key)。这里
// 只发 URL,不发 key;边缘函数不校验 JWT。
// 两个 flavor 同一份白名单(BEL-135)。国际版打东京 MT_BACKEND.url;中国版打境内
// china.url + /functions/v1/bt-ingest。china.ready 未就绪才发 null(没有境内入口
// 就不指一个地址)。绝不把中国版指到 *.supabase.co。
const TELEMETRY = require('./build/telemetry.config.js');
const telemetrySpec = { common: TELEMETRY.COMMON, events: TELEMETRY.EVENTS, limits: TELEMETRY.LIMITS };
let telemetry = null;
if (flavor === 'china') {
if (chinaBackendReady()) {
const base = String(chinaBackend().url).replace(/\/+$/, '');
telemetry = { url: base + '/functions/v1/bt-ingest', spec: telemetrySpec };
}
} else {
const base = String(require('./extension/learn/backend.config.js').url).replace(/\/+$/, '');
telemetry = { url: base + '/functions/v1/bt-ingest', spec: telemetrySpec };
}
// 免费额度(learning-design §8.10)。搭同一辆车,理由同 telemetry:设置页与引导页
// 都已经加载 providers.gen.js,而它们不能加载 backend.config.js(里面有 anon key)。
//
// **中国版恒为 null**,且不是「关着」而是「不存在」:中国用户的原文会经东京中转,
// 而境内后端未就绪。中国版走的是另一条路(引导去领百炼官方的免费额度)。
// 全球版也要 `grant.enabled` 为真才发 —— 那个开关是 G6 的动作,前置是两站隐私
// 与 README 的 Gate F 文案同版上线。发 null 时客户端所有额度分支都取不到 spec,
// 行为与从前逐字相同。
const BK = require('./extension/learn/backend.config.js');
// 中国版:方案 C(§8.10.1)。只在 grant.china.ready 且地址合法时才有;领取与翻译都打
// 境内中继(中继代转领取),产物里一个东京的额度路径都没有 —— 合规门按这一条验。
const cnGrant = flavor === 'china' ? chinaGrant() : null;
const grantCfg = cnGrant ? {
vendor: cnGrant.vendor,
vendorLabel: cnGrant.vendorLabel,
limitUsd: BK.grant.limitUsd,
claimUrl: cnGrant.relayUrl + '/claim',
models: { chat: (providers.find((p) => p.id === 'grant') || {}).defaultModel || '' },
} : (flavor === 'china' || !BK.grant || !BK.grant.enabled) ? null : {
vendor: BK.grant.vendor,
vendorLabel: BK.grant.vendorLabel || BK.grant.vendor, // 披露文案里的 {vendor}
limitUsd: BK.grant.limitUsd,
claimUrl: BK.url + '/functions/v1/bt-grant',
// 三个槽各自钉住的模型 —— 客户端要把它们写进配置,否则用注册表默认会撞上
// 服务端的 403 model_not_allowed。**这三个值必须与中继的 GRANT_MODELS 一致**,
// 判据是 `npm run grant:status` 那一行(它读的是中继 /spec 的实际回值)。
// 单一来源:build/grant-models.config.js —— 与三张注册表的 grantOnly 条目同源。
models: {
chat: GRANT_MODELS.chat,
tts: GRANT_MODELS.tts,
stt: GRANT_MODELS.stt,
},
};
let body = `window.MT_GRANT = ${JSON.stringify(grantCfg)};\n`
+ `window.MT_FLAVOR = ${JSON.stringify(flavor)};\n`
+ `window.MT_VERSION = ${JSON.stringify(require('./package.json').version)};\n`
+ `window.MT_TELEMETRY = ${JSON.stringify(telemetry)};\n`
+ `window.MT_SYNC_ENABLED = ${JSON.stringify(syncOn)};\n`
+ `window.MT_DEFAULT_TARGET_LANG = ${JSON.stringify(dtl[1])};\n`
+ `window.MT_PROVIDERS = ${JSON.stringify(providers)};\n`
+ `window.MT_MODEL_PARAMS = ${JSON.stringify(params)};\n`;
// 「哪些 host 有实测推荐」——同样搭 providers.gen.js 的车(理由同上:这个文件已经
// 在每一个需要它的面上加载了)。它只是一个**排序提示**:一键配置卡把有实测推荐的
// 平台排在前面,其余按注册表顺序。
//
// 唯一来源是 build/recommend.config.js,不新造第二份 —— 那张表已经有门禁守着
// (每个 (平台, 能力) 必须有 default 轴),而注册表顺序是历史形成的、不是推荐序。
// 只发 host,不发平台名/模型/理由:排序只需要 host,多发的每一个字段都是一块
// 会漂的副本,也是中国包里多一分品牌词面。
const recHosts = [];
for (const r of require('./build/recommend.config.js').PICKS) {
if (r.host && recHosts.indexOf(r.host) < 0) recHosts.push(r.host);
}
body += `window.MT_RECOMMENDED_HOSTS = ${JSON.stringify(recHosts)};\n`;
fs.writeFileSync(path.join(dir, 'content', 'providers.gen.js'), banner + body);
// BEL-277:SW 只放行**本 build 的** ingest 端点。清单必须在 SW 能读到的位置,
// 且与 MT_TELEMETRY.url 同源同一次生成 —— 否则「内容脚本发往 A、SW 只认 B」
// 会让遥测在升级窗口里静默全丢。没有遥测规格(中国版未就绪)就是空清单:
// SW fail closed,队列保留,不是「任意 URL 放行」。
fs.writeFileSync(path.join(dir, 'telemetry-endpoints.json'),
JSON.stringify({ ingest: telemetry && telemetry.url ? [telemetry.url] : [] }, null, 2) + '\n');
log(`Generated content/providers.gen.js (${flavor}: ${providers.map((p) => p.id).join(', ')}`
+ ` · ${params.length} param rows)`);
}
// ─── Palette registry bundle ────────────────────────────────────────────────
// build/palette.config.js is the single source of truth for every brand colour
// (design/handoff.md §1). Emits the runtime JS module and the shared CSS token
// sheet; legacyBrandGate() below refuses to ship the pre-2026-08 green.
function generatePalette(dir) {
const P = require('./build/palette.config.js');
const banner = '// AUTO-GENERATED by build.js from build/palette.config.js — do not edit by hand.\n';
const body = `window.MT_PALETTE = ${JSON.stringify(P.runtime)};\n${P.roundBtnCssJs()}\n`;
fs.writeFileSync(path.join(dir, 'content', 'palette.gen.js'), banner + body);
fs.writeFileSync(path.join(dir, 'styles', 'organic-tokens.gen.css'), P.tokensCss());
log('Generated content/palette.gen.js + styles/organic-tokens.gen.css');
}
// The pre-rebrand green family must never ship again. Only the storage
// migration in background.js may mention the legacy defaults (it retires them).
// `label` distinguishes the two gated artifacts (dist and dist-app).
function legacyBrandGate(dir, label, extraSrcDirs) {
const P = require('./build/palette.config.js');
// No blanket file exemptions — that shape was a hole (anything else in an
// exempted file shipped ungated). background.js instead gets an EXACT
// occurrence budget: precisely the one-shot migration's mention and nothing
// more. Everything else: zero.
const expected = { 'background.js': { '#0a7a3c': 1 } };
// Legacy colours in every spelling that has actually appeared in this repo:
// lowercase hex plus the rgba() triples the round buttons used pre-refactor.
const forbidden = [...P.forbiddenLegacy, '10,122,60', '10, 122, 60'];
const offenders = [];
const count = (text, needle) => text.split(needle).length - 1;
const scanFile = (p, rel) => {
const text = fs.readFileSync(p, 'utf8').toLowerCase();
const budget = expected[rel] || {};
for (const needle of forbidden) {
const n = count(text, needle);
if (n !== (budget[needle] || 0)) offenders.push(`${rel} (${needle} ×${n}, expected ${budget[needle] || 0})`);
}
};
const walk = (root, d) => {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
const p = path.join(d, e.name);
if (e.isDirectory()) { walk(root, p); continue; }
if (!/\.(js|css|html|json|svg)$/.test(e.name)) continue;
// posix-normalized so the expected-budget keys match on every OS
scanFile(p, path.relative(root, p).split(path.sep).join('/'));
}
};
walk(dir, dir);
// dist-app's Script.js is a concatenation — scanning the SOURCES it is built
// from keeps per-file attribution instead of exempting the whole bundle.
for (const extra of extraSrcDirs || []) walk(extra, extra);
if (offenders.length) {
err(`Legacy brand colours in ${label}: ${offenders.join(', ')} — palette lives in build/palette.config.js`);
process.exit(1);
}
// Membership pin for the files that MUST keep literal brand hexes (page-injected
// CSS and the mascot can't read a JS registry; the page stylesheets keep only
// registry-known hexes). 2026-09-30(审计 OVL-01):**页内注入层也进名单** ——
// 字幕叠层与控制菜单原先整片漏过门禁(`#ffb3b3` / `#d6d6d6` / `#4caf50` 就是这么
// 躲过 registry 的);它们现在读 `window.MT_PALETTE`,这里只用来钉住「不许再冒出
// 未登记的 hex」。rgba() 字面量仍不受门禁约束(阴影等合法用法太多),改色搜注册表。
const pinned = ['styles/floating-button.css', 'styles/bilingual.css', 'icons/icon.svg',
'options/options.html', 'popup/popup.css', 'options/options.css', 'learn/review.css',
'content/subtitle-adapter.js', 'content/sub-menu.bundle.js',
'background.js'].filter((f) => fs.existsSync(path.join(dir, f)));
const known = new Set(
[...Object.values(P.ramps), ...Object.values(P.runtime), ...Object.values(P.migration)]
.filter((v) => typeof v === 'string' && v.startsWith('#'))
.map((v) => v.toLowerCase()));
['#ffffff', '#000000'].forEach((n) => known.add(n));
const drift = [];
for (const f of pinned) {
const text = fs.readFileSync(path.join(dir, f), 'utf8').toLowerCase();
for (const hex of text.match(/#[0-9a-f]{6}\b/g) || []) {
if (!known.has(hex)) drift.push(`${f} (${hex})`);
}
}
if (drift.length) {
err(`Brand hex not in the palette registry: ${drift.join(', ')} — add it to build/palette.config.js or use a registry colour`);
process.exit(1);
}
log(`Palette gate OK (${label}: legacy budget exact; pinned files match the registry)`);
}
// ─── China: brand-free _locales ─────────────────────────────────────────────
// Rewrites dist-china/_locales/*/messages.json so the manifest's __MSG__ resolves
// to a China-safe description, and strips brand hint keys (hint_openai/hint_claude)
// that are unused in China but would otherwise carry OpenAI/Claude strings past the
// compliance gate. The i18n table is regenerated from these afterward.
// Which message keys belong ONLY to entries the China bundle does not ship — so their
// strings (which may name a brand) never reach the compliance gate.
//
// This used to be a hand-written list, `['hint_openai', 'hint_claude']`. That list was
// correct for the provider registry and silently wrong the moment a SECOND registry
// (speech engines) arrived with a brand hint of its own. Derive it from the registries
// instead: a list a human must remember to extend is not a gate, it is a wish. The
// derived set must match the old literal for providers — it does.
function chinaOnlyStripKeys() {
const keysOf = (e) => [e.hintKey, e.labelKey].filter(Boolean);
const out = new Set(), kept = new Set();
for (const reg of [require('./build/providers.config.js'), require('./build/tts.config.js'), require('./build/stt.config.js')]) {
for (const e of reg) for (const k of keysOf(e)) (e.flavors.includes('china') ? kept : out).add(k);
}
// A key shared with an entry China DOES ship must survive.
return [...out].filter((k) => !kept.has(k));
}
// Brand words come from build/brands.js so a test can require them — see the note
// there about why this cannot live in build.js.
const { providerBrands } = require("./build/brands.js");
// ─── Gate: the store description must not name providers (issue #69) ───────
// `extension_description` had drifted to naming 4 of 9 providers — and the one it
// omitted was `google`, the zero-config default every new user meets first. Completing
// the list would only move the bug to the next registry change (and 9 names do not fit
// a 132-character store summary anyway), so the description describes the CAPABILITY
// and this gate keeps it that way.
//
// GLOBAL builds only. The China description is generated at build time from
// descriptions.china.js and already has the forbidden-brand grep over dist-china/.
function descriptionBrandGate(dir) {
const brands = providerBrands();
const localesDir = path.join(dir, '_locales');
const hits = [];
for (const loc of fs.readdirSync(localesDir)) {
const f = path.join(localesDir, loc, 'messages.json');
if (!fs.existsSync(f)) continue;
const desc = (JSON.parse(fs.readFileSync(f, 'utf8')).extension_description || {}).message || '';
for (const b of brands) {
if (desc.toLowerCase().indexOf(b.toLowerCase()) >= 0) hits.push(`${loc}: "${b}" in ${JSON.stringify(desc.slice(0, 90))}`);
}
}
if (hits.length) {
err('extension_description names a provider — the registry is the single source of truth\n' +
' (CLAUDE.md: never re-state a model name, endpoint or provider list in UI strings).\n' +
' Describe the capability instead; the list will drift the moment the registry changes.\n' +
hits.map((h) => ' ' + h).join('\n'));
process.exit(1);
}
log(`Store description is provider-neutral (checked ${brands.length} brand tokens)`);
}
// ─── Gate: Apple caps the description at 112 characters ────────────────────
// Apple's App Store Connect validator rejects the whole upload with
// "Invalid messages file … The description field must be present, of string type,
// and 112 or fewer characters long."
// per offending locale. Chrome's store summary allows 132, which is what the #69
// rewrite was checked against — so six locales sailed through every local gate, built
// fine, installed fine on the simulator, and only failed at the TestFlight upload.
// Nothing before that point can see it, which is exactly why it is a gate now.
//
// Runs for BOTH flavors: the China descriptions are generated at build time and are
// just as capable of being too long.
const DESC_MAX = 112;
function descriptionLengthGate(dir) {
const localesDir = path.join(dir, '_locales');
const over = [];
for (const loc of fs.readdirSync(localesDir)) {
const f = path.join(localesDir, loc, 'messages.json');
if (!fs.existsSync(f)) continue;
const desc = (JSON.parse(fs.readFileSync(f, 'utf8')).extension_description || {}).message;
if (typeof desc !== 'string' || !desc) { over.push(`${loc}: missing or not a string`); continue; }
const n = [...desc].length;
if (n > DESC_MAX) over.push(`${loc}: ${n} chars (max ${DESC_MAX}) — ${JSON.stringify(desc.slice(0, 60))}…`);
}
if (over.length) {
err(`extension_description exceeds Apple's ${DESC_MAX}-character limit — App Store Connect\n` +
` rejects the upload, one error per locale, after a successful archive and export:\n` +
over.map((o) => ' ' + o).join('\n'));
process.exit(1);
}
log(`Store description within Apple's ${DESC_MAX}-char limit (all locales)`);
}
// extension_name 的上限是 **40**,不是 manifest 那个 45。
//
// 2026-08-29 撞到的:`altool --upload-app` 在归档成功、导出成功、上传走到最后才拒:
// Invalid messages file. The messages.json validation failed for locale pt_BR …
// The name field must be present, of string type, and 40 or fewer characters long.
//
// 它一次只报**一个** locale,所以「改完再传」会一个一个撞过去;而本地此前只有描述
// 有门禁,名称一道都没有。五个 locale(de/en/es/pt_BR/ru)同时超标,全靠 Apple 的
// 服务器告诉我们 —— 那是这条链上最慢、最贵的反馈点。
//
// 40 是 Safari Web Extension 的限制,比 Chrome manifest 的 45 更严。两个 flavor 都跑:
// 中国版的名称不经 applyChinaLocales 替换,同样会原样进 App Store。
const NAME_MAX = 40;
function nameLengthGate(dir) {
const localesDir = path.join(dir, '_locales');
const over = [];
for (const loc of fs.readdirSync(localesDir)) {
const f = path.join(localesDir, loc, 'messages.json');
if (!fs.existsSync(f)) continue;
const name = (JSON.parse(fs.readFileSync(f, 'utf8')).extension_name || {}).message;
if (typeof name !== 'string' || !name) { over.push(`${loc}: missing or not a string`); continue; }
// Apple 数的是字符不是字节,和它的报错口径一致([...s] 而不是 s.length)。
const n = [...name].length;
if (n > NAME_MAX) over.push(`${loc}: ${n} chars (max ${NAME_MAX}) — ${JSON.stringify(name)}`);
}
if (over.length) {
err(`extension_name exceeds Apple's ${NAME_MAX}-character limit — the upload is rejected\n` +
` AFTER a successful archive and export, and Apple reports only ONE locale per try:\n` +
over.map((o) => ' ' + o).join('\n'));
process.exit(1);
}
log(`Store name within Apple's ${NAME_MAX}-char limit (all locales)`);
}
function applyChinaLocales(dir) {
const DESC = require('./build/descriptions.china.js');
const STRIP_KEYS = chinaOnlyStripKeys();
const localesDir = path.join(dir, '_locales');
for (const loc of fs.readdirSync(localesDir)) {
const f = path.join(localesDir, loc, 'messages.json');
if (!fs.existsSync(f)) continue;
const raw = JSON.parse(fs.readFileSync(f, 'utf8'));
let dirty = false;
if (raw.extension_description) {
// A locale with no China description must FAIL the build, not silently take the
// English `_default`. That fallback hid #70 for two weeks: `_locales/pt` was
// renamed `pt_BR` (#65) and `descriptions.china.js` kept the old `pt` key, so
// Portuguese users of the China build would have seen an English description —
// a compliant, brand-free, perfectly buildable wrong answer.
//
// `_default` stays, but now only as the last line of defence for a locale dir
// that appears without warning; on the normal path it is never reached, and if
// it ever is, this throws first. Deleting it instead would write `undefined`
// into messages.json, which is worse than an English fallback.
if (!DESC[loc]) {
err(`no China description for locale "${loc}" — add it to build/descriptions.china.js.\n` +
` Falling back to English would ship a wrong description that still builds and still passes\n` +
` the brand grep (that is exactly how #70 survived). Present keys: ${Object.keys(DESC).filter((k) => k !== '_default').join(', ')}`);
process.exit(1);
}
raw.extension_description.message = DESC[loc];
dirty = true;
}
for (const k of STRIP_KEYS) { if (raw[k]) { delete raw[k]; dirty = true; } }
if (dirty) fs.writeFileSync(f, JSON.stringify(raw, null, 2) + '\n');
}
log('Applied China-flavor locales (brand-free description + stripped brand hints)');
}
// ─── Compliance gate (China only) ───────────────────────────────────────────
// Fails the build if any brand reference to OpenAI/ChatGPT/Claude or a global
// endpoint leaks into the China bundle. `anthropic-version` (a protocol header for
// the generic Messages format) is intentionally NOT flagged — it is not a brand
// reference. See docs/domain-design.md.
function complianceGateChina(dir, label) {
// 公仓只守通用不变量(品牌词 + 无 *.supabase.co),判据与证伪在 build/china-gate.js。
// 区域策略(境内 host 白名单 / MT_GRANT 形状 / grantOnly 端点)在 compliance 私仓的
// china-gate/ —— BEL-172 拆仓,见 BOUNDARY.md §4。
const G = require('./build/china-gate.js');
const files = [];
(function walk(d) {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
const p = path.join(d, e.name);
if (e.isDirectory()) { walk(p); continue; }
if (!/\.(m?js|json|html|css|txt)$/.test(e.name)) continue; // .mjs 也扫(vendor pdf.js,2026-09-11)
files.push({ name: path.relative(dir, p), text: fs.readFileSync(p, 'utf8') });
}
})(dir);
const hits = G.scan(files);
if (hits.length) {
err(`China compliance gate FAILED — forbidden brand/endpoint references in ${label || 'dist-china'}/:`);
hits.slice(0, 30).forEach((h) => console.error(' ' + h));
process.exit(1);
}
log(`China compliance gate passed for ${label || 'dist-china'} (public invariant:`
+ ' no OpenAI/ChatGPT/Claude brand, no *.supabase.co host)');
}
// ─── Speech (TTS) engine registry bundle ────────────────────────────────────
// build/tts.config.js is the single source of truth for speech engines. Same shape
// and same rules as generateProviders() above — a second capability, a second
// registry, never a hardcoded list at a call site.
function generateTts(dir, flavor) {
const CONFIG = require('./build/tts.config.js');
const pick = pickFlavor(flavor);
const engines = CONFIG.filter((e) => e.flavors.includes(flavor)).map((e) => ({
id: e.id, type: e.type, label: pick(e.label), labelKey: e.labelKey || null,
grantOnly: !!e.grantOnly, // §8.10,同 providers 那一份的理由
defaultEndpoint: pick(e.defaultEndpoint), placeholder: e.placeholder || null,
defaultModel: e.defaultModel || '', voices: e.voices || null,
needsKey: !!e.needsKey, supportsKey: e.supportsKey === undefined ? !!e.needsKey : !!e.supportsKey,
supportsBaseUrl: !!e.supportsBaseUrl,
supportsModel: !!e.supportsModel, requiresEndpoint: !!e.requiresEndpoint,
returnsAudio: !!e.returnsAudio, hintKey: e.hintKey || null,
...(e.oneClick === false ? { oneClick: false } : {}),
}));
const banner = '// AUTO-GENERATED by build.js from build/tts.config.js — do not edit by hand.\n';
fs.writeFileSync(path.join(dir, 'content', 'tts.gen.js'),
banner + `window.MT_TTS_ENGINES = ${JSON.stringify(engines)};\n`);
log(`Generated content/tts.gen.js (${flavor}: ${engines.map((e) => e.id).join(', ')})`);
}
// ─── Speech-input (transcription) engine registry bundle ────────────────────
// build/stt.config.js is the single source of truth for transcription engines
// (learning-design §9.4). Same shape and rules as generateTts() above — a third
// capability, a third registry, never a hardcoded list at a call site.
function generateStt(dir, flavor) {
const CONFIG = require('./build/stt.config.js');
const pick = pickFlavor(flavor);
const engines = CONFIG.filter((e) => e.flavors.includes(flavor)).map((e) => ({
id: e.id, type: e.type, label: pick(e.label), labelKey: e.labelKey || null,
grantOnly: !!e.grantOnly, // §8.10,同 providers 那一份的理由
defaultEndpoint: pick(e.defaultEndpoint), placeholder: e.placeholder || null,
defaultModel: e.defaultModel || '',
needsKey: !!e.needsKey, supportsKey: e.supportsKey === undefined ? !!e.needsKey : !!e.supportsKey,
supportsBaseUrl: !!e.supportsBaseUrl,
supportsModel: !!e.supportsModel, requiresEndpoint: !!e.requiresEndpoint,
hintKey: e.hintKey || null,
...(e.oneClick === false ? { oneClick: false } : {}),
// §2.4 / §2.5: stored address for the large-file upload (Gemini Files API). The live*
// socket fields that sat here 2026-09-06 → 09-17 are gone with the cloud live tier —
// live transcription is the device recogniser, reached through the native bridge.
uploadEndpoint: e.uploadEndpoint || null,
}));
const banner = '// AUTO-GENERATED by build.js from build/stt.config.js — do not edit by hand.\n';
fs.writeFileSync(path.join(dir, 'content', 'stt.gen.js'),
banner + `window.MT_STT_ENGINES = ${JSON.stringify(engines)};\n`);
log(`Generated content/stt.gen.js (${flavor}: ${engines.map((e) => e.id).join(', ')})`);
}
// ─── Learnable-language registry bundle ─────────────────────────────────────
// build/langs.config.js is the single source of truth for the learning-language
// whitelist (learning-design §4.1). Not flavored: language names carry no brand.
function generateLangs(dir) {
const CONFIG = require('./build/langs.config.js');
const langs = CONFIG.map((l) => ({
code: l.code, labelKey: l.labelKey || null, label: l.label, scripts: l.scripts || [],
// 「按住说」对方那个键的小字(2026-10-08):**用那门语言写**,不随界面语言翻译。
// 漏了它右键就只剩一个大字、没告诉对方怎么用(P-01 当场抓到)。
pttHint: l.pttHint || '',
}));
const banner = '// AUTO-GENERATED by build.js from build/langs.config.js — do not edit by hand.\n';
fs.writeFileSync(path.join(dir, 'content', 'langs.gen.js'),
banner + `window.MT_LANGS = ${JSON.stringify(langs)};\n`);
log(`Generated content/langs.gen.js (${langs.map((l) => l.code).join(', ')})`);
}
// ─── Firefox manifest patch ────────────────────────────────────────────────
function patchManifestForFirefox() {
const manifestPath = path.join(DIST, 'manifest.json');
const m = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
m.background = { scripts: ['background.js'] };
fs.writeFileSync(manifestPath, JSON.stringify(m, null, 2));
log('Patched manifest.json for Firefox (background.scripts)');
}
// ─── Generate icons ────────────────────────────────────────────────────────
function generateIcons(distDir) {
const iconDir = path.join(distDir, 'icons');
const isPng = (p) => {
if (!fs.existsSync(p)) return false;
const fd = fs.openSync(p, 'r');
const buf = Buffer.alloc(8);
fs.readSync(fd, buf, 0, 8, 0);
fs.closeSync(fd);
return buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
};
const missing = [16, 48, 128]
.filter((s) => !isPng(path.join(iconDir, `icon${s}.png`)))
.map((s) => `icon${s}.png`);
if (missing.length) {
err(`Missing or non-PNG icons: ${missing.join(', ')} — regenerate from extension/icons/icon.svg`);
process.exit(1);
}
log('Icons OK (real PNG)');
}
// ─── default_locale 按 flavor ──────────────────────────────────────────────
//
// `chrome.i18n` 对**没有对应 _locales/<locale> 目录**的用户,回落到 default_locale。
// 这个值一直是 zh_CN,于是每一个我们没做本地化的市场,装完看到的是中文界面。
//
// 2026-09-04 用下载数据量出了代价:IT 是 30 天下载量第 3 名(18 次,8.9%),而
// `_locales/` 里没有 it;加上 TR 9 / VN 6 / PL 4,共 37 次 = 国际版的 21.5%。
// 这些人打开的是一个中文界面的翻译扩展。(`node scripts/store-stats.js` 的
// 「市场缺口」那一节会持续报这个数。)
//
// 所以它按 flavor 分叉,而不是一个常量:
// · global / firefox —— `en`。国际版发到 36 个国家,英文是唯一合理的兜底。
// · china —— `zh_CN`。它只在中国区分发,兜底成英文纯属倒退。
//
// 门禁而不是约定:这个值改错了**不会报错**,只会让一个市场安静地读到另一种语言
// —— 和 issue #65 那个「目录名 Chrome 不认识就静默忽略」是同一类病。
function defaultLocaleGate(distDir, label, flavor) {
const want = flavor === 'china' ? 'zh_CN' : 'en';
const m = JSON.parse(fs.readFileSync(path.join(distDir, 'manifest.json'), 'utf8'));
if (m.default_locale !== want) {
err(`${label}: default_locale is "${m.default_locale}", expected "${want}" for flavor ${flavor}`);
process.exit(1);
}
// 兜底语言自己必须存在,否则回落的目的地是个空目录 —— 那比回落到别的语言更糟。
if (!fs.existsSync(path.join(distDir, '_locales', want, 'messages.json'))) {
err(`${label}: default_locale "${want}" has no _locales/${want}/messages.json`);
process.exit(1);
}
log(`default_locale gate OK (${label}: ${want})`);
}
// ─── Validate manifest ─────────────────────────────────────────────────────
function validateManifest(distDir, isFirefox) {
const m = JSON.parse(fs.readFileSync(path.join(distDir, 'manifest.json'), 'utf8'));
if (m.manifest_version !== 3) { err('manifest_version must be 3'); process.exit(1); }
if (isFirefox && !m.background?.scripts) { err('Firefox build missing background.scripts'); process.exit(1); }
if (!isFirefox && !m.background?.service_worker) { err('Chrome build missing background.service_worker'); process.exit(1); }
if (!m.browser_specific_settings?.gecko?.id) { err('Missing gecko.id (required for AMO)'); process.exit(1); }
// Firefox requires an explicit data-collection disclosure on every new AMO
// submission since 2025-11-03; AMO's validator hard-fails without it. Since Gate B
// (v1.4.0, 2026-08-09) the honest value is THREE entries: `websiteContent` (page /
// transcript text goes to the user's chosen provider, and captured sentences go to
// sync), `browsingActivity` (the sync source table is URL + title + time — §8.6:
// "the sensitive column is the URL"), and `personallyIdentifyingInfo` (the account
// is an email address). The exact-value check lives in the Gate B block below —
// this one only guards presence, which AMO itself enforces.
const dcp = m.browser_specific_settings?.gecko?.data_collection_permissions?.required;
if (!Array.isArray(dcp) || dcp.length === 0) {
err('Missing gecko.data_collection_permissions.required (AMO rejects the upload without it)');
process.exit(1);
}
// A version literal inside a translated string has as many copies as there are
// locales and tracks none of them: `about_line` said "v1.0.0" in all eleven while
// the manifest was 1.3.0, and nothing anywhere noticed. Same disease as a model
// name in a hint — one registry, N consumers (AGENTS.md).
for (const loc of fs.readdirSync(path.join(distDir, '_locales'))) {
const f = path.join(distDir, '_locales', loc, 'messages.json');
if (!fs.existsSync(f)) continue;
const msgs = JSON.parse(fs.readFileSync(f, 'utf8'));
for (const [k, v] of Object.entries(msgs)) {
if (/\bv?\d+\.\d+\.\d+\b/.test(String(v && v.message))) {
err(`_locales/${loc}/messages.json key "${k}" hardcodes a version: ` +
`"${v.message}"\nRender it from chrome.runtime.getManifest().version instead — ` +
`a version inside a translation has N copies and tracks none of them.`);
process.exit(1);
}
}
}
// ─── Sync flag ↔ privacy promise, coupled mechanically ───────────────────
// learning-design.md §10 Gate B. Turning sync on makes four sentences false at
// once ("no account", "we receive nothing", "never uploaded", "no servers of
// ours in the middle" as applied to the corpus). Every one of them is somewhere
// a build cannot see — the README, a website, a store listing — so the only
// thing that can be checked here is the one that lives in this repo. A promise
// whose upkeep depends on someone remembering at release time is the kind that
// gets broken; this makes forgetting fail the build instead.
const backend = require('./extension/learn/backend.config.js');
// ── Gate F(docs/learning-design.md §10;2026-09-08)─────────────────────
//
// 免费额度是**整个产品里唯一一条用户文本会经过我们服务器的路**。所以它的披露
// 与开关必须同版上线 —— 而「同版」这件事靠人记着是不成立的(Gate B 与 Gate D
// 都为此立过同样形状的门)。
//
// 两个方向都查:
// · 开关翻了而披露没跟上 ⇒ 我们在没有告知的情况下让用户的文本经过了我们。
// · 中国版产物里出现额度的任何痕迹 ⇒ 那个 flavor 恒不提供它(已在合规门里查)。
// 只查一个方向的话,把披露整段删掉也能过。
const grant = backend.grant || {};
if (grant.enabled) {
const miss = [];
const rdEn = fs.readFileSync(path.join(__dirname, 'README.md'), 'utf8');
const rdZh = fs.readFileSync(path.join(__dirname, 'README.zh-CN.md'), 'utf8');
// 词干而不是整句:整句一改标点就漏,而词干在的话那一段一定在。
if (!/free credit/i.test(rdEn)) miss.push('README.md 没有免费额度的披露(Gate F)');
if (!/免费额度/.test(rdZh)) miss.push('README.zh-CN.md 没有「免费额度」的披露(Gate F)');
// 每一门 locale 都要有那段披露,且**必须提到「经过我们的服务器」这件事**。
// 只查键在不在的话,写一句「有免费额度可以领」也能过,而那正是要防的那种话。
for (const loc of fs.readdirSync(path.join(distDir, '_locales'))) {
const f = path.join(distDir, '_locales', loc, 'messages.json');
if (!fs.existsSync(f)) continue;
const m = JSON.parse(fs.readFileSync(f, 'utf8'));
const v = String(m.grant_privacy?.message || '');
if (!v) { miss.push(`_locales/${loc} 缺 grant_privacy(Gate F)`); continue; }
if (!v.includes('{vendor}')) miss.push(`_locales/${loc} 的 grant_privacy 没有 {vendor} 占位符`);