Repository navigation
Expand file tree
/
Copy pathbefore-pack.cjs
More file actions
1291 lines (1213 loc) · 58.1 KB
/
Copy pathbefore-pack.cjs
File metadata and controls
1291 lines (1213 loc) · 58.1 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
// electron-builder beforePack hook: refuse to package a compositor addon that is older than its
// Rust sources.
//
// `compositor_view.node` is an untracked build artifact, and plain `npm run build` does NOT rebuild
// it (only `build:win` runs `build:native:compositor`). So a bare `npm run build` — or a fresh
// worktree that inherited a copy from the main checkout — happily ships a `.node` built from
// whatever the sources looked like days ago.
//
// That failure is silent, which is what makes it worth a hard error. Scene fields the app sends are
// `#[serde(default)]` on the Rust side, so an addon predating a contract change does not reject the
// payload: it ignores the unknown key, takes the default, and falls back to older art. The feature
// simply does nothing, with no error in any log — it reads exactly like a bug in the TypeScript, and
// it has already cost one full false-trail investigation (custom cursor themes, 2026-07-27, where
// the shipped addon was 3 days older than the commit adding `cursorSprites`).
//
// ponytail: mtime comparison, not content hashing. A `git checkout` restamps source mtimes, so this
// can fire when the addon is actually fine. That trade is deliberate — the false positive costs one
// rebuild, the false negative ships a broken installer. Switch to hashing the sources into a stamp
// file next to the `.node` if branch-switching makes the noise annoying.
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const ADDON = path.join(ROOT, "electron/native/compositor-view/build/compositor_view.node");
// Everything the addon is compiled from. shaders.hlsl lives under src/, so it is covered.
// crates/poc-d3d/ is deliberately absent: nothing links it, so editing the POC cannot
// invalidate the shipped addon.
const SOURCE_PATHS = [
"crates/compositor/src",
"crates/compositor-view-napi/src",
"crates/Cargo.toml",
"crates/compositor/Cargo.toml",
"crates/compositor-view-napi/Cargo.toml",
].map((p) => path.join(ROOT, p));
const FIX =
"Rebuild it with:\n\n npm run build:native:compositor\n\nor use `npm run build:win`, which does that for you.";
const FIX_MAC =
"Rebuild it with:\n\n npm run build:native:compositor:mac\n\nor use `npm run build:mac`, which does that for you.";
const FIX_LINUX =
"Rebuild it with:\n\n npm run build:native:compositor:linux\n\nor use `npm run build:linux`, which does that for you.";
const FIX_LINUX_HELPER =
"Rebuild it with:\n\n npm run build:native:linux\n\nor use `npm run build:linux`, which does that for you.";
/** Everything the PipeWire capture helper is compiled from. */
const HELPER_SOURCE_PATHS = [
"electron/native/pipewire-capture/src",
"electron/native/pipewire-capture/csrc",
"electron/native/pipewire-capture/build.rs",
"electron/native/pipewire-capture/Cargo.toml",
].map((p) => path.join(ROOT, p));
/**
* Everything that has to be inside `electron/native/bin/darwin-<arch>/` for the .app to
* work, keyed by what breaks when it is absent.
*
* This list exists because the macOS deliverable had no guard at all: `beforePack`
* returned early on any non-win32 platform, so a mac package built without the compositor
* addon shipped silently — the preview and the export come up dead, with nothing in any
* log to say why. That is precisely the failure mode the staleness check below was written
* to prevent, and the platform guard was letting it through on the other OS.
*
* `mac.extraResources` ships this directory wholesale (`filter: ["darwin-*/*"]`), so
* "present here" is the same thing as "present in the installed app".
*/
/**
* L'exigence ONNX Runtime de macOS, séparée parce qu'elle ne vaut QUE sur arm64.
*
* L'amont ne publie aucun binaire ONNX pour les Macs Intel : `fetch-onnxruntime.mjs` le constate
* et sort en 0 sans rien poser. Un paquet x64 sans la bibliothèque est donc CORRECT, et l'exiger
* là ferait échouer à l'empaquetage une build parfaitement saine — la garde se retournerait
* contre ce qu'elle protège.
*
* Sur arm64 en revanche son absence ne casse rien de visible : `Segmenter::load` refuse, le
* compositeur dessine la webcam telle quelle, et le contrôle disparaît de l'éditeur. Le paquet
* est silencieusement amputé, ce qui est exactement la panne que cette garde existe pour
* attraper et qu'aucun test ne peut voir puisque tout se dégrade proprement.
*/
const MAC_ONNX_REQUIRED = {
match: (name) => name === "libonnxruntime.dylib",
what: "the ONNX Runtime library the camera-background segmentation loads",
breaks: "the camera-background control vanishes from the editor and every effect is a no-op",
fix: "Stage it with:\n\n npm run fetch:onnxruntime",
};
const MAC_REQUIRED = [
{
match: (name) => name === "compositor_view.node",
what: "the Metal compositor addon",
breaks: "the preview and every export render nothing",
fix: FIX_MAC,
},
// One requirement per library, not `atLeast: N` over a combined regex — the
// same trap LINUX_REQUIRED documents above. Several versioned copies of one
// library would satisfy a combined count while another was missing entirely,
// and the addon would still fail to load.
...["avcodec", "avformat", "avutil", "swresample", "swscale", "avfilter"].map((library) => ({
match: (name) => new RegExp(`^lib${library}\\.\\d+\\.dylib$`).test(name),
what: `the LGPL lib${library} dylib the compositor links`,
breaks: "the compositor addon cannot be loaded at all (dyld error at require())",
fix: FIX_MAC,
})),
{
match: (name) => /^libavdevice\.\d+\.dylib$/.test(name),
what: "the LGPL libavdevice dylib the ffmpeg CLI links",
breaks: "ffmpeg dies in dyld before main(), so waveform and STT extraction cannot start",
fix: FIX_MAC,
},
{
match: (name) => name === "whisper-stt-server",
what: "the whisper.cpp STT helper",
breaks: "transcription and captions fail with a developer error shown to end users",
fix: "Build it with:\n\n npm run build:whisper-binaries\n\nor stage CI's with `bash scripts/stage-whisper-stt.sh darwin-<arch>`.",
},
{
match: (name) => /^libggml.*\.dylib$/.test(name),
what: "the ggml backend dylibs the STT helper links",
breaks: "whisper-stt-server dies in dyld before main(), so STT times out with no diagnostic",
fix: "Build it with:\n\n npm run build:whisper-binaries",
atLeast: 1,
},
{
match: (name) => name === "openscreen-screencapturekit-helper",
what: "the ScreenCaptureKit capture helper",
breaks: "native screen capture is unavailable",
fix: "Build it with:\n\n npm run build:native:mac",
},
{
match: (name) => name === "ffmpeg",
what: "the LGPL ffmpeg CLI (spawned for waveform peaks and STT audio extraction)",
breaks:
'transcription fails in the editor, over MCP and in the CLI with "ffmpeg is missing" (#616)',
fix: "Build it with:\n\n npm run build:native:compositor:mac\n\nwhich stages the SDK's ffmpeg beside the vendored dylibs.",
},
];
/**
* The Linux counterpart of MAC_REQUIRED. It exists for the same reason: until this
* hook grew a Linux branch, `beforePack` asserted nothing at all on Linux — the
* comment said "Linux ships no native addon of its own", which stopped being true
* when the wgpu compositor addon and the PipeWire capture helper landed.
*
* `linux.extraResources` ships this directory wholesale (`filter: ["linux-*/**"]`),
* so "present here" is the same thing as "present in the installed app".
*
* Note the two ffmpeg sets, which is why `helper-ffmpeg/` is required separately below:
* the `.so` files sitting directly in this directory are the compositor's copies,
* with every symbol renamed to `osff_*` so the addon cannot bind to Chromium's
* bundled ffmpeg. The helper needs the *unrenamed* originals, which is what the
* `helper-ffmpeg/` subdirectory holds.
*/
const LINUX_REQUIRED = [
// L'effet de fond de caméra est le seul dont la présence dépend d'un binaire optionnel, et
// son absence ne casse RIEN de visible : `Segmenter::load` refuse, le compositeur dessine la
// webcam telle quelle, et le contrôle disparaît de l'éditeur. Un paquet livré sans elle est
// donc silencieusement amputé — la panne exacte que cette garde existe pour attraper, et
// celle qu'aucun test ne peut voir puisque tout se dégrade proprement.
{
match: (name) => name === "libonnxruntime.so",
what: "the ONNX Runtime library the camera-background segmentation loads",
breaks: "the camera-background control vanishes from the editor and every effect is a no-op",
fix: "Stage it with:\n\n npm run fetch:onnxruntime",
},
{
match: (name) => name === "compositor_view.node",
what: "the wgpu/Vulkan compositor addon",
breaks: "the preview renders nothing and every export falls back to the no-op compositor",
fix: FIX_LINUX,
},
// Une exigence par famille, plutôt qu'`atLeast: 5` sur une regex combinée. Le
// compte total était satisfait par cinq copies versionnées d'une même
// bibliothèque — libavcodec.so.58 à .62 laissées par un build précédent —
// pendant qu'une autre manquait. Le paquet passait alors la garde et le
// compositeur ne chargeait pas : exactement le mode de panne que cette garde
// existe pour attraper.
...["avcodec", "avformat", "avutil", "swresample", "swscale", "avfilter"].map((library) => ({
match: (name) => new RegExp(`^lib${library}\\.so\\.\\d+$`).test(name),
what: `the symbol-renamed lib${library} shared object the compositor links`,
breaks: "the compositor addon cannot be loaded at all (ld.so error at require())",
fix: FIX_LINUX,
})),
{
match: (name) => name === "openscreen-pipewire-helper",
what: "the PipeWire screen-capture helper",
breaks: "Wayland capture is unavailable and cursor recording throws",
fix: FIX_LINUX_HELPER,
},
{
match: (name) => name === "ffmpeg",
what: "the LGPL ffmpeg CLI (spawned for waveform peaks and STT audio extraction)",
breaks: 'transcription fails in the editor, over MCP and in the CLI with "ffmpeg is missing"',
fix: `${FIX_LINUX_HELPER}\n\nwhich stages the SDK's shared ffmpeg beside helper-ffmpeg/.`,
},
{
match: (name) => name === "whisper-stt-server",
what: "the whisper.cpp STT helper",
breaks: "transcription and captions fail with a developer error shown to end users",
fix: "Build it with:\n\n npm run build:whisper-binaries\n\nor stage CI's with `bash scripts/stage-whisper-stt.sh linux-x64`.",
},
{
match: (name) => /^libggml.*\.so(\.\d+)*$/.test(name),
what: "the ggml backend shared objects the STT helper links",
breaks: "whisper-stt-server dies in ld.so before main(), so STT times out with no diagnostic",
fix: "Build it with:\n\n npm run build:whisper-binaries",
atLeast: 1,
},
];
/** electron-builder passes `context.arch` as a numeric enum; map it to our directory tag. */
function archTagFor(context) {
const BY_INDEX = { 0: "ia32", 1: "x64", 2: "armv7l", 3: "arm64", 4: "universal" };
const name = BY_INDEX[context?.arch];
return name && name !== "universal" ? name : process.arch;
}
/**
* Shared by the macOS and Linux payload checks — same contract on both: the arch-tagged
* directory under electron/native/bin/ is what extraResources ships, so a missing entry
* here is a missing entry in the installed app.
*/
function checkNativePayload({ dir, required, osLabel, bundleNoun, emptyDirFix }) {
if (!fs.existsSync(dir)) {
throw new Error(
`Refusing to package: ${path.relative(ROOT, dir)} does not exist, so ${bundleNoun} would ` +
"ship with no native modules at all.\n\n" +
emptyDirFix,
);
}
const present = fs.readdirSync(dir);
const missing = required.filter(
(req) => present.filter((name) => req.match(name)).length < (req.atLeast ?? 1),
);
if (missing.length === 0) {
return;
}
const detail = missing
.map(
(req) =>
` - ${req.what}\n without it: ${req.breaks}\n ${req.fix.replace(/\n+/g, " ")}`,
)
.join("\n");
throw new Error(
`Refusing to package an incomplete ${osLabel} payload.\n\n` +
` looked in: ${path.relative(ROOT, dir)}\n\n` +
`Missing:\n${detail}\n\n` +
"Every one of these fails silently or as an unactionable timeout in the installed\n" +
"app, which is why this is a hard error at pack time rather than a warning.",
);
}
/**
* The Windows addon must sit in the SAME directory as the ffmpeg DLLs it links
* against, because that is the only arrangement that loads under MSIX.
*
* The addon dlopens avcodec/avformat/avutil at require() time. While it shipped from
* app.asar.unpacked — one directory away from the DLLs — loading it depended on
* `ensureFfmpegSharedDllsOnPath` prepending their directory to PATH. That works for
* the NSIS installer and does not work under MSIX, which resolves dependent DLLs
* through the package graph and ignores PATH. Measured inside a registered package,
* with the directory correctly on PATH: `require` failed both before and after the
* PATH was set; with the addon beside its DLLs it loaded with no PATH at all.
*
* That shipped as 1.9.0 on the Store: no compositor loaded, so the editor showed no
* preview at all while audio kept playing — and it looked like an app bug, not a
* packaging one, because every file was present and the NSIS build of the same commit
* was fine.
*
* `win.extraResources` ships this directory wholesale (filter `win32-*/*`), so
* "together here" is the same thing as "together in the installed app".
*/
const WIN_REQUIRED = [
// L'effet de fond de caméra est le seul dont la présence dépend d'un binaire optionnel, et
// son absence ne casse RIEN de visible : `Segmenter::load` refuse, le compositeur dessine la
// webcam telle quelle, et le contrôle disparaît de l'éditeur. Un paquet livré sans elle est
// donc silencieusement amputé — la panne exacte que cette garde existe pour attraper, et
// celle qu'aucun test ne peut voir puisque tout se dégrade proprement.
{
match: (name) => name === "onnxruntime.dll",
what: "the ONNX Runtime library the camera-background segmentation loads",
breaks: "the camera-background control vanishes from the editor and every effect is a no-op",
fix: "Stage it with:\n\n npm run fetch:onnxruntime",
},
{
match: (name) => name === "compositor_view.node",
what: "the D3D11 compositor addon",
breaks: "the preview renders nothing and every export falls back to the no-op compositor",
fix: FIX,
},
// One requirement per library, not `atLeast: 3` over a combined regex — the same
// trap LINUX_REQUIRED documents above. Several versioned copies of one library
// (avcodec-60/61/62.dll left by an earlier fetch) would satisfy a combined count
// while another library was missing entirely, and the addon would still fail to
// load.
...["avcodec", "avformat", "avutil", "swresample", "swscale", "avfilter"].map((library) => ({
match: (name) => new RegExp(`^${library}-\\d+\\.dll$`).test(name),
what: `the ${library} DLL the compositor links`,
breaks: "the addon cannot be loaded at all under MSIX, which ignores PATH",
fix: "Fetch them with:\n\n npm run fetch:ffmpeg",
})),
];
/**
* DLLs that come from the Visual C++ Redistributable rather than from Windows itself.
*
* The `api-ms-win-crt-*` api-sets are deliberately absent: that is the UCRT, which IS
* part of Windows 10 and later. These are not, and no machine is obliged to have them.
*
* `vcomp` and `vcamp` were missing from the first version of this list, and the gap was
* not academic: ggml-base.dll and ggml-cpu.dll are built with OpenMP and import
* vcomp140.dll, so the shipped whisper payload still needed the redistributable after
* 1.9.1 was supposed to have ended that. The guard reported the payload clean because
* `vcomp` starts with none of msvcp/vcruntime/concrt. Enumerate the family, not the
* members that happened to bite.
*/
const VC_REDIST_DLL = /^(msvcp|vcruntime|concrt|vcomp|vcamp|mfc)\d+/i;
/**
* The DLL names a PE binary imports — just enough of the format to walk the import
* directory, so this needs no dumpbin and therefore no Visual Studio on the runner.
*/
function importedDlls(file) {
const b = fs.readFileSync(file);
// Every read below is bounds-checked through this, so a truncated or non-PE file
// arrives at the message this function means to give rather than at a RangeError
// from readUInt32LE. The diagnostic is the whole product here: the caller's job is
// to explain an absence, and "offset is out of bounds" explains nothing.
const notPe = () => new Error(`${file} is not a PE binary, or is truncated`);
const u32 = (at) => {
if (at < 0 || at + 4 > b.length) throw notPe();
return b.readUInt32LE(at);
};
const u16 = (at) => {
if (at < 0 || at + 2 > b.length) throw notPe();
return b.readUInt16LE(at);
};
if (u16(0) !== 0x5a4d) throw notPe(); // "MZ"
const pe = u32(0x3c);
if (u32(pe) !== 0x00004550) throw notPe(); // "PE\0\0"
const opt = pe + 24;
// The optional header's fixed part is 96 bytes for PE32 and 112 for PE32+ (five
// fields widen to 8 bytes); the data directories follow it.
const dirs = opt + (u16(opt) === 0x20b ? 112 : 96);
// NumberOfRvaAndSizes is the last field before the directories, so it sits four
// bytes back whichever the format. Without it, a binary declaring fewer entries
// than we index would have unrelated header bytes read as an RVA.
const dirCount = u32(dirs - 4);
const sections = [];
for (let i = 0; i < u16(pe + 6); i++) {
const s = opt + u16(pe + 20) + i * 40;
sections.push({ va: u32(s + 12), size: u32(s + 16), ptr: u32(s + 20) });
}
const fileOffset = (rva) => {
const s = sections.find((s) => rva >= s.va && rva < s.va + s.size);
if (!s) throw new Error(`${file}: RVA 0x${rva.toString(16)} is in no section`);
return s.ptr + (rva - s.va);
};
const names = [];
// Both directories are arrays of fixed-size descriptors ending in an all-zero one,
// and both hold the DLL name as an RVA at a fixed offset. Reading only the first
// would miss a delay-loaded dependency entirely — the loader resolves those on
// first call rather than at load time, so the failure would arrive later and
// nowhere near the cause, which is worse than the one this guard was written for.
const walk = (index, stride, nameOffset) => {
if (dirCount <= index) return;
const rva = u32(dirs + index * 8);
if (!rva) return;
for (let entry = fileOffset(rva); ; entry += stride) {
const nameRva = u32(entry + nameOffset);
if (!nameRva) return;
const at = fileOffset(nameRva);
names.push(b.subarray(at, b.indexOf(0, at)).toString("latin1"));
}
};
walk(1, 20, 12); // IMAGE_IMPORT_DESCRIPTOR.Name
walk(13, 32, 4); // ImgDelayDescr.rvaDLLName
return names;
}
/** IMAGE_FILE_HEADER.Machine, as the arch tag of the `win32-<arch>` directories. */
const PE_MACHINE = { 0x8664: "x64", 0xaa64: "arm64" };
/** The architecture a PE binary is built for, or undefined for a machine we do not ship. */
function peArch(file) {
const b = fs.readFileSync(file);
const notPe = () => new Error(`${file} is not a PE binary, or is truncated`);
if (b.length < 0x40 || b.readUInt16LE(0) !== 0x5a4d) throw notPe();
const pe = b.readUInt32LE(0x3c);
if (pe + 6 > b.length || b.readUInt32LE(pe) !== 0x00004550) throw notPe();
return PE_MACHINE[b.readUInt16LE(pe + 4)];
}
/**
* Nothing we ship may depend on the Visual C++ Redistributable.
*
* This is the one failure this whole hook could not see. Every machine that builds this
* repo, and most machines that have ever installed a desktop app, carry those DLLs in
* System32 — so a binary that needs them works in local testing, in CI, and in every
* package format, while being unloadable on a clean Windows image. There is no way to
* reproduce it here; only the import table tells the truth.
*
* Store certification rejected 1.9.1 for exactly this: the WGC helper was built against
* the dynamic CRT and died in the loader before main(), so the app reported
* `Native Windows capture exited before recording started (code=3221225781)`
* — 0xC0000135, STATUS_DLL_NOT_FOUND — and recording was impossible on the test device.
* `compositor_view.node` had the same defect and would have failed certification a
* second time, on the preview, right after the helper was fixed.
*
* The fix is per-toolchain, hence the two-part message: /MT for the CMake helpers
* (electron/native/wgc-capture/CMakeLists.txt), `+crt-static` for the Rust addon
* (crates/.cargo/config.toml).
*/
function checkWinNoRedistDependency(dir) {
// Regular files only, and the same list serves both questions below. A directory
// answers `readdirSync` by name exactly as a file does, and this directory really
// does hold subdirectories (the vendored ffmpeg SDK), so the distinction is not
// hypothetical. Without it one named `something.dll` is opened as a binary and the
// hook dies on a raw `EISDIR` — the build stops, which is right, on a message that
// names nothing, which is not.
const files = fs
.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isFile())
.map((entry) => entry.name);
const scanned = files
.filter((name) => /\.(exe|dll|node)$/i.test(name))
.map((name) => ({ name, imports: importedDlls(path.join(dir, name)) }));
// A guard that silently stops looking is worse than no guard: it reports "clean" for
// the rest of the project's life. Every native binary imports something — kernel32 at
// the very least — so an empty result means the parser broke, not that the file is
// self-contained. Asserted here against the real payload rather than a synthetic PE
// fixture, which would only ever prove this parser agrees with itself.
const unread = scanned.filter((entry) => entry.imports.length === 0);
if (unread.length > 0) {
throw new Error(
`Refusing to package: read no imports at all from ${unread.map((e) => e.name).join(", ")}.\n\n` +
"Every native binary imports at least kernel32, so this is a bug in importedDlls()\n" +
"(scripts/before-pack.cjs), not a self-contained binary. Fix the parser — leaving it\n" +
"is how the Visual C++ Redistributable dependency gets back into a shipped build.",
);
}
// The property that matters is not "imports a redistributable DLL", it is "imports a
// redistributable DLL that will not be there". A copy sitting in this directory WILL
// be there: it ships, and the loader searches an executable's own directory and, for
// a .node, the module's — the same colocation that carries the ffmpeg DLLs. Shipping
// vcomp140.dll beside the ggml libraries is therefore a fix, not an exception, and
// the check has to be able to say so or it would forbid the remedy it asks for.
const shipped = new Set(files.map((name) => name.toLowerCase()));
const offenders = scanned
.map((entry) => ({
name: entry.name,
bad: entry.imports.filter((d) => VC_REDIST_DLL.test(d) && !shipped.has(d.toLowerCase())),
}))
.filter((entry) => entry.bad.length > 0);
if (offenders.length > 0) {
throw new Error(
"Refusing to package binaries that need the Visual C++ Redistributable.\n\n" +
` looked in: ${path.relative(ROOT, dir)}\n\n` +
`${offenders.map((o) => ` - ${o.name} imports ${o.bad.join(", ")}`).join("\n")}\n\n` +
"Those DLLs are not part of Windows. On a clean image the loader kills the process\n" +
"before main() (0xC0000135) or fails require(), and the app can only report an exit\n" +
"code. It works on every developer machine, which is why this is checked here.\n\n" +
"Build against the static CRT instead:\n" +
" - CMake helpers: CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded (electron/native/wgc-capture)\n" +
" - Rust addon: -C target-feature=+crt-static (crates/.cargo/config.toml)\n\n" +
"For a prebuilt binary that is not ours to recompile, ship the DLL it needs into this\n" +
"same directory and the check passes — that is what scripts/stage-vcomp-runtime.mjs\n" +
"does for the OpenMP runtime the whisper/ggml libraries import.",
);
}
// Every binary here must be built for this directory's architecture, and none of the
// checks above can tell: the right name and clean imports say nothing about the
// machine. An x64 compositor addon in win32-arm64 fails require() on every ARM64
// device, and the Redist tree holds an x64 and an arm64 vcomp140.dll under the same
// name, so either satisfies `shipped` while the loader refuses the wrong one with
// the same 0xC0000135 as a missing file.
//
// The one exception is a runtime DLL that nothing here imports. The arm64 Redist
// folder carries a vcruntime140_1.dll whose header says x64 — it is the ARM64EC build
// Microsoft ships for emulated x64 code — and no ARM64 binary loads it.
const dirArch = path.basename(dir).match(/^win32-(.+)$/)?.[1];
if (!dirArch) {
return;
}
const imported = new Set(scanned.flatMap((entry) => entry.imports.map((d) => d.toLowerCase())));
const wrongArch = scanned
.filter(({ name }) => !VC_REDIST_DLL.test(name) || imported.has(name.toLowerCase()))
.map(({ name }) => ({ name, arch: peArch(path.join(dir, name)) }))
.filter((entry) => entry.arch !== dirArch);
if (wrongArch.length > 0) {
throw new Error(
"Refusing to package native binaries built for the wrong architecture.\n\n" +
`${wrongArch.map((e) => ` - ${e.name} in ${path.basename(dir)} is built for ${e.arch ?? "an unknown machine"}`).join("\n")}\n\n` +
`A ${dirArch} process cannot load them. Rebuild or re-fetch them for ${dirArch}; for the\n` +
`Visual C++ runtime, stage the copy from VC\\Redist\\MSVC\\<version>\\${dirArch}\\ —\n` +
"scripts/stage-vcomp-runtime.mjs does.",
);
}
}
/**
* Every `win32-*` directory, because that is what ships: the extraResources filter is
* `win32-*` / `*`, not the target's directory alone. The arm64 installer carries
* win32-x64 for the whisper helper that runs under emulation, and checking only
* win32-arm64 let that helper ship without the OpenMP runtime its ggml libraries import.
*/
function checkWinShippedRedist(binDir) {
for (const entry of fs.readdirSync(binDir, { withFileTypes: true })) {
if (entry.isDirectory() && /^win32-/.test(entry.name)) {
checkWinNoRedistDependency(path.join(binDir, entry.name));
}
}
}
function checkWinNativePayload(context) {
const dir = path.join(ROOT, "electron", "native", "bin", `win32-${archTagFor(context)}`);
checkNativePayload({
dir,
required: WIN_REQUIRED,
osLabel: "Windows",
bundleNoun: "the installer",
emptyDirFix: `${FIX}\n\nThe STT helper and the capture helper are separate builds — see\ntechnical-documentation/engineering/build-and-packaging.md.`,
});
checkWinShippedRedist(path.dirname(dir));
}
function checkMacNativePayload(context) {
const arch = archTagFor(context);
const dir = path.join(ROOT, "electron", "native", "bin", `darwin-${arch}`);
checkNativePayload({
dir,
// Voir `MAC_ONNX_REQUIRED` : exiger la bibliothèque sur Intel ferait échouer une build
// que l'amont rend impossible à satisfaire.
required: arch === "arm64" ? [...MAC_REQUIRED, MAC_ONNX_REQUIRED] : MAC_REQUIRED,
osLabel: "macOS",
bundleNoun: "the .app",
emptyDirFix: `${FIX_MAC}\n\nThe STT helper and the capture helper are separate builds — see\ntechnical-documentation/engineering/build-and-packaging.md.`,
});
// "Complete" is not the same property as "runnable on the macOS we claim". This file
// exists because a payload can be whole and still broken; a floor above the supported
// one is the second way that happens. See checkMacOsVersionFloor().
checkMacOsVersionFloor(dir);
}
function checkLinuxNativePayload(context) {
const dir = path.join(ROOT, "electron", "native", "bin", `linux-${archTagFor(context)}`);
checkNativePayload({
dir,
required: LINUX_REQUIRED,
osLabel: "Linux",
bundleNoun: "the package",
emptyDirFix: `${FIX_LINUX}\n\nThe capture helper and the STT helper are separate builds — see\ntechnical-documentation/engineering/build-and-packaging.md.`,
});
// Checked apart from LINUX_REQUIRED because "something named ffmpeg exists" is not the
// property that matters — it has to be a directory holding the *unrenamed* libraries.
// An empty one, or the wrong kind of entry, passes a name match and still ships a
// helper that cannot start.
const helperFfmpeg = path.join(dir, "helper-ffmpeg");
const isDir = fs.existsSync(helperFfmpeg) && fs.statSync(helperFfmpeg).isDirectory();
if (fs.existsSync(helperFfmpeg) && !isDir) {
throw new Error(
`Refusing to package: ${path.relative(ROOT, helperFfmpeg)} is a file, not a directory.\n\n` +
"It should hold the PipeWire helper's unrenamed ffmpeg shared objects.\n" +
"Delete it and re-run:\n\n npm run build:native:linux",
);
}
const libs = isDir
? fs.readdirSync(helperFfmpeg).filter((name) => /^lib(av|sw)\w+\.so\.\d+$/.test(name))
: [];
if (libs.length === 0) {
throw new Error(
"Refusing to package an incomplete Linux payload.\n\n" +
` looked in: ${path.relative(ROOT, helperFfmpeg)}\n\n` +
"Missing:\n - the PipeWire helper's own ffmpeg shared objects\n" +
" without it: openscreen-pipewire-helper dies in ld.so, so capture never starts\n" +
` ${FIX_LINUX_HELPER.replace(/\n+/g, " ")}\n\n` +
"These are deliberately not the copies one level up: those have every symbol\n" +
"renamed to `osff_*` for the compositor addon, and the helper needs the originals.",
);
}
checkLinuxSymbolVersionFloor(dir);
}
/**
* The highest versioned symbol a shipped ELF may require, per version prefix.
*
* The Linux counterpart of the Windows import-table guard (checkWinNoRedistDependency
* and importedDlls(), from #321 — this may land first, in which case they arrive with
* it), and the same failure that hook could not see: the linker binds each symbol to
* the newest version the BUILD machine
* offers, so the runner image silently decides the oldest distro the packages run on.
* It works on every developer machine and in CI by construction, and only the target
* distro tells the truth.
*
* Nothing in the source asks for any of it. Built on ubuntu-latest (24.04) the payload
* needed GLIBC_2.38 for four `__isoc23_strto*` — glibc 2.38's C23 redirect of `strtol`
* — GLIBCXX_3.4.32 for `_ZSt21ios_base_library_initv`, which GCC 13.2+ emits into every
* translation unit that includes <iostream>, and GLIBC_2.35 for one `hypotf`, a symbol
* that has existed since 2.2.5 and whose newest version Rust's f32::hypot simply took.
*
* That shipped: on Ubuntu 22.04, Debian 12 and RHEL 9, whisper-stt-server and the ggml
* backends died in ld.so before main() (transcription and captions fail with a developer
* error), and on RHEL 9 compositor_view.node failed require() as well (no preview, and
* every export falls back to the no-op compositor). The app still LAUNCHES on all of
* them — Electron itself only needs 2.25 — so it reads as a broken app rather than a
* broken package, and nothing in any log says otherwise. No package format catches it
* either: the deb/rpm/pacman `depends` lists are hand-written in electron-builder.json5,
* and electron-builder passes fpm none of --rpm-autoreq*, so not even dnf generates the
* `libc.so.6(GLIBC_2.38)` requirement that would have refused the install.
*
* The ceiling is what the OLDEST distro the README claims actually provides. Ubuntu
* 22.04 is the binding one — glibc 2.35, libstdc++6 from GCC 12 — against Debian 12's
* 2.36 with the same libstdc++. Raising any of these is a decision to drop a distro
* from the README, not a build detail; the runners are pinned to match (build.yml's
* build-linux and build-whisper-stt.yml).
*/
const MAX_SYMBOL_VERSION = { GLIBC: "2.35", GLIBCXX: "3.4.30", CXXABI: "1.3.13" };
/**
* The oldest macOS anything in the payload may demand — the macOS twin of
* MAX_SYMBOL_VERSION above, and the same class of bug on a different libc.
*
* Must equal `mac.minimumSystemVersion` in electron-builder.json5, which is what the .app
* tells LaunchServices; before-pack.test.mjs asserts exactly that, so the two cannot drift
* apart quietly. Not read from the config at runtime because this hook must keep working
* if that file is ever restructured — a guard that throws while parsing is a guard that
* gets deleted.
*/
const MAC_MIN_OS_FLOOR = "13.0";
/**
* The one supported way past the ceiling, for the one case it does not fit: a developer
* on a distro newer than the floor, building a package for their own machine.
*
* Without it there is no way to get a .deb out of a working tree on, say, Ubuntu 24.04.
* `npm run build:whisper-binaries` links whisper/ggml against the host's glibc, so the
* guard refuses every local build and the only recourse is to push and wait for CI.
* That is a real cost — it means nobody can test a packaging change without a round
* trip — and it is what this exists to remove.
*
* `host` does NOT disable the check. It swaps the pinned ceiling for what this machine
* actually provides, so a payload needing something even the host lacks still fails.
* The guard keeps catching genuinely broken builds; it just stops pretending the
* developer is on Ubuntu 22.04. What it gives up is the distro-floor promise, which is
* exactly the promise a local build is not making.
*
* Refused outright under CI: an escape hatch that can reach a published artifact is not
* an escape hatch, it is a hole. The runners are pinned to the floor, so they never
* need it, and a release built with it set would be the bug this whole file prevents.
*/
const SYMBOL_FLOOR_MODE = process.env.OPENSCREEN_SYMBOL_FLOOR ?? "";
/** Dotted numeric compare, so 3.4.9 < 3.4.30 and 2.4 < 2.38 rather than by string. */
function compareVersions(a, b) {
const left = a.split(".").map(Number);
const right = b.split(".").map(Number);
for (let i = 0; i < Math.max(left.length, right.length); i++) {
if ((left[i] ?? 0) !== (right[i] ?? 0)) return (left[i] ?? 0) - (right[i] ?? 0);
}
return 0;
}
/**
* The highest version an ELF needs per prefix, as `{ GLIBC: "2.38", GLIBCXX: "3.4.32" }`.
*
* Reads `.gnu.version_r` (the version NEEDS) and deliberately not `.gnu.version_d` (the
* version DEFINITIONS): libc and libstdc++ define every version they ever shipped, so
* reading definitions would report a bundled library as needing itself. Parsed here
* rather than shelled out to readelf for the same reason importedDlls() does not use
* dumpbin — binutils is not installed on every machine that packages this.
*
* 64-bit little-endian only, which is every arch this ships (x86_64, aarch64).
*/
function neededSymbolVersions(file) {
const b = fs.readFileSync(file);
if (b.readUInt32BE(0) !== 0x7f454c46) throw new Error(`${file} is not an ELF binary`);
if (b[4] !== 2 || b[5] !== 1) throw new Error(`${file} is not 64-bit little-endian ELF`);
const shoff = Number(b.readBigUInt64LE(0x28));
const shentsize = b.readUInt16LE(0x3a);
const SHT_GNU_VERNEED = 0x6ffffffe;
let section;
for (let i = 0; i < b.readUInt16LE(0x3c); i++) {
const sh = shoff + i * shentsize;
if (b.readUInt32LE(sh + 4) !== SHT_GNU_VERNEED) continue;
// sh_info is the Verneed count; sh_link is the string table these names live in.
const strtabHeader = shoff + b.readUInt32LE(sh + 0x28) * shentsize;
section = {
offset: Number(b.readBigUInt64LE(sh + 0x18)),
count: b.readUInt32LE(sh + 0x2c),
strtab: Number(b.readBigUInt64LE(strtabHeader + 0x18)),
};
break;
}
// No such section means the binary needs no versioned symbols at all — legitimate
// for a fully static one, and nothing to check either way.
if (!section) return {};
const nameAt = (at) =>
b.subarray(section.strtab + at, b.indexOf(0, section.strtab + at)).toString("latin1");
const highest = {};
let verneed = section.offset;
for (let i = 0; i < section.count; i++) {
let vernaux = verneed + b.readUInt32LE(verneed + 8);
for (let j = 0; j < b.readUInt16LE(verneed + 2); j++) {
// "GLIBC_2.38" -> prefix GLIBC, version 2.38. Anything not shaped like that
// (there is none in practice) is skipped rather than guessed at.
const [, prefix, version] =
/^(.+)_(\d+(?:\.\d+)*)$/.exec(nameAt(b.readUInt32LE(vernaux + 8))) ?? [];
if (prefix && (!highest[prefix] || compareVersions(version, highest[prefix]) > 0)) {
highest[prefix] = version;
}
vernaux += b.readUInt32LE(vernaux + 12);
}
verneed += b.readUInt32LE(verneed + 12);
}
return highest;
}
/**
* The mirror of neededSymbolVersions: what a library DEFINES (SHT_GNU_VERDEF) rather
* than what it asks for. Only used to read the host's own ceiling — a payload binary
* defines nothing interesting.
*
* Same hand-rolled parse as above, and for the same reason: this file already refuses
* to shell out to readelf, so that a missing binutils cannot turn the guard off.
*/
function definedSymbolVersions(file) {
const b = fs.readFileSync(file);
if (b.readUInt32BE(0) !== 0x7f454c46) throw new Error(`${file} is not an ELF binary`);
if (b[4] !== 2 || b[5] !== 1) throw new Error(`${file} is not 64-bit little-endian ELF`);
const shoff = Number(b.readBigUInt64LE(0x28));
const shentsize = b.readUInt16LE(0x3a);
const SHT_GNU_VERDEF = 0x6ffffffd;
let section;
for (let i = 0; i < b.readUInt16LE(0x3c); i++) {
const sh = shoff + i * shentsize;
if (b.readUInt32LE(sh + 4) !== SHT_GNU_VERDEF) continue;
// sh_info is the Verdef count; sh_link is the string table these names live in.
const strtabHeader = shoff + b.readUInt32LE(sh + 0x28) * shentsize;
section = {
offset: Number(b.readBigUInt64LE(sh + 0x18)),
count: b.readUInt32LE(sh + 0x2c),
strtab: Number(b.readBigUInt64LE(strtabHeader + 0x18)),
};
break;
}
if (!section) return {};
const nameAt = (at) =>
b.subarray(section.strtab + at, b.indexOf(0, section.strtab + at)).toString("latin1");
const highest = {};
let verdef = section.offset;
for (let i = 0; i < section.count; i++) {
// Verdef: vd_version(2) vd_flags(2) vd_ndx(2) vd_cnt(2) vd_hash(4) vd_aux(4) vd_next(4)
let verdaux = verdef + b.readUInt32LE(verdef + 12);
for (let j = 0; j < b.readUInt16LE(verdef + 6); j++) {
// Verdaux: vda_name(4) vda_next(4). The first entry of the first Verdef is the
// soname rather than a version, and it simply does not match the pattern.
const [, prefix, version] =
/^(.+)_(\d+(?:\.\d+)*)$/.exec(nameAt(b.readUInt32LE(verdaux))) ?? [];
if (prefix && (!highest[prefix] || compareVersions(version, highest[prefix]) > 0)) {
highest[prefix] = version;
}
verdaux += b.readUInt32LE(verdaux + 4);
}
verdef += b.readUInt32LE(verdef + 16);
}
return highest;
}
/**
* What THIS machine provides, read from the libraries node itself is running against —
* `process.report` gives their absolute paths, so there is nothing to guess at and no
* `ldconfig` to parse. node links both of the ones that matter.
*/
function hostSymbolCeiling() {
const providers = process.report
.getReport()
.sharedObjects.filter((so) => /\/lib(?:c|stdc\+\+)\.so\.6(?:\.\d+)*$/.test(so));
const ceiling = {};
for (const lib of providers) {
for (const [prefix, version] of Object.entries(definedSymbolVersions(lib))) {
if (!(prefix in MAX_SYMBOL_VERSION)) continue;
if (!ceiling[prefix] || compareVersions(version, ceiling[prefix]) > 0) {
ceiling[prefix] = version;
}
}
}
// Every prefix the pinned ceiling names has to come back, or the comparison below
// would quietly skip one and pass a payload nobody checked.
const missing = Object.keys(MAX_SYMBOL_VERSION).filter((prefix) => !ceiling[prefix]);
if (missing.length > 0) {
throw new Error(
`OPENSCREEN_SYMBOL_FLOOR=host could not read ${missing.join(", ")} from this machine.\n\n` +
` looked in: ${providers.join(", ") || "(node reported no libc/libstdc++)"}\n\n` +
"Unset the variable to check against the pinned floor instead.",
);
}
return ceiling;
}
/**
* The ceiling this run compares against, plus whether it is the pinned one. Validates
* OPENSCREEN_SYMBOL_FLOOR here rather than at module load, so a stray value cannot
* break a Windows or macOS pack that never consults it.
*/
function resolveSymbolCeiling() {
if (SYMBOL_FLOOR_MODE === "") {
return { ceiling: MAX_SYMBOL_VERSION, pinned: true };
}
// An unrecognised value is an error, never a silent "enforce" or a silent "waive":
// a typo in the one variable that relaxes this guard must not decide either way.
if (SYMBOL_FLOOR_MODE !== "host") {
throw new Error(
`OPENSCREEN_SYMBOL_FLOOR=${SYMBOL_FLOOR_MODE} is not a value this guard knows.\n\n` +
'The only accepted value is "host": compare against this machine rather than the\n' +
"oldest supported distro, for a package you are building to run locally.\n" +
"Unset it to check against the pinned floor.",
);
}
if (process.env.CI) {
throw new Error(
"OPENSCREEN_SYMBOL_FLOOR=host is refused under CI.\n\n" +
"It exists so a developer on a newer distro can build a package for their own\n" +
"machine; a released artifact built with it would not start on the distros the\n" +
"README claims. The runners are pinned to the floor (build.yml build-linux,\n" +
"build-whisper-stt.yml), so nothing on CI needs it.",
);
}
return { ceiling: hostSymbolCeiling(), pinned: false };
}
// Exported for scripts/before-pack.test.mjs and nothing else. The two refusals above
// are the only things standing between this escape hatch and a published package that
// starts on nobody's machine but the builder's, and they are reachable from a test
// without a payload to scan — so they are tested rather than trusted.
exports.__testing = {
resolveSymbolCeiling,
MAX_SYMBOL_VERSION,
machoMinOs,
checkMacOsVersionFloor,
MAC_MIN_OS_FLOOR,
MAC_REQUIRED,
LINUX_REQUIRED,
checkNativePayload,
checkWinShippedRedist,
};
/** Every ELF under `dir`, recursively — the helper's ffmpeg sits in a subdirectory. */
function elfFilesUnder(dir) {
const found = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
found.push(...elfFilesUnder(full));
continue;
}
if (!entry.isFile()) continue;
// By magic, not by extension: the helpers, whisper-stt-server and ffmpeg have none.
const magic = Buffer.alloc(4);
const fd = fs.openSync(full, "r");
try {
fs.readSync(fd, magic, 0, 4, 0);
} finally {
fs.closeSync(fd);
}
if (magic.readUInt32BE(0) === 0x7f454c46) found.push(full);
}
return found;
}
/** Nothing we ship may need a newer glibc or libstdc++ than MAX_SYMBOL_VERSION allows. */
function checkLinuxSymbolVersionFloor(dir) {
const scanned = elfFilesUnder(dir).map((file) => ({
name: path.relative(dir, file),
needs: neededSymbolVersions(file),
}));
// The same assertion checkWinNoRedistDependency makes, for the same reason: a guard
// that silently stops looking reports "clean" for the rest of the project's life.
// Every dynamically linked binary in this payload needs versioned glibc symbols, so
// finding none anywhere means the parser broke. Asserted across the scan rather than
// per file, because a genuinely static binary legitimately has no .gnu.version_r.
if (!scanned.some((entry) => entry.needs.GLIBC)) {
throw new Error(
`Refusing to package: read no glibc symbol versions from any of the ${scanned.length} ` +
`ELF files in ${path.relative(ROOT, dir)}.\n\n` +
"Every one of them links glibc, so this is a bug in neededSymbolVersions()\n" +
"(scripts/before-pack.cjs), not a self-contained payload. Fix the parser — leaving\n" +
"it is how packages that cannot start on the supported distros get shipped again.",
);
}
// After the parser assertion on purpose: "does the pinned floor apply here" and "did
// the scan work at all" are unrelated questions, and the second is how this guard
// stays honest whichever ceiling it ends up using.
const { ceiling, pinned } = resolveSymbolCeiling();
if (!pinned) {
// Loud, because a relaxed guard that says nothing is indistinguishable from a
// guard that passed — and this one leaves a package that only runs here.
console.log(
`[before-pack] symbol-version ceiling taken from THIS MACHINE, not the pinned floor:\n` +
` ${Object.entries(ceiling)
.map(([prefix, max]) => `${prefix}_${max}`)
.join(", ")} (pinned floor: ${Object.entries(MAX_SYMBOL_VERSION)
.map(([prefix, max]) => `${prefix}_${max}`)
.join(", ")})\n` +
" OPENSCREEN_SYMBOL_FLOOR=host is set. The package this produces may not start on\n" +
" the distros the README claims — do not publish it.",
);
}
const offenders = scanned
.map((entry) => ({
name: entry.name,
bad: Object.entries(ceiling)
.filter(
([prefix, max]) => entry.needs[prefix] && compareVersions(entry.needs[prefix], max) > 0,
)
.map(([prefix, max]) => `${prefix}_${entry.needs[prefix]} (max ${prefix}_${max})`),
}))
.filter((entry) => entry.bad.length > 0);
if (offenders.length === 0) {
return;
}
throw new Error(
"Refusing to package binaries that need a newer glibc or libstdc++ than the oldest\n" +
"supported distro provides.\n\n" +
` looked in: ${path.relative(ROOT, dir)}\n\n` +
`${offenders.map((o) => ` - ${o.name} needs ${o.bad.join(", ")}`).join("\n")}\n\n` +
"Almost certainly nothing asked for this: the linker binds each symbol to the newest\n" +
"version the build machine offers, so this means something was built on a newer image\n" +
"than the floor. On the target it dies in ld.so before main() or fails require(), while\n" +
"the app still launches — so it reads as a broken app, and no package format catches it.\n\n" +
"Build on the pinned runners: ubuntu-22.04 in .github/workflows/build.yml (build-linux)\n" +
"and build-whisper-stt.yml. To see which symbols pulled a version in:\n\n" +
" readelf -V <file>\n" +
" readelf -W --dyn-syms <file> | grep @GLIBC_2.38\n\n" +
(pinned
? "Building a package to run on THIS machine rather than to release? Set\n" +
"OPENSCREEN_SYMBOL_FLOOR=host, which compares against your own glibc instead of\n" +
"the floor. It is refused under CI, so it cannot reach a published artifact.\n\n"
: "") +
"Raising MAX_SYMBOL_VERSION drops a distro the README claims to support.",
);
}
/**
* The macOS minimum-OS a Mach-O declares, as "12.0", or null if it declares none.
*
* Reads LC_BUILD_VERSION (and LC_VERSION_MIN_MACOSX, which is what anything built
* against an older SDK carries) straight out of the file. Parsed here rather than
* shelled out to `vtool -show-build` for the same reason neededSymbolVersions() does not
* use readelf and importedDlls() does not use dumpbin — but with an extra one on top:
* this hook runs for the Windows and Linux packs too, and vtool exists on neither, so a
* subprocess would have to be skipped on exactly the hosts where skipping is silent.
* Parsing makes the guard host-independent instead of conditionally absent.
*
* Universal binaries are walked slice by slice and the HIGHEST floor wins: an x86_64 half
* built on a newer machine strands Intel users just as thoroughly as a thin binary would.
*/
function machoMinOs(file) {
const b = fs.readFileSync(file);
const FAT_MAGIC = 0xcafebabe;
const FAT_MAGIC_64 = 0xcafebabf;
const MH_MAGIC_64 = 0xfeedfacf;
const MH_MAGIC_32 = 0xfeedface;
const LC_VERSION_MIN_MACOSX = 0x24;
const LC_BUILD_VERSION = 0x32;
const PLATFORM_MACOS = 1;
/** X.Y.Z packed as nibbles: 0x000c0000 is 12.0.0. */
const decode = (packed) => `${packed >>> 16}.${(packed >> 8) & 0xff}.${packed & 0xff}`;
const sliceMinOs = (start) => {
const magic = b.readUInt32LE(start);