bun_runtime 0.1.0

Bao runtime integration — JS engine + Bun API + event loop
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
// @trace REQ-ENG-006 [api:node:worker_threads]
//
// Node.js `worker_threads` builtin module — real OS-thread Workers.
//
// Architecture:
//   - SpiderMonkey's JSEngine is process-global (OnceLock<JSEngineHandle>).
//   - Each Worker spawns a std::thread that calls Runtime::new(handle) to get
//     its own thread-local JSContext. No cross-thread JSObject sharing.
//   - Messages cross threads as SpiderMonkey structured-clone bytes via mpsc
//     channels (Node semantics: postMessage = structured clone, NOT JSON —
//     TypedArray/Map/Set/Date/BigInt/cyclic objects keep their types).
//   - Worker JS objects (postMessage/terminate/threadId) are native host fns.

use ::std::cell::RefCell;
use ::std::ffi::CString;
use ::std::ptr::NonNull;
use ::std::sync::atomic::{AtomicU32, Ordering};
use ::std::sync::mpsc::{self, Receiver, Sender};
use ::std::sync::OnceLock;

use dashmap::DashMap;
use mozjs::conversions::unsafe_jsstr_to_string;
use mozjs::glue::{
    CopyJSStructuredCloneData, GetLengthOfJSStructuredCloneData, WriteBytesToJSStructuredCloneData,
};
use mozjs::jsapi::*;
use mozjs::jsval::{BooleanValue, Int32Value, JSVal, ObjectValue, StringValue, UndefinedValue};
use mozjs::realm::AutoRealm;
use mozjs::rooted;
use mozjs::rust::wrappers2 as w2;
use mozjs::rust::JSAutoStructuredCloneBufferWrapper;

use crate::require::cache_builtin;

// ---------------------------------------------------------------------------
// Worker registry (process-global)
// ---------------------------------------------------------------------------

/// Next thread ID counter (monotonically increasing).
static NEXT_THREAD_ID: AtomicU32 = AtomicU32::new(1);

/// Process-wide registry of live Workers, keyed by threadId.
/// Stores the sender half so main-thread code can postMessage / terminate.
static WORKER_REGISTRY: OnceLock<DashMap<u32, WorkerHandle>> = OnceLock::new();

fn worker_registry() -> &'static DashMap<u32, WorkerHandle> {
    WORKER_REGISTRY.get_or_init(DashMap::new)
}

/// Handle held by the main thread for each Worker.
struct WorkerHandle {
    sender: Sender<WorkerMessage>,
    /// JoinHandle for the worker OS thread, taken on terminate/join.
    thread: Option<::std::thread::JoinHandle<()>>,
    /// Receiver for worker → main messages, drained non-blockingly by
    /// `worker_try_recv` (the main-side receive primitive). Mutex-wrapped:
    /// mpsc::Receiver is !Sync but the registry is a process-global static.
    main_rx: Option<::std::sync::Mutex<Receiver<WorkerToMainMessage>>>,
}

// ---------------------------------------------------------------------------
// Cross-thread messages
// ---------------------------------------------------------------------------

enum WorkerMessage {
    /// Structured-clone bytes from main → worker.
    Data(Vec<u8>),
    /// Signal the worker thread to exit.
    Terminate,
}

/// Messages from worker thread → main thread.
enum WorkerToMainMessage {
    /// Structured-clone bytes.
    Data(Vec<u8>),
    /// Error message.
    Error(String),
}

// ---------------------------------------------------------------------------
// Structured clone (SpiderMonkey engine, no host callbacks)
// ---------------------------------------------------------------------------
//
// Node semantics: postMessage uses the structured clone algorithm. We use
// SpiderMonkey's own JS_WriteStructuredClone / JS_ReadStructuredClone — the
// same engine servo's DOM postMessage builds on — with NO host callbacks:
// every plain JS value type is covered natively (Map/Set/Date/RegExp/
// TypedArray/ArrayBuffer/BigInt/cyclic object graphs preserve identity), and
// anything the engine cannot clone (functions, WeakMap, ...) fails the write,
// which the callers surface as a DataCloneError. `DifferentProcess` scope
// keeps the serialized form a flat byte buffer, safe to move across threads
// via mpsc. Both ends live in the same binary, so no protocol versioning is
// needed beyond the engine's own JS_STRUCTURED_CLONE_VERSION header.

/// Clone data policy: shared-memory objects are rejected (cross-thread SAB
/// semantics are not provided); everything else clones.
fn sc_clone_policy() -> CloneDataPolicy {
    CloneDataPolicy {
        allowIntraClusterClonableSharedObjects_: false,
        allowSharedMemoryObjects_: false,
    }
}

/// Serialize `value` into structured-clone bytes. `Err(())` when the value
/// contains anything the structured clone algorithm cannot clone — the caller
/// must report a DataCloneError (Node ERR_DATACLONE_ERROR semantics).
#[allow(unsafe_op_in_unsafe_fn)]
pub(crate) unsafe fn sc_serialize(raw_cx: *mut JSContext, value: JSVal) -> ::std::result::Result<Vec<u8>, ()> {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(raw_cx));
    let cx = &mut wrapped_cx;

    rooted!(&in(cx) let val = value);
    rooted!(&in(cx) let mut no_transfer = UndefinedValue());

    // SAFETY: scbuf owns the clone buffer until the bytes are copied out
    // below; null callbacks = no host custom types (unsupported → write
    // fails, which is the DataCloneError path).
    let scbuf = unsafe {
        JSAutoStructuredCloneBufferWrapper::new(
            StructuredCloneScope::DifferentProcess,
            ::std::ptr::null(),
        )
    };
    let scdata = unsafe { &mut ((*scbuf.as_raw_ptr()).data_) };

    let ok = unsafe {
        w2::JS_WriteStructuredClone(
            cx,
            val.handle(),
            scdata,
            StructuredCloneScope::DifferentProcess,
            &sc_clone_policy(),
            ::std::ptr::null(),
            ::std::ptr::null_mut(),
            no_transfer.handle(),
        )
    };
    if !ok {
        return Err(());
    }

    let nbytes = unsafe { GetLengthOfJSStructuredCloneData(scdata) };
    let mut bytes = Vec::with_capacity(nbytes);
    unsafe {
        CopyJSStructuredCloneData(scdata, bytes.as_mut_ptr());
        bytes.set_len(nbytes);
    }
    Ok(bytes)
}

/// Deserialize structured-clone bytes into `rval`. The caller must have
/// entered the realm the resulting objects should live in (objects are
/// created in the current realm).
#[allow(unsafe_op_in_unsafe_fn)]
pub(crate) unsafe fn sc_deserialize(
    raw_cx: *mut JSContext,
    bytes: &[u8],
    rval: mozjs::gc::MutableHandleValue<'_>,
) -> bool {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(raw_cx));
    let cx = &mut wrapped_cx;

    let scbuf = unsafe {
        JSAutoStructuredCloneBufferWrapper::new(
            StructuredCloneScope::DifferentProcess,
            ::std::ptr::null(),
        )
    };
    let scdata = unsafe { &mut ((*scbuf.as_raw_ptr()).data_) };

    if !bytes.is_empty()
        && !unsafe { WriteBytesToJSStructuredCloneData(bytes.as_ptr(), bytes.len(), scdata) }
    {
        return false;
    }

    unsafe {
        w2::JS_ReadStructuredClone(
            cx,
            scdata,
            JS_STRUCTURED_CLONE_VERSION,
            StructuredCloneScope::DifferentProcess,
            rval,
            &sc_clone_policy(),
            ::std::ptr::null(),
            ::std::ptr::null_mut(),
        )
    }
}

/// Report a DataCloneError (Node message shape) and clear any pending
/// engine exception so the thrown error is deterministic.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn report_data_clone_error(raw_cx: *mut JSContext) {
    let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(raw_cx));
    if w2::JS_IsExceptionPending(&wrapped_cx) {
        JS_ClearPendingException(raw_cx);
    }
    JS_ReportErrorUTF8(
        raw_cx,
        c"DataCloneError: The object could not be cloned.".as_ptr(),
    );
}

// ---------------------------------------------------------------------------
// Worker thread entry point
// ---------------------------------------------------------------------------

fn worker_entry(
    filename: String,
    thread_id: u32,
    receiver: Receiver<WorkerMessage>,
    main_sender: Sender<WorkerToMainMessage>,
    worker_data_bytes: Option<Vec<u8>>,
) {
    // 1. Obtain process-global JSEngine handle.
    let engine_handle = match bao_engine::context::ensure_engine_handle() {
        Ok(h) => h,
        Err(_) => return,
    };

    // 2. Create a new Runtime on this thread — gets its own JSContext.
    let _runtime = mozjs::rust::Runtime::new(engine_handle);

    // 3. Wrap the worker's Runtime in a JsContext (parasitic — Runtime::new
    //    above already set the TLS) with the worker global setup.
    //    Realm-per-context: the worker's single realm is created lazily by
    //    the realm-init eval below and persists for the worker's whole
    //    lifetime, published to thread_realm_global so the message loop and
    //    async dispatch can AutoRealm into it.
    let mut ctx = match unsafe { bao_engine::context::JsContext::from_servo_runtime() } {
        Ok(c) => c,
        Err(_) => return,
    };
    ctx.set_global_setup(worker_global_setup);

    let mut cx = ctx.cx();
    let raw_cx = ctx.raw_cx();

    // 4. Init JobQueue + ModuleLoader on this thread's JSContext.
    if !bao_engine::job_queue::JobQueue::init(&cx) {
        return;
    }
    bao_engine::module_loader::ModuleLoader::init_thread_local(&cx);
    bao_engine::module_loader::set_job_queue_drain(bao_engine::job_queue::JobQueue::drain);

    // 5. Read the worker script from disk.
    let source = match ::std::fs::read_to_string(&filename) {
        Ok(s) => s,
        Err(e) => {
            let msg = format!("Worker: failed to read '{}': {}", filename, e);
            let _ = main_sender.send(WorkerToMainMessage::Error(msg));
            return;
        }
    };

    // 6. Build a bootstrap script that sets up self.onmessage / self.postMessage
    //    then evaluates the worker source.
    //
    //    The worker script can use:
    //      - self.onmessage = function(e) { ... }  (e.data = structured-clone value)
    //      - self.postMessage(data)  (structured-clones data, sends to main thread)
    //      - workerData (from options, also structured-cloned)
    let bootstrap = format!(
        r#"(function() {{
  // workerData — deserialized from structured-clone bytes by the host before
  // this script runs; non-enumerable raw value is deleted after capture.
  var workerData = (typeof __baoWorkerDataRaw === 'undefined') ? null : __baoWorkerDataRaw;
  delete self.__baoWorkerDataRaw;

  var __pendingMessages = [];

  // self.postMessage — structured clone via native host fn; uncloneable
  // values (functions, ...) throw DataCloneError, matching Node.
  self.postMessage = __baoPostToMain;

  // Queue messages until onmessage handler is set. `data` arrives already
  // deserialized from structured-clone bytes by the host.
  self.__baoDeliverMessage = function(data) {{
    if (typeof self.onmessage === 'function') {{
      self.onmessage({{ data: data }});
    }} else {{
      __pendingMessages.push(data);
    }}
  }};

  // When onmessage is set, deliver any queued messages
  var __origOnMessage = null;
  Object.defineProperty(self, 'onmessage', {{
    configurable: true,
    enumerable: true,
    get: function() {{ return __origOnMessage; }},
    set: function(fn) {{
      __origOnMessage = fn;
      // Deliver queued messages
      while (__pendingMessages.length > 0 && typeof fn === 'function') {{
        var data = __pendingMessages.shift();
        fn({{ data: data }});
      }}
    }}
  }});

  // parentPort stub (worker_threads compat)
  var parentPort = {{
    postMessage: self.postMessage,
    on: function() {{}},
    once: function() {{}},
    removeListener: function() {{}},
  }};

  // isMainThread is false inside workers
  self.isMainThread = false;
  self.threadId = {thread_id};
  self.parentPort = parentPort;

  // Execute the worker script
  {source}
}})();"#,
        thread_id = thread_id,
        source = source,
    );

    // 7. Initialize the worker's persistent realm (lazily creates the
    //     global, applies worker_global_setup exactly once, publishes
    //     thread_realm_global). Idempotent + no eval runs, so no exit
    //     dispatch. Then evaluate the bootstrap module INSIDE that realm —
    //     the same realm every later dispatch on this worker (message
    //     delivery, timers, job queue) uses.
    let global_ptr = match ctx.ensure_realm_global(&mut cx, Some(worker_global_setup)) {
        Ok(g) if !g.is_null() => g,
        Ok(_) => {
            let _ = main_sender.send(WorkerToMainMessage::Error(
                "Worker realm global null after ensure_realm_global".into(),
            ));
            return;
        }
        Err(e) => {
            let _ = main_sender.send(WorkerToMainMessage::Error(format!(
                "Worker realm init failed: {}",
                e.message
            )));
            return;
        }
    };
    rooted!(&in(cx) let global = global_ptr);

    // 7a. Deserialize workerData (structured-clone bytes produced on the main
    //     thread) and publish it on the worker global as a non-enumerable
    //     raw value; the bootstrap captures it into `var workerData` and
    //     deletes the global property.
    if let Some(wd_bytes) = worker_data_bytes.as_ref() {
        let mut realm = AutoRealm::new_from_handle(&mut cx, global.handle());
        let realm_cx: &mut mozjs::context::JSContext = &mut realm;
        rooted!(&in(realm_cx) let mut wd_val = UndefinedValue());
        let wd_ok = unsafe { sc_deserialize(realm_cx.raw_cx(), wd_bytes, wd_val.handle_mut()) };
        if !wd_ok {
            let _ = main_sender.send(WorkerToMainMessage::Error(
                "Worker: workerData structured-clone deserialization failed".into(),
            ));
            return;
        }
        unsafe {
            JS_DefineProperty(
                realm_cx.raw_cx(),
                global.handle().into(),
                c"__baoWorkerDataRaw".as_ptr(),
                wd_val.handle().into(),
                0u32, // not enumerable
            );
        }
    }

    let eval_result = bao_engine::module_loader::ModuleLoader::eval_module_in_realm(
        &mut cx,
        &bootstrap,
        &filename,
        None,
        global.handle(),
    );

    if let Err(e) = eval_result {
        let msg = format!(
            "Worker script error: {} ({}:{})",
            e.message, e.filename, e.line
        );
        let _ = main_sender.send(WorkerToMainMessage::Error(msg));
        return;
    }

    // 8. Drain the job queue (process any microtasks from the script).
    bao_engine::job_queue::JobQueue::drain(&mut cx);

    // 9. Store the main_sender in TLS for __baoPostToMain to access.
    WORKER_MAIN_SENDER.with(|s| {
        *s.borrow_mut() = Some(main_sender);
    });

    // 10. Message receive loop: wait for messages from main thread.
    loop {
        match receiver.recv() {
            Ok(WorkerMessage::Data(sc_bytes)) => {
                // Deserialize structured-clone bytes and call
                // self.__baoDeliverMessage(data) on the worker's global.
                deliver_message_to_worker(raw_cx, &sc_bytes);
                bao_engine::job_queue::JobQueue::drain(&mut cx);
            }
            Ok(WorkerMessage::Terminate) | Err(_) => {
                break;
            }
        }
    }
}

/// Global setup for worker JSContext — installs __baoPostToMain native function.
unsafe fn worker_global_setup(
    cx: &mut mozjs::context::JSContext,
    global: mozjs::rust::Handle<*mut JSObject>,
) {
    // Install __baoPostToMain(data) on the global object.
    // This is called by self.postMessage() to send data to the main thread.
    w2::JS_DefineFunction(
        cx,
        global,
        c"__baoPostToMain".as_ptr(),
        Some(worker_post_to_main),
        1,
        JSPROP_ENUMERATE as u32,
    );

    // Node / WorkerGlobalScope semantics: `self` is an alias of the worker
    // global. SpiderMonkey does not provide it on a bare embedding global,
    // and without it every worker bootstrap that touches `self` throws a
    // ReferenceError that module evaluation silently captures in its
    // evaluation promise — the worker then runs its message loop with none
    // of its globals installed.
    rooted!(&in(cx) let global_val = ObjectValue(global.get()));
    JS_DefineProperty(
        cx.raw_cx(),
        global.into(),
        c"self".as_ptr(),
        global_val.handle().into(),
        (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32,
    );
}

/// Native function: __baoPostToMain(data) — called from worker JS to post a
/// message to the main thread. The argument is structured-cloned; uncloneable
/// values throw DataCloneError (Node semantics).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn worker_post_to_main(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"__baoPostToMain requires a value argument".as_ptr());
        return false;
    }

    let data_val = *args.get(0).ptr;
    let sc_bytes = match unsafe { sc_serialize(cx, data_val) } {
        Ok(bytes) => bytes,
        Err(()) => {
            unsafe { report_data_clone_error(cx) };
            return false;
        }
    };

    // Find this worker's main-sender from a thread-local.
    WORKER_MAIN_SENDER.with(|sender| {
        if let Some(tx) = sender.borrow().as_ref() {
            let _ = tx.send(WorkerToMainMessage::Data(sc_bytes));
        }
    });

    args.rval().set(UndefinedValue());
    true
}

// Thread-local for the main-thread sender, set by worker_entry.
thread_local! {
    static WORKER_MAIN_SENDER: RefCell<Option<Sender<WorkerToMainMessage>>> =
        RefCell::new(None);
}

/// Deserialize structured-clone bytes and call self.__baoDeliverMessage(data)
/// in the worker's JSContext.
fn deliver_message_to_worker(raw_cx: *mut JSContext, sc_bytes: &[u8]) {
    unsafe {
        // Realm-per-context: the message loop runs after the bootstrap
        // eval's AutoRealm popped — no realm is entered, so
        // CurrentGlobalOrNull is NULL here (under the old eval-per-global
        // model every message was silently dropped at this point). Enter the
        // worker's persistent realm, published by the realm-init eval.
        let global = match bao_engine::context::thread_realm_global() {
            Some(g) if !g.is_null() => g,
            _ => return,
        };

        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(raw_cx));
        let cx = &mut wrapped_cx;

        rooted!(&in(cx) let global_root = global);
        // All JS below (deserialization, property lookup, call) must run in
        // the realm that owns the global — objects created by the clone
        // reader land in the current realm.
        let mut realm = AutoRealm::new_from_handle(cx, global_root.handle());
        let cx: &mut mozjs::context::JSContext = &mut realm;

        rooted!(&in(cx) let mut data_val = UndefinedValue());
        if !sc_deserialize(raw_cx, sc_bytes, data_val.handle_mut()) {
            // Explicit error path: corrupt bytes must not be silently
            // dropped (same-binary serialization makes this unreachable in
            // practice; report it to the main thread instead).
            WORKER_MAIN_SENDER.with(|sender| {
                if let Some(tx) = sender.borrow().as_ref() {
                    let _ = tx.send(WorkerToMainMessage::Error(
                        "Worker: message structured-clone deserialization failed".into(),
                    ));
                }
            });
            return;
        }

        rooted!(&in(cx) let mut fn_val = UndefinedValue());
        JS_GetProperty(
            raw_cx,
            global_root.handle().into(),
            c"__baoDeliverMessage".as_ptr(),
            fn_val.handle_mut().into(),
        );

        if !fn_val.is_object() {
            return;
        }

        rooted!(&in(cx) let fn_obj = fn_val.to_object());

        let call_args_elements = [data_val.get()];
        let call_args = HandleValueArray {
            length_: 1,
            elements_: call_args_elements.as_ptr() as *const Value,
        };

        rooted!(&in(cx) let fn_obj_val = ObjectValue(fn_obj.get()));
        rooted!(&in(cx) let mut rval = UndefinedValue());
        JS_CallFunctionValue(
            raw_cx,
            global_root.handle().into(),
            fn_obj_val.handle().into(),
            &call_args,
            rval.handle_mut().into(),
        );
    }
}

// ---------------------------------------------------------------------------
// JS-exposed Worker constructor and methods
// ---------------------------------------------------------------------------

/// Worker constructor: `new Worker(filename, options?)`.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn worker_constructor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"Worker requires a filename argument".as_ptr());
        return false;
    }

    let filename_val = *args.get(0).ptr;
    if !filename_val.is_string() {
        JS_ReportErrorUTF8(
            cx,
            c"Worker first argument must be a string filename".as_ptr(),
        );
        return false;
    }

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let filename = unsafe_jsstr_to_string(
        wrapped_cx.raw_cx(),
        NonNull::new_unchecked(filename_val.to_string()),
    );

    // Validate the entry path synchronously, before spawning the worker thread.
    // Node.js throws ERR_WORKER_PATH / ENOENT from the Worker constructor itself
    // when the file does not exist or the path is empty; the previous async
    // (channel-reported) error never surfaced as a JS exception, so
    // `new Worker('/nonexistent')` did not throw — which several conformance
    // tests rely on. Do NOT defer this to the worker thread.
    // Check the raw filename *before* resolve — an empty string would otherwise
    // resolve to cwd and silently pass.
    if filename.is_empty() {
        JS_ReportErrorUTF8(cx, c"Worker: entry file path must not be empty".as_ptr());
        return false;
    }

    // Resolve filename to absolute path.
    let abs_filename = if ::std::path::Path::new(&filename).is_absolute() {
        filename.clone()
    } else {
        match ::std::env::current_dir() {
            Ok(cwd) => cwd.join(&filename).to_string_lossy().to_string(),
            Err(_) => filename.clone(),
        }
    };

    if !::std::path::Path::new(&abs_filename).exists() {
        let msg = format!("Worker: entry file not found: {}", abs_filename);
        let c_msg = ::std::ffi::CString::new(msg).unwrap_or_default();
        JS_ReportErrorUTF8(cx, c_msg.as_ptr());
        return false;
    }

    // Parse options (second argument, optional object).
    let mut worker_data_bytes: Option<Vec<u8>> = None;
    if argc > 1 {
        let opts_val = *args.get(1).ptr;
        if opts_val.is_object() {
            let opts_obj = opts_val.to_object();
            let cx_ref = &mut wrapped_cx;
            rooted!(&in(cx_ref) let opts_root = opts_obj);
            let mut wd_val = UndefinedValue();
            JS_GetProperty(
                cx,
                opts_root.handle().into(),
                c"workerData".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut wd_val,
                },
            );
            if !wd_val.is_undefined() {
                // Serialize workerData with the structured clone algorithm
                // (Node semantics). Uncloneable workerData is a constructor
                // error, not a silent null.
                match unsafe { sc_serialize(cx, wd_val) } {
                    Ok(bytes) => worker_data_bytes = Some(bytes),
                    Err(()) => {
                        unsafe { report_data_clone_error(cx) };
                        return false;
                    }
                }
            }
        }
    }

    // Allocate thread ID.
    let thread_id = NEXT_THREAD_ID.fetch_add(1, Ordering::Relaxed);

    // Create channels.
    let (main_to_worker_tx, main_to_worker_rx): (Sender<WorkerMessage>, Receiver<WorkerMessage>) =
        mpsc::channel();
    let (worker_to_main_tx, worker_to_main_rx): (
        Sender<WorkerToMainMessage>,
        Receiver<WorkerToMainMessage>,
    ) = mpsc::channel();

    // Spawn the worker OS thread.
    let worker_filename = abs_filename.clone();
    let join_handle = ::std::thread::Builder::new()
        .name(format!("bao-worker-{}", thread_id))
        .spawn(move || {
            worker_entry(
                worker_filename,
                thread_id,
                main_to_worker_rx,
                worker_to_main_tx,
                worker_data_bytes,
            );
        });

    let join_handle = match join_handle {
        Ok(h) => h,
        Err(e) => {
            let msg = format!("Worker: failed to spawn thread: {}", e);
            let c_msg = CString::new(msg).unwrap_or_default();
            JS_ReportErrorUTF8(cx, c_msg.as_ptr());
            return false;
        }
    };

    // Register the worker handle. The worker → main receiver lives here and
    // is drained via `worker_try_recv` (main-side receive primitive).
    worker_registry().insert(
        thread_id,
        WorkerHandle {
            sender: main_to_worker_tx,
            thread: Some(join_handle),
            main_rx: Some(::std::sync::Mutex::new(worker_to_main_rx)),
        },
    );

    // Create the Worker JS object with postMessage, terminate, threadId.
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let worker_obj = w2::JS_NewPlainObject(cx_ref));
    if worker_obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Store threadId as a private property so host fns can read it.
    rooted!(&in(cx_ref) let tid_val = Int32Value(thread_id as i32));
    JS_DefineProperty(
        cx,
        worker_obj.handle().into(),
        c"__threadId".as_ptr(),
        tid_val.handle().into(),
        0u32, // not enumerable
    );

    // Store the worker_to_main receiver on the registry handle — drained via
    // `worker_try_recv` instead of a boxed raw pointer on the JS object.

    // Install methods on the instance.
    w2::JS_DefineFunction(
        cx_ref,
        worker_obj.handle(),
        c"postMessage".as_ptr(),
        Some(worker_post_message),
        1,
        JSPROP_ENUMERATE as u32,
    );
    w2::JS_DefineFunction(
        cx_ref,
        worker_obj.handle(),
        c"terminate".as_ptr(),
        Some(worker_terminate),
        0,
        JSPROP_ENUMERATE as u32,
    );
    w2::JS_DefineFunction(
        cx_ref,
        worker_obj.handle(),
        c"ref".as_ptr(),
        Some(worker_noop),
        0,
        JSPROP_ENUMERATE as u32,
    );
    w2::JS_DefineFunction(
        cx_ref,
        worker_obj.handle(),
        c"unref".as_ptr(),
        Some(worker_noop),
        0,
        JSPROP_ENUMERATE as u32,
    );

    // threadId (read-only enumerable property).
    rooted!(&in(cx_ref) let tid_enum = Int32Value(thread_id as i32));
    JS_DefineProperty(
        cx,
        worker_obj.handle().into(),
        c"threadId".as_ptr(),
        tid_enum.handle().into(),
        (JSPROP_ENUMERATE | JSPROP_READONLY) as u32,
    );

    args.rval().set(ObjectValue(worker_obj.get()));
    true
}

/// Worker.prototype.postMessage(data) — serialize data to JSON, send to worker thread.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn worker_post_message(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    // Get threadId from the Worker object.
    let this_val = args.thisv();
    if !this_val.is_object() {
        JS_ReportErrorUTF8(
            cx,
            c"Worker.prototype.postMessage called on non-object".as_ptr(),
        );
        return false;
    }

    let this_obj = this_val.to_object();
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let this_root = this_obj);
    let mut tid_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_root.handle().into(),
        c"__threadId".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut tid_val,
        },
    );

    if !tid_val.is_int32() {
        JS_ReportErrorUTF8(cx, c"Worker: invalid threadId".as_ptr());
        return false;
    }
    let thread_id = tid_val.to_int32() as u32;

    // Transfer list (second argument): explicitly rejected until transfer
    // infrastructure exists (Node accepts an empty list, which is a no-op).
    if argc > 1 {
        let transfer_val = *args.get(1).ptr;
        if transfer_val.is_object() {
            let transfer_obj = transfer_val.to_object();
            rooted!(&in(cx_ref) let transfer_root = transfer_obj);
            let mut len_val = UndefinedValue();
            JS_GetProperty(
                cx,
                transfer_root.handle().into(),
                c"length".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut len_val,
                },
            );
            if len_val.is_int32() && len_val.to_int32() > 0 {
                JS_ReportErrorUTF8(
                    cx,
                    c"DataCloneError: postMessage transfer list is not supported in Bao".as_ptr(),
                );
                return false;
            }
        }
    }

    // Serialize the argument with the structured clone algorithm.
    // Uncloneable values (functions, WeakMap, ...) throw DataCloneError —
    // the old JSON path silently degraded them to null.
    let sc_bytes = if argc > 0 {
        let data_val = *args.get(0).ptr;
        match unsafe { sc_serialize(cx, data_val) } {
            Ok(bytes) => bytes,
            Err(()) => {
                unsafe { report_data_clone_error(cx) };
                return false;
            }
        }
    } else {
        // No payload: postMessage() — clone `undefined` (SC supports it).
        match unsafe { sc_serialize(cx, UndefinedValue()) } {
            Ok(bytes) => bytes,
            Err(()) => {
                unsafe { report_data_clone_error(cx) };
                return false;
            }
        }
    };

    // Send to the worker thread.
    if let Some(handle) = worker_registry().get_mut(&thread_id) {
        let _ = handle.sender.send(WorkerMessage::Data(sc_bytes));
    }

    args.rval().set(UndefinedValue());
    true
}

/// Worker.prototype.terminate() — signal the worker to exit and join its thread.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn worker_terminate(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);

    let this_val = args.thisv();
    if !this_val.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let this_obj = this_val.to_object();
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let this_root = this_obj);
    let mut tid_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_root.handle().into(),
        c"__threadId".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut tid_val,
        },
    );

    if !tid_val.is_int32() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let thread_id = tid_val.to_int32() as u32;

    // Remove from registry and join the thread (dropping the handle also
    // drops the worker → main receiver).
    if let Some((_, mut handle)) = worker_registry().remove(&thread_id) {
        let _ = handle.sender.send(WorkerMessage::Terminate);
        if let Some(join) = handle.thread.take() {
            let _ = join.join();
        }
    }

    args.rval().set(UndefinedValue());
    true
}

/// Worker.prototype.ref() / unref() — no-op (single-process runtime).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn worker_noop(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(UndefinedValue());
    true
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Main-side receive primitive (worker → main)
// ---------------------------------------------------------------------------

/// Outcome of a non-blocking poll of a worker's main-thread inbox.
#[derive(Debug, PartialEq)]
pub enum WorkerIncoming {
    /// A data message was deserialized into the caller-provided `rval`
    /// (inside the current thread's realm).
    Data,
    /// The worker reported an error (message text included).
    Error(String),
    /// No message pending (or the worker is no longer registered).
    Empty,
}

/// Try to receive ONE pending worker → main message and, for data messages,
/// deserialize the structured-clone bytes into `rval` inside the current
/// thread's persistent realm. Non-blocking; call from the main JS thread
/// only. This is the primitive a `worker.onmessage` event-loop integration
/// builds on.
pub fn worker_try_recv(
    cx: &mut mozjs::context::JSContext,
    thread_id: u32,
    rval: mozjs::gc::MutableHandleValue<'_>,
) -> WorkerIncoming {
    // Take one message out of the channel while holding the registry guard
    // only for the try_recv (no JS runs under the DashMap borrow).
    let msg = {
        let handle = match worker_registry().get_mut(&thread_id) {
            Some(h) => h,
            None => return WorkerIncoming::Empty,
        };
        match handle.main_rx.as_ref() {
            Some(rx) => rx.lock().ok().and_then(|rx| rx.try_recv().ok()),
            None => return WorkerIncoming::Empty,
        }
    };

    match msg {
        Some(WorkerToMainMessage::Data(bytes)) => unsafe {
            // Objects created by the clone reader land in the current realm —
            // enter this thread's persistent realm, same as
            // deliver_message_to_worker does on the worker side.
            let global = match bao_engine::context::thread_realm_global() {
                Some(g) if !g.is_null() => g,
                _ => {
                    return WorkerIncoming::Error(
                        "worker_try_recv: main thread realm not initialized".into(),
                    )
                }
            };
            rooted!(&in(cx) let global_root = global);
            let mut realm = AutoRealm::new_from_handle(cx, global_root.handle());
            let realm_cx: &mut mozjs::context::JSContext = &mut realm;
            if sc_deserialize(realm_cx.raw_cx(), &bytes, rval) {
                WorkerIncoming::Data
            } else {
                WorkerIncoming::Error(
                    "worker_try_recv: structured-clone deserialization failed".into(),
                )
            }
        },
        Some(WorkerToMainMessage::Error(msg)) => WorkerIncoming::Error(msg),
        None => WorkerIncoming::Empty,
    }
}

// ---------------------------------------------------------------------------
// Module install
// ---------------------------------------------------------------------------

pub fn install(cx: &mut mozjs::context::JSContext) {
    let raw_cx = unsafe { cx.raw_cx() };

    // Build the module exports object natively.
    rooted!(&in(cx) let exports = unsafe { w2::JS_NewPlainObject(cx) });
    if exports.get().is_null() {
        return;
    }

    unsafe {
        // Worker constructor function.
        let worker_fn = JS_NewFunction(
            raw_cx,
            Some(worker_constructor),
            1,     // min args
            0x400, // JSFUN_CONSTRUCTOR
            c"Worker".as_ptr(),
        );
        if !worker_fn.is_null() {
            let fn_obj = JS_GetFunctionObject(worker_fn);
            rooted!(&in(cx) let fn_root = fn_obj);

            // Worker.prototype — plain object with methods.
            rooted!(&in(cx) let proto = w2::JS_NewPlainObject(cx));
            if !proto.get().is_null() {
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"postMessage".as_ptr(),
                    Some(worker_post_message),
                    1,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"terminate".as_ptr(),
                    Some(worker_terminate),
                    0,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"ref".as_ptr(),
                    Some(worker_noop),
                    0,
                    JSPROP_ENUMERATE as u32,
                );
                w2::JS_DefineFunction(
                    cx,
                    proto.handle(),
                    c"unref".as_ptr(),
                    Some(worker_noop),
                    0,
                    JSPROP_ENUMERATE as u32,
                );

                // Wire prototype onto the constructor.
                rooted!(&in(cx) let proto_val = ObjectValue(proto.get()));
                JS_DefineProperty(
                    raw_cx,
                    fn_root.handle().into(),
                    c"prototype".as_ptr(),
                    proto_val.handle().into(),
                    0u32,
                );
            }

            // Export Worker on the module object.
            rooted!(&in(cx) let fn_val = ObjectValue(fn_root.get()));
            JS_DefineProperty(
                raw_cx,
                exports.handle().into(),
                c"Worker".as_ptr(),
                fn_val.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        // MessageChannel — use globalThis.MessageChannel if available, otherwise in-process stub.
        // We evaluate a JS helper that returns the constructor.
        let source = r#"(function() {
  var MC = (typeof globalThis.MessageChannel === 'function')
    ? globalThis.MessageChannel
    : function MessageChannel() {
        var queue1 = [];
        var queue2 = [];
        var onmsg1 = null;
        var onmsg2 = null;
        this.port1 = {
          postMessage: function(data) {
            if (typeof onmsg2 === 'function') {
              onmsg2({ data: data });
            } else {
              queue2.push(data);
            }
          },
          get onmessage() { return onmsg1; },
          set onmessage(fn) {
            onmsg1 = fn;
            while (queue1.length > 0 && typeof fn === 'function') {
              fn({ data: queue1.shift() });
            }
          },
          close: function() {},
          start: function() {},
          addEventListener: function() {},
          removeEventListener: function() {},
        };
        this.port2 = {
          postMessage: function(data) {
            if (typeof onmsg1 === 'function') {
              onmsg1({ data: data });
            } else {
              queue1.push(data);
            }
          },
          get onmessage() { return onmsg2; },
          set onmessage(fn) {
            onmsg2 = fn;
            while (queue2.length > 0 && typeof fn === 'function') {
              fn({ data: queue2.shift() });
            }
          },
          close: function() {},
          start: function() {},
          addEventListener: function() {},
          removeEventListener: function() {},
        };
      };
  return MC;
})()"#;

        let mut source_text = mozjs::rust::transform_str_to_source_text(source);
        let mut rval = UndefinedValue();
        let rval_handle = MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut rval,
        };
        let opts =
            mozjs::glue::NewCompileOptions(raw_cx, c"<worker_threads:MessageChannel>".as_ptr(), 1);
        if !opts.is_null() {
            let ok = mozjs_sys::jsapi::JS::Evaluate2(raw_cx, opts, &mut source_text, rval_handle);
            libc::free(opts as *mut _);
            if ok && rval.is_object() {
                // The source ends with `})()`, so Evaluate2's completion
                // value IS the MessageChannel constructor already — do NOT
                // call it again. The previous code re-invoked the constructor
                // as a plain function (constructor has no `return` →
                // undefined), so MessageChannel was never exported:
                // require('worker_threads').MessageChannel === undefined
                // (BCE sweep #19, same class as the http2 install() fix,
                // commit 854677b0).
                rooted!(&in(cx) let mc_val = ObjectValue(rval.to_object()));
                JS_DefineProperty(
                    raw_cx,
                    exports.handle().into(),
                    c"MessageChannel".as_ptr(),
                    mc_val.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }

        // MessagePort — delegate to globalThis.MessagePort or refuse.
        // A bare `new MessagePort()` has no entangled peer, so an empty
        // constructor would hand back an inert object whose postMessage
        // silently dropped every message (silent-fake eradication group D).
        // Real ports come from MessageChannel (port1/port2) or Worker.
        let mp_source = r#"(typeof globalThis.MessagePort === 'function'
  ? globalThis.MessagePort
  : function MessagePort() {
      throw new TypeError("worker_threads.MessagePort must be obtained from MessageChannel (port1/port2) or Worker — bare construction is not supported and would return an inert fake port.");
    })"#;
        let mut mp_text = mozjs::rust::transform_str_to_source_text(mp_source);
        let mut mp_val = UndefinedValue();
        let mp_opts =
            mozjs::glue::NewCompileOptions(raw_cx, c"<worker_threads:MessagePort>".as_ptr(), 1);
        if !mp_opts.is_null() {
            let mp_ok = mozjs_sys::jsapi::JS::Evaluate2(
                raw_cx,
                mp_opts,
                &mut mp_text,
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut mp_val,
                },
            );
            libc::free(mp_opts as *mut _);
            if mp_ok && mp_val.is_object() {
                rooted!(&in(cx) let mp_obj = ObjectValue(mp_val.to_object()));
                JS_DefineProperty(
                    raw_cx,
                    exports.handle().into(),
                    c"MessagePort".as_ptr(),
                    mp_obj.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }

        // BroadcastChannel — delegate to globalThis, else real in-process
        // broadcast: a registry keyed by channel name fans every postMessage
        // out to the OTHER open instances of the same channel (per WHATWG
        // semantics the sender does not receive its own message). The
        // previous fallback's postMessage was a no-op that silently dropped
        // every message (silent-fake eradication group D).
        let bc_source = r#"(typeof globalThis.BroadcastChannel === 'function'
  ? globalThis.BroadcastChannel
  : (function() {
      var registry = globalThis.__baoBroadcastRegistry || (globalThis.__baoBroadcastRegistry = {});
      function BroadcastChannel(name) {
        if (!(this instanceof BroadcastChannel)) return new BroadcastChannel(name);
        if (typeof name !== 'string' || name === '') throw new TypeError('BroadcastChannel: name must be a non-empty string');
        this.name = name;
        this.onmessage = null;
        this.onmessageerror = null;
        this._closed = false;
        this._listeners = [];
        (registry[name] || (registry[name] = [])).push(this);
      }
      function _deliver(port, ev) {
        var firstErr = null;
        if (typeof port.onmessage === 'function') {
          try { port.onmessage(ev); } catch (e) { if (!firstErr) firstErr = e; }
        }
        for (var i = 0; i < port._listeners.length; i++) {
          try { port._listeners[i](ev); } catch (e) { if (!firstErr) firstErr = e; }
        }
        return firstErr;
      }
      BroadcastChannel.prototype.postMessage = function(message) {
        if (this._closed) throw new Error('BroadcastChannel "' + this.name + '" is closed');
        var peers = registry[this.name] || [];
        var firstErr = null;
        for (var i = 0; i < peers.length; i++) {
          var peer = peers[i];
          if (peer === this || peer._closed) continue;
          var err = _deliver(peer, { data: message });
          if (err && !firstErr) firstErr = err;
        }
        // Delivery completes for every peer before a throwing handler's
        // error surfaces — no peer is starved, no error is swallowed.
        if (firstErr) throw firstErr;
      };
      BroadcastChannel.prototype.close = function() {
        if (this._closed) return;
        this._closed = true;
        var peers = registry[this.name] || [];
        var idx = peers.indexOf(this);
        if (idx >= 0) peers.splice(idx, 1);
        if (peers.length === 0) delete registry[this.name];
      };
      BroadcastChannel.prototype.addEventListener = function(type, fn) {
        if (typeof fn !== 'function') throw new TypeError('BroadcastChannel.addEventListener: listener must be a function');
        // 'messageerror' can never fire in-process (no structured-clone
        // failures without serialization); anything else is refused.
        if (type !== 'message' && type !== 'messageerror') throw new TypeError('BroadcastChannel.addEventListener: unsupported event type "' + type + '"');
        this._listeners.push(fn);
      };
      BroadcastChannel.prototype.removeEventListener = function(type, fn) {
        if (type !== 'message' && type !== 'messageerror') return;
        var idx = this._listeners.indexOf(fn);
        if (idx >= 0) this._listeners.splice(idx, 1);
      };
      Object.defineProperty(BroadcastChannel.prototype, 'closed', { get: function() { return this._closed; }, configurable: true });
      return BroadcastChannel;
    })())"#;
        let mut bc_text = mozjs::rust::transform_str_to_source_text(bc_source);
        let mut bc_val = UndefinedValue();
        let bc_opts = mozjs::glue::NewCompileOptions(
            raw_cx,
            c"<worker_threads:BroadcastChannel>".as_ptr(),
            1,
        );
        if !bc_opts.is_null() {
            let bc_ok = mozjs_sys::jsapi::JS::Evaluate2(
                raw_cx,
                bc_opts,
                &mut bc_text,
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut bc_val,
                },
            );
            libc::free(bc_opts as *mut _);
            if bc_ok && bc_val.is_object() {
                rooted!(&in(cx) let bc_obj = ObjectValue(bc_val.to_object()));
                JS_DefineProperty(
                    raw_cx,
                    exports.handle().into(),
                    c"BroadcastChannel".as_ptr(),
                    bc_obj.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }

        // Static properties.
        rooted!(&in(cx) let true_val = BooleanValue(true));
        JS_DefineProperty(
            raw_cx,
            exports.handle().into(),
            c"isMainThread".as_ptr(),
            true_val.handle().into(),
            JSPROP_ENUMERATE as u32,
        );

        rooted!(&in(cx) let zero_val = Int32Value(0));
        JS_DefineProperty(
            raw_cx,
            exports.handle().into(),
            c"threadId".as_ptr(),
            zero_val.handle().into(),
            JSPROP_ENUMERATE as u32,
        );

        // workerData and parentPort are null/undefined on the main thread.
        rooted!(&in(cx) let undef_val = UndefinedValue());
        JS_DefineProperty(
            raw_cx,
            exports.handle().into(),
            c"workerData".as_ptr(),
            undef_val.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
        JS_DefineProperty(
            raw_cx,
            exports.handle().into(),
            c"parentPort".as_ptr(),
            undef_val.handle().into(),
            JSPROP_ENUMERATE as u32,
        );

        rooted!(&in(cx) let empty_obj = w2::JS_NewPlainObject(cx));
        rooted!(&in(cx) let empty_obj_val = ObjectValue(empty_obj.get()));
        JS_DefineProperty(
            raw_cx,
            exports.handle().into(),
            c"resourceLimits".as_ptr(),
            empty_obj_val.handle().into(),
            JSPROP_ENUMERATE as u32,
        );

        // SHARE_ENV symbol — create via JS eval.
        let share_env_source = r#"Symbol('nodejs.worker_threads.SHARE_ENV')"#;
        let mut se_text = mozjs::rust::transform_str_to_source_text(share_env_source);
        rooted!(&in(cx) let mut se_val = UndefinedValue());
        let se_opts =
            mozjs::glue::NewCompileOptions(raw_cx, c"<worker_threads:SHARE_ENV>".as_ptr(), 1);
        if !se_opts.is_null() {
            let se_ok = mozjs_sys::jsapi::JS::Evaluate2(
                raw_cx,
                se_opts,
                &mut se_text,
                se_val.handle_mut().into(),
            );
            libc::free(se_opts as *mut _);
            if se_ok {
                JS_DefineProperty(
                    raw_cx,
                    exports.handle().into(),
                    c"SHARE_ENV".as_ptr(),
                    se_val.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }

        // Utility functions (JS-evaluated for simplicity).
        let utils_source = r#"({
  getEnvironmentData: function() {},
  setEnvironmentData: function() {},
  getHeapSnapshot: function() { return {}; },
  markAsUntransferable: function() { throw new Error('markAsUntransferable is not implemented in Bao'); },
  moveMessagePortToContext: function() { throw new Error('moveMessagePortToContext is not implemented in Bao'); },
  receiveMessageOnPort: function() { return undefined; },
})"#;
        let mut ut_text = mozjs::rust::transform_str_to_source_text(utils_source);
        let mut ut_val = UndefinedValue();
        let ut_opts = mozjs::glue::NewCompileOptions(raw_cx, c"<worker_threads:utils>".as_ptr(), 1);
        if !ut_opts.is_null() {
            let ut_ok = mozjs_sys::jsapi::JS::Evaluate2(
                raw_cx,
                ut_opts,
                &mut ut_text,
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut ut_val,
                },
            );
            libc::free(ut_opts as *mut _);
            if ut_ok && ut_val.is_object() {
                let utils_obj = ut_val.to_object();
                rooted!(&in(cx) let utils_root = utils_obj);
                // Copy each property to exports.
                for name in &[
                    "getEnvironmentData",
                    "setEnvironmentData",
                    "getHeapSnapshot",
                    "markAsUntransferable",
                    "moveMessagePortToContext",
                    "receiveMessageOnPort",
                ] {
                    let c_name = CString::new(*name).unwrap_or_default();
                    rooted!(&in(cx) let mut prop_val = UndefinedValue());
                    JS_GetProperty(
                        raw_cx,
                        utils_root.handle().into(),
                        c_name.as_ptr(),
                        prop_val.handle_mut().into(),
                    );
                    if !prop_val.is_undefined() {
                        JS_DefineProperty(
                            raw_cx,
                            exports.handle().into(),
                            c_name.as_ptr(),
                            prop_val.handle().into(),
                            JSPROP_ENUMERATE as u32,
                        );
                    }
                }
            }
        }
    }

    cache_builtin(cx, "worker_threads", exports.get());
}