browser_oxide 0.1.3

Stealth headless browser engine in Rust: real HTML/CSS/DOM/JS, V8 via deno_core, own BoringSSL TLS/JA4 fingerprint, no Chromium, no CDP — for anti-bot web scraping, archival, and AI agents
Documentation
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
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
use crate::css_values::calc::resolve_computed_value;
use crate::css_values::types::length::CalcContext;
use crate::dom::node::NodeId;
use crate::dom::DomElement;
use crate::js_runtime::native_fns::{install_native_fp_tostring, IframeRealmStore};
use crate::js_runtime::state::DomState;
use crate::js_runtime::utils::tokens_to_string;
use deno_core::op2;
use deno_core::v8;
use deno_core::JsRuntime;
use deno_core::OpState;
use std::collections::HashMap;

/// Build a `CalcContext` from the current DOM state's stealth profile.
/// Provides viewport + font-size + container dimensions so calc()
/// math functions can resolve relative units (vw, em, etc.) correctly
/// for `getComputedStyle` resolution.
fn calc_context_from(state: &DomState) -> CalcContext {
    let mut ctx = CalcContext::default();
    if let Some(p) = state.stealth_profile.as_ref() {
        ctx.viewport_w = p.inner_width as f64;
        ctx.viewport_h = p.inner_height as f64;
        ctx.container_w = p.inner_width as f64;
        ctx.container_h = p.inner_height as f64;
        // 16px is Chrome's default; profiles don't currently override.
        ctx.root_font_size_px = 16.0;
        ctx.font_size_px = 16.0;
    }
    ctx
}

// Convention: ops that return "nullable NodeId" return i64.
// -1 means null/not found. JS bootstrap converts -1 → null.

// --- Read ops ---

#[op2(fast)]
#[smi]
pub fn op_dom_document_node() -> i32 {
    NodeId::DOCUMENT.to_raw() as i32
}

#[op2]
#[string]
pub fn op_dom_get_tag_name(state: &mut OpState, #[smi] node_id: i32) -> String {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    state
        .dom
        .get(id)
        .and_then(|n| n.as_element())
        .map(|e| e.name.local.clone())
        .unwrap_or_default()
}

#[op2(fast)]
#[smi]
pub fn op_dom_get_node_type(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    state.dom.node_type(NodeId::from_raw(node_id as u32)) as i32
}

#[op2]
#[string]
pub fn op_dom_get_text_content(state: &mut OpState, #[smi] node_id: i32) -> String {
    let state = state.borrow::<DomState>();
    state.dom.text_content(NodeId::from_raw(node_id as u32))
}

#[op2]
#[string]
pub fn op_dom_get_inner_html(state: &mut OpState, #[smi] node_id: i32) -> String {
    let state = state.borrow::<DomState>();
    state
        .dom
        .serialize_inner_html(NodeId::from_raw(node_id as u32))
}

#[op2]
#[string]
pub fn op_dom_get_outer_html(state: &mut OpState, #[smi] node_id: i32) -> String {
    let state = state.borrow::<DomState>();
    state.dom.serialize_html(NodeId::from_raw(node_id as u32))
}

#[op2]
#[string]
pub fn op_dom_get_attribute(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] name: &str,
) -> String {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    state
        .dom
        .get(id)
        .and_then(|n| n.as_element())
        .and_then(|e| {
            e.attrs
                .iter()
                .find(|a| a.name.local.eq_ignore_ascii_case(name))
                .map(|a| a.value.clone())
        })
        .unwrap_or_default()
}

#[op2(fast)]
pub fn op_dom_has_attribute(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] name: &str,
) -> bool {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    state
        .dom
        .get(id)
        .and_then(|n| n.as_element())
        .is_some_and(|e| {
            e.attrs
                .iter()
                .any(|a| a.name.local.eq_ignore_ascii_case(name))
        })
}

/// Returns the names of all attributes on `node_id`, in source order.
/// Used by Proxy ownKeys traps for `element.attributes` and `element.dataset`.
#[op2]
#[serde]
pub fn op_dom_get_attribute_names(state: &mut OpState, #[smi] node_id: i32) -> Vec<String> {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    state
        .dom
        .get(id)
        .and_then(|n| n.as_element())
        .map(|e| e.attrs.iter().map(|a| a.name.local.clone()).collect())
        .unwrap_or_default()
}

/// Returns parent NodeId or -1 if no parent.
#[op2(fast)]
#[smi]
pub fn op_dom_get_parent(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    state
        .dom
        .get(id)
        .and_then(|n| n.parent)
        .map(|p| p.to_raw() as i32)
        .unwrap_or(-1)
}

#[op2]
#[serde]
pub fn op_dom_get_children(state: &mut OpState, #[smi] node_id: i32) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    state
        .dom
        .children(NodeId::from_raw(node_id as u32))
        .iter()
        .map(|id| id.to_raw() as i32)
        .collect()
}

#[op2]
#[serde]
pub fn op_dom_get_children_with_types(state: &mut OpState, #[smi] node_id: i32) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    let children = state.dom.children(id);
    let mut res = Vec::with_capacity(children.len() * 2);
    for cid in children {
        res.push(cid.to_raw() as i32);
        res.push(state.dom.node_type(cid) as i32);
    }
    res
}

#[op2]
#[serde]
pub fn op_dom_get_child_elements(state: &mut OpState, #[smi] node_id: i32) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    state
        .dom
        .child_elements(NodeId::from_raw(node_id as u32))
        .iter()
        .map(|id| id.to_raw() as i32)
        .collect()
}

#[op2]
#[serde]
pub fn op_dom_get_child_elements_with_types(state: &mut OpState, #[smi] node_id: i32) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    let children = state.dom.child_elements(id);
    let mut res = Vec::with_capacity(children.len() * 2);
    for cid in children {
        res.push(cid.to_raw() as i32);
        res.push(state.dom.node_type(cid) as i32);
    }
    res
}

#[op2(fast)]
#[smi]
pub fn op_dom_get_first_child(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get(NodeId::from_raw(node_id as u32))
        .and_then(|n| n.first_child)
        .map(|id| id.to_raw() as i32)
        .unwrap_or(-1)
}

#[op2(fast)]
#[smi]
pub fn op_dom_get_last_child(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get(NodeId::from_raw(node_id as u32))
        .and_then(|n| n.last_child)
        .map(|id| id.to_raw() as i32)
        .unwrap_or(-1)
}

#[op2(fast)]
#[smi]
pub fn op_dom_get_next_sibling(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get(NodeId::from_raw(node_id as u32))
        .and_then(|n| n.next_sibling)
        .map(|id| id.to_raw() as i32)
        .unwrap_or(-1)
}

#[op2(fast)]
#[smi]
pub fn op_dom_get_prev_sibling(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get(NodeId::from_raw(node_id as u32))
        .and_then(|n| n.prev_sibling)
        .map(|id| id.to_raw() as i32)
        .unwrap_or(-1)
}

#[op2(fast)]
#[smi]
pub fn op_dom_query_selector(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] selector: &str,
) -> i32 {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    let element = match DomElement::new(&state.dom, id) {
        Some(el) => el,
        None => {
            // For Document node, search from first element child
            let children = state.dom.child_elements(id);
            if children.is_empty() {
                return -1;
            }
            match DomElement::new(&state.dom, children[0]) {
                Some(el) => {
                    // Search from root element
                    if let Ok(Some(found)) = crate::css_selectors::query_selector(&el, selector) {
                        return found.node_id().to_raw() as i32;
                    }
                    return -1;
                }
                None => return -1,
            }
        }
    };
    match crate::css_selectors::query_selector(&element, selector) {
        Ok(Some(found)) => found.node_id().to_raw() as i32,
        _ => -1,
    }
}

#[op2]
#[serde]
pub fn op_dom_query_selector_all(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] selector: String,
) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    // For document or element, try to build a DomElement for querying
    let root_el = DomElement::new(&state.dom, id).or_else(|| {
        let children = state.dom.child_elements(id);
        children
            .first()
            .and_then(|&c| DomElement::new(&state.dom, c))
    });
    match root_el {
        Some(el) => crate::css_selectors::query_selector_all(&el, &selector)
            .unwrap_or_default()
            .iter()
            .map(|e| e.node_id().to_raw() as i32)
            .collect(),
        None => vec![],
    }
}

#[op2(fast)]
#[smi]
pub fn op_dom_get_element_by_id(state: &mut OpState, #[string] id: &str) -> i32 {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get_element_by_id(id)
        .map(|n| n.to_raw() as i32)
        .unwrap_or(-1)
}

#[op2]
#[serde]
pub fn op_dom_get_elements_by_tag_name(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] tag: String,
) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get_elements_by_tag_name(NodeId::from_raw(node_id as u32), &tag)
        .iter()
        .map(|id| id.to_raw() as i32)
        .collect()
}

#[op2]
#[serde]
pub fn op_dom_get_elements_by_class_name(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] class: String,
) -> Vec<i32> {
    let state = state.borrow::<DomState>();
    state
        .dom
        .get_elements_by_class_name(NodeId::from_raw(node_id as u32), &class)
        .iter()
        .map(|id| id.to_raw() as i32)
        .collect()
}

// --- Mutation ops ---

#[op2(fast)]
#[smi]
pub fn op_dom_create_element(state: &mut OpState, #[string] tag: &str) -> i32 {
    let state = state.borrow_mut::<DomState>();
    state
        .dom
        .create_element(crate::dom::node::QualName::new(tag), vec![])
        .to_raw() as i32
}

#[op2(fast)]
#[smi]
pub fn op_dom_create_text_node(state: &mut OpState, #[string] text: &str) -> i32 {
    let state = state.borrow_mut::<DomState>();
    state.dom.create_text(text.to_string()).to_raw() as i32
}

#[op2(fast)]
#[smi]
pub fn op_dom_create_document_fragment(state: &mut OpState) -> i32 {
    let state = state.borrow_mut::<DomState>();
    state.dom.create_document_fragment().to_raw() as i32
}

#[op2(fast)]
pub fn op_dom_append_child(state: &mut OpState, #[smi] parent: i32, #[smi] child: i32) {
    let state = state.borrow_mut::<DomState>();
    state.dom.append_child(
        NodeId::from_raw(parent as u32),
        NodeId::from_raw(child as u32),
    );
    state.layout_engine.mark_dirty();
}

#[op2(fast)]
pub fn op_dom_insert_before(
    state: &mut OpState,
    #[smi] parent: i32,
    #[smi] child: i32,
    #[smi] reference: i32,
) {
    let state = state.borrow_mut::<DomState>();
    state.dom.insert_before(
        NodeId::from_raw(parent as u32),
        NodeId::from_raw(child as u32),
        NodeId::from_raw(reference as u32),
    );
    state.layout_engine.mark_dirty();
}

#[op2(fast)]
pub fn op_dom_remove_child(state: &mut OpState, #[smi] _parent: i32, #[smi] child: i32) {
    let state = state.borrow_mut::<DomState>();
    state.dom.detach(NodeId::from_raw(child as u32));
    state.layout_engine.mark_dirty();
}

#[op2(fast)]
pub fn op_dom_set_attribute(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] name: &str,
    #[string] value: &str,
) {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    if let Some(node) = state.dom.get_mut(id) {
        if let Some(elem) = node.as_element_mut() {
            if let Some(attr) = elem
                .attrs
                .iter_mut()
                .find(|a| a.name.local.eq_ignore_ascii_case(name))
            {
                attr.value = value.to_string();
            } else {
                elem.attrs.push(crate::dom::node::Attribute {
                    name: crate::dom::node::QualName::new(name),
                    value: value.to_string(),
                });
            }
        }
    }
    if name.eq_ignore_ascii_case("style") || name.eq_ignore_ascii_case("class") {
        state.layout_engine.mark_dirty();
    }
}

#[op2(fast)]
pub fn op_dom_remove_attribute(state: &mut OpState, #[smi] node_id: i32, #[string] name: &str) {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    if let Some(node) = state.dom.get_mut(id) {
        if let Some(elem) = node.as_element_mut() {
            elem.attrs
                .retain(|a| !a.name.local.eq_ignore_ascii_case(name));
        }
    }
    if name.eq_ignore_ascii_case("style") || name.eq_ignore_ascii_case("class") {
        state.layout_engine.mark_dirty();
    }
}

#[op2(fast)]
pub fn op_dom_set_text_content(state: &mut OpState, #[smi] node_id: i32, #[string] text: &str) {
    let state = state.borrow_mut::<DomState>();
    state
        .dom
        .set_text_content(NodeId::from_raw(node_id as u32), text);
    state.layout_engine.mark_dirty();
}

#[op2(fast)]
pub fn op_dom_set_inner_html(state: &mut OpState, #[smi] node_id: i32, #[string] html: &str) {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    let fragment_dom = crate::html_parser::parse_html(&format!("<body>{}</body>", html));
    let body = fragment_dom
        .get_elements_by_tag_name(NodeId::DOCUMENT, "body")
        .into_iter()
        .next();

    // Remove existing children
    let old_children: Vec<NodeId> = state.dom.children(id);
    for child in old_children {
        state.dom.remove(child);
    }

    // Merge fragment children
    if let Some(body_id) = body {
        for child_id in fragment_dom.children(body_id) {
            let new_child = state.dom.merge_subtree(&fragment_dom, child_id);
            state.dom.append_child(id, new_child);
        }
    }
    state.layout_engine.mark_dirty();
}

/// Clone a node. If deep=true, clone all descendants too.
#[op2(fast)]
#[smi]
pub fn op_dom_clone_node(state: &mut OpState, #[smi] node_id: i32, deep: bool) -> i32 {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    if deep {
        // merge_subtree does a deep copy from the same DOM
        let cloned = {
            // We need to read from &self and write to &mut self.
            // merge_subtree takes &Dom for source. Build a snapshot of the subtree.
            // Actually, we can use a two-pass: first collect the tree shape, then rebuild.
            clone_subtree_deep(&mut state.dom, id)
        };
        cloned.to_raw() as i32
    } else {
        // Shallow: copy just this node (no children)
        let node = match state.dom.get(id) {
            Some(n) => n,
            None => return -1,
        };
        let new_id = match &node.data {
            crate::dom::node::NodeData::Element(elem) => state
                .dom
                .create_element(elem.name.clone(), elem.attrs.clone()),
            crate::dom::node::NodeData::Text(t) => state.dom.create_text(t.clone()),
            crate::dom::node::NodeData::Comment(t) => state.dom.create_comment(t.clone()),
            _ => state.dom.create_document_fragment(),
        };
        new_id.to_raw() as i32
    }
}

/// Deep clone a subtree within the same Dom.
fn clone_subtree_deep(dom: &mut crate::dom::Dom, root: NodeId) -> NodeId {
    // Collect the tree structure first (read phase)
    let snapshot = collect_subtree(dom, root);
    // Rebuild from snapshot (write phase)
    rebuild_from_snapshot(dom, &snapshot)
}

#[derive(Debug)]
enum SnapshotNode {
    Element {
        name: crate::dom::node::QualName,
        attrs: Vec<crate::dom::node::Attribute>,
        children: Vec<SnapshotNode>,
    },
    Text(String),
    Comment(String),
    Fragment(Vec<SnapshotNode>),
}

fn collect_subtree(dom: &crate::dom::Dom, id: NodeId) -> SnapshotNode {
    let node = match dom.get(id) {
        Some(n) => n,
        None => return SnapshotNode::Fragment(vec![]),
    };
    let children: Vec<SnapshotNode> = dom
        .children(id)
        .iter()
        .map(|&child_id| collect_subtree(dom, child_id))
        .collect();
    match &node.data {
        crate::dom::node::NodeData::Element(elem) => SnapshotNode::Element {
            name: elem.name.clone(),
            attrs: elem.attrs.clone(),
            children,
        },
        crate::dom::node::NodeData::Text(t) => SnapshotNode::Text(t.clone()),
        crate::dom::node::NodeData::Comment(t) => SnapshotNode::Comment(t.clone()),
        _ => SnapshotNode::Fragment(children),
    }
}

fn rebuild_from_snapshot(dom: &mut crate::dom::Dom, snapshot: &SnapshotNode) -> NodeId {
    match snapshot {
        SnapshotNode::Element {
            name,
            attrs,
            children,
        } => {
            let id = dom.create_element(name.clone(), attrs.clone());
            for child in children {
                let child_id = rebuild_from_snapshot(dom, child);
                dom.append_child(id, child_id);
            }
            id
        }
        SnapshotNode::Text(t) => dom.create_text(t.clone()),
        SnapshotNode::Comment(t) => dom.create_comment(t.clone()),
        SnapshotNode::Fragment(children) => {
            let id = dom.create_document_fragment();
            for child in children {
                let child_id = rebuild_from_snapshot(dom, child);
                dom.append_child(id, child_id);
            }
            id
        }
    }
}

/// Insert HTML at a position relative to an element.
/// position: "beforebegin", "afterbegin", "beforeend", "afterend"
#[op2(fast)]
pub fn op_dom_insert_adjacent_html(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] position: &str,
    #[string] html: &str,
) {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    let fragment_dom = crate::html_parser::parse_html(&format!("<body>{}</body>", html));
    let frag_body = fragment_dom
        .get_elements_by_tag_name(NodeId::DOCUMENT, "body")
        .into_iter()
        .next();
    let frag_children: Vec<NodeId> = frag_body
        .map(|b| fragment_dom.children(b))
        .unwrap_or_default();
    if frag_children.is_empty() {
        return;
    }

    match position {
        "beforebegin" => {
            // Insert before this element (as previous sibling)
            if let Some(parent) = state.dom.get(id).and_then(|n| n.parent) {
                for &child_id in &frag_children {
                    let new_child = state.dom.merge_subtree(&fragment_dom, child_id);
                    state.dom.insert_before(parent, new_child, id);
                }
            }
        }
        "afterbegin" => {
            // Insert as first child
            let first = state.dom.get(id).and_then(|n| n.first_child);
            for child_id in frag_children.iter().rev() {
                let new_child = state.dom.merge_subtree(&fragment_dom, *child_id);
                if let Some(ref_child) = first {
                    state.dom.insert_before(id, new_child, ref_child);
                } else {
                    state.dom.append_child(id, new_child);
                }
            }
        }
        "beforeend" => {
            // Append as last child (same as appendChild)
            for &child_id in &frag_children {
                let new_child = state.dom.merge_subtree(&fragment_dom, child_id);
                state.dom.append_child(id, new_child);
            }
        }
        "afterend" => {
            // Insert after this element (as next sibling)
            if let Some(parent) = state.dom.get(id).and_then(|n| n.parent) {
                let next = state.dom.get(id).and_then(|n| n.next_sibling);
                for &child_id in &frag_children {
                    let new_child = state.dom.merge_subtree(&fragment_dom, child_id);
                    if let Some(ref_child) = next {
                        state.dom.insert_before(parent, new_child, ref_child);
                    } else {
                        state.dom.append_child(parent, new_child);
                    }
                }
            }
        }
        _ => {}
    }
    state.layout_engine.mark_dirty();
}

#[op2]
#[serde]
pub fn op_dom_document_write(state: &mut OpState, #[string] html: &str) -> Vec<i32> {
    let state = state.borrow_mut::<DomState>();
    let body_id = state
        .dom
        .get_elements_by_tag_name(NodeId::DOCUMENT, "body")
        .into_iter()
        .next();
    let body_id = match body_id {
        Some(id) => id,
        None => return vec![],
    };
    let fragment_dom = crate::html_parser::parse_html(&format!("<body>{}</body>", html));
    let frag_body = fragment_dom
        .get_elements_by_tag_name(NodeId::DOCUMENT, "body")
        .into_iter()
        .next();
    let mut new_ids = Vec::new();
    if let Some(frag_body_id) = frag_body {
        for child_id in fragment_dom.children(frag_body_id) {
            let new_child = state.dom.merge_subtree(&fragment_dom, child_id);
            state.dom.append_child(body_id, new_child);
            new_ids.push(new_child.to_raw() as i32);
        }
    }
    state.layout_engine.mark_dirty();
    new_ids
}

#[op2(fast)]
pub fn op_dom_class_list_add(state: &mut OpState, #[smi] node_id: i32, #[string] class: &str) {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    if let Some(node) = state.dom.get_mut(id) {
        if let Some(elem) = node.as_element_mut() {
            let current = elem
                .attrs
                .iter()
                .find(|a| a.name.local == "class")
                .map(|a| a.value.clone())
                .unwrap_or_default();
            if !current.split_whitespace().any(|c| c == class) {
                let new_val = if current.is_empty() {
                    class.to_string()
                } else {
                    format!("{} {}", current, class)
                };
                if let Some(attr) = elem.attrs.iter_mut().find(|a| a.name.local == "class") {
                    attr.value = new_val;
                } else {
                    elem.attrs.push(crate::dom::node::Attribute {
                        name: crate::dom::node::QualName::new("class"),
                        value: new_val,
                    });
                }
            }
        }
    }
}

#[op2(fast)]
pub fn op_dom_class_list_remove(state: &mut OpState, #[smi] node_id: i32, #[string] class: &str) {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    if let Some(node) = state.dom.get_mut(id) {
        if let Some(elem) = node.as_element_mut() {
            if let Some(attr) = elem.attrs.iter_mut().find(|a| a.name.local == "class") {
                let new_val: String = attr
                    .value
                    .split_whitespace()
                    .filter(|c| *c != class)
                    .collect::<Vec<_>>()
                    .join(" ");
                attr.value = new_val;
            }
        }
    }
}

/// Get computed style for an element.
/// Checks: 1) inline style attribute, 2) `<style>` block rules, 3) CSS defaults.
/// Uses selector matching for style block rules. Higher specificity wins.
#[op2]
#[serde]
// explicit_counter_loop: `source_order` is a manual CSS source-order
// counter used inside the nested selector-match loop; .enumerate()
// would force a usize↔u32 cast against the stored specificity tuple.
#[allow(
    clippy::explicit_counter_loop,
    reason = "explicit CSS source-order counter"
)]
pub fn op_dom_get_all_computed_styles(
    state: &mut OpState,
    #[smi] node_id: i32,
) -> HashMap<String, String> {
    let state = state.borrow_mut::<DomState>();
    if state.cached_rules.is_empty() && !state.stylesheets.is_empty() {
        state.update_cached_rules();
    }
    let id = NodeId::from_raw(node_id as u32);
    let dom_el = if let Some(el) = DomElement::new(&state.dom, id) {
        el
    } else {
        return HashMap::new();
    };

    let mut declarations: HashMap<String, (u32, u32, String)> = HashMap::new();
    let mut source_order: u32 = 0;

    for rule in &state.cached_rules {
        for sel in &rule.selectors {
            if crate::css_selectors::matches_selector(&dom_el, sel) {
                let s = crate::css_selectors::compute_specificity(sel);
                let spec = s.a * 10000 + s.b * 100 + s.c;
                for (name, val) in &rule.declarations {
                    let entry = declarations
                        .entry(name.clone())
                        .or_insert((0, 0, String::new()));
                    if spec > entry.0 || (spec == entry.0 && source_order >= entry.1) {
                        *entry = (spec, source_order, val.clone());
                    }
                }
            }
        }
        source_order += 1;
    }

    // Add inline styles (highest specificity)
    if let Some(el) = state.dom.get(id).and_then(|n| n.as_element()) {
        if let Some(style) = el
            .attrs
            .iter()
            .find(|a| a.name.local.eq_ignore_ascii_case("style"))
        {
            for decl in style.value.split(';') {
                if let Some(colon) = decl.find(':') {
                    let name = decl[..colon].trim().to_string();
                    let val = decl[colon + 1..].trim().to_string();
                    declarations.insert(name, (999999, 999999, val));
                }
            }
        }
    }

    // Resolve calc() and CSS Values 4 math functions to their used
    // pixel value before returning — Chrome's getComputedStyle does
    // this. Otherwise scripts that compute via calc(... sin(pi) ...)
    // and read the result back would see the unresolved expression
    // text instead of the resolved value real Chrome returns.
    let ctx = calc_context_from(state);
    let res: HashMap<String, String> = declarations
        .into_iter()
        .map(|(k, v)| (k, resolve_computed_value(&v.2, &ctx)))
        .collect();
    res
}

#[op2]
#[string]
pub fn op_dom_get_computed_style(
    state: &mut OpState,
    #[smi] node_id: i32,
    #[string] property: &str,
) -> String {
    let state = state.borrow_mut::<DomState>();
    if state.cached_rules.is_empty() && !state.stylesheets.is_empty() {
        state.update_cached_rules();
    }
    let id = NodeId::from_raw(node_id as u32);
    let ctx = calc_context_from(state);

    // 1. Check inline style (highest specificity)
    let inline_val = get_inline_style_value(&state.dom, id, property);
    if let Some(val) = &inline_val {
        if !val.is_empty() {
            return resolve_computed_value(val, &ctx);
        }
    }

    // 2. Check <style> block rules (matched by selector)
    if let Some(val) = get_stylesheet_value(state, id, property) {
        return resolve_computed_value(&val, &ctx);
    }

    // 3. CSS inheritance — walk up the DOM for inherited properties
    const INHERITED: &[&str] = &[
        "color",
        "font-family",
        "font-size",
        "font-style",
        "font-weight",
        "font-variant",
        "line-height",
        "letter-spacing",
        "word-spacing",
        "text-align",
        "text-indent",
        "text-transform",
        "white-space",
        "direction",
        "visibility",
        "cursor",
        "list-style-type",
        "list-style-position",
        "list-style-image",
        "list-style",
        "border-collapse",
        "border-spacing",
        "caption-side",
        "empty-cells",
        "quotes",
        "orphans",
        "widows",
        "text-decoration-color",
    ];

    if INHERITED.contains(&property) {
        let mut current = id;
        while let Some(parent_id) = state.dom.get(current).and_then(|n| n.parent) {
            if let Some(val) = get_inline_style_value(&state.dom, parent_id, property) {
                if !val.is_empty() {
                    return resolve_computed_value(&val, &ctx);
                }
            }
            if let Some(val) = get_stylesheet_value(state, parent_id, property) {
                return resolve_computed_value(&val, &ctx);
            }
            current = parent_id;
        }
    }

    // 4. CSS default
    crate::js_runtime::extensions::layout_ext::css_default(property)
}

/// Extract a property value from an element's inline style attribute.
fn get_inline_style_value(dom: &crate::dom::Dom, id: NodeId, property: &str) -> Option<String> {
    let style_attr = dom.get(id).and_then(|n| n.as_element()).and_then(|e| {
        e.attrs
            .iter()
            .find(|a| a.name.local.eq_ignore_ascii_case("style"))
            .map(|a| a.value.clone())
    })?;

    for decl in style_attr.split(';') {
        let decl = decl.trim();
        if decl.is_empty() {
            continue;
        }
        if let Some(colon) = decl.find(':') {
            let prop = decl[..colon].trim();
            let val = decl[colon + 1..].trim();
            if prop.eq_ignore_ascii_case(property) {
                return Some(val.to_string());
            }
        }
    }
    None
}

/// Search <style> block rules for a matching declaration.
/// Returns the value from the highest-specificity matching rule.
#[allow(clippy::explicit_counter_loop, reason = "CSS source-order counter")]
fn get_stylesheet_value(state: &DomState, id: NodeId, property: &str) -> Option<String> {
    let dom_el = DomElement::new(&state.dom, id)?;

    // Collect all matching declarations: (specificity, source_order, value)
    let mut matches: Vec<(u32, u32, String)> = Vec::new();
    let mut source_order: u32 = 0;

    for rule in &state.cached_rules {
        let mut matched = false;
        let mut best_spec: u32 = 0;
        for sel in &rule.selectors {
            if crate::css_selectors::matches_selector(&dom_el, sel) {
                matched = true;
                let s = crate::css_selectors::compute_specificity(sel);
                let spec = s.a * 10000 + s.b * 100 + s.c;
                if spec > best_spec {
                    best_spec = spec;
                }
            }
        }

        if matched {
            if let Some(val) = rule.declarations.get(property) {
                matches.push((best_spec, source_order, val.clone()));
            }
        }
        source_order += 1;
    }

    if matches.is_empty() {
        return None;
    }

    // Sort by specificity (ascending), then source order — last wins
    matches.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));

    // Winner is the last entry (highest specificity, latest source order)
    matches.last().map(|(_, _, val)| val.clone())
}

// --- Shadow DOM ops ---

/// Attach a shadow root to an element. Returns the shadow root node ID.
#[op2(fast)]
#[smi]
pub fn op_dom_attach_shadow(state: &mut OpState, #[smi] node_id: i32, #[string] mode: &str) -> i32 {
    let state = state.borrow_mut::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    let shadow_mode = match mode {
        "closed" => crate::dom::node::ShadowRootMode::Closed,
        _ => crate::dom::node::ShadowRootMode::Open,
    };
    let shadow_id = state.dom.create_shadow_root(id, shadow_mode);
    shadow_id.to_raw() as i32
}

/// Get shadow root of an element (-1 if none).
#[op2(fast)]
#[smi]
pub fn op_dom_get_shadow_root(state: &mut OpState, #[smi] node_id: i32) -> i32 {
    let state = state.borrow::<DomState>();
    let id = NodeId::from_raw(node_id as u32);
    state
        .dom
        .get(id)
        .and_then(|n| n.as_element())
        .and_then(|e| e.shadow_root)
        .map(|sr| sr.to_raw() as i32)
        .unwrap_or(-1)
}

// --- CSSOM ops ---

#[op2(fast)]
pub fn op_dom_get_stylesheet_count(state: &mut OpState) -> i32 {
    let state = state.borrow::<DomState>();
    state.stylesheets.len() as i32
}

#[derive(serde::Serialize)]
pub struct CSSRuleJson {
    pub selector_text: String,
    pub css_text: String,
    pub rule_type: u8,
}

/// Get parsed rules for a stylesheet by index.
#[op2]
#[serde]
pub fn op_dom_get_stylesheet_rules(state: &mut OpState, #[smi] index: i32) -> Vec<CSSRuleJson> {
    let state = state.borrow::<DomState>();
    let idx = index as usize;
    if idx >= state.stylesheets.len() {
        return vec![];
    }
    let (stylesheet, _errors) = crate::css_parser::parse_stylesheet(&state.stylesheets[idx]);
    let mut rules = Vec::new();
    for rule in &stylesheet.rules {
        if let crate::css_parser::ast::Rule::Qualified(qr) = rule {
            let selector_text = tokens_to_string(&qr.prelude);
            if selector_text.is_empty() {
                continue;
            }
            let decl_parts: Vec<String> = qr
                .declarations
                .iter()
                .map(|d| {
                    let val = tokens_to_string(&d.value).trim().to_string();
                    if d.important {
                        format!("{}: {} !important", d.name, val)
                    } else {
                        format!("{}: {}", d.name, val)
                    }
                })
                .collect();
            let css_text = format!("{} {{ {} }}", selector_text, decl_parts.join("; "));
            rules.push(CSSRuleJson {
                selector_text: selector_text.trim().to_string(),
                css_text,
                rule_type: 1, // CSSStyleRule
            });
        }
    }
    rules
}

#[op2]
#[string]
pub fn op_dom_get_base_url(state: &mut OpState) -> String {
    let state = state.borrow::<DomState>();
    state
        .base_url
        .as_ref()
        .map(|u| u.to_string())
        .unwrap_or_else(|| "about:blank".to_string())
}

#[op2]
#[string]
pub fn op_dom_storage_get(
    state: &mut OpState,
    #[string] area: String,
    #[string] key: String,
) -> Option<String> {
    let state = state.borrow::<DomState>();
    state.storage.get(&area).and_then(|m| m.get(&key)).cloned()
}

#[op2(fast)]
pub fn op_dom_storage_set(
    state: &mut OpState,
    #[string] area: String,
    #[string] key: String,
    #[string] value: String,
) {
    let state = state.borrow_mut::<DomState>();
    if let Some(m) = state.storage.get_mut(&area) {
        m.insert(key, value);
    }
}

#[op2(fast)]
pub fn op_dom_storage_remove(state: &mut OpState, #[string] area: String, #[string] key: String) {
    let state = state.borrow_mut::<DomState>();
    if let Some(m) = state.storage.get_mut(&area) {
        m.remove(&key);
    }
}

#[op2(fast)]
pub fn op_dom_storage_clear(state: &mut OpState, #[string] area: String) {
    let state = state.borrow_mut::<DomState>();
    if let Some(m) = state.storage.get_mut(&area) {
        m.clear();
    }
}

#[op2]
#[serde]
pub fn op_dom_storage_keys(state: &mut OpState, #[string] area: String) -> Vec<String> {
    let state = state.borrow::<DomState>();
    state
        .storage
        .get(&area)
        .map(|m| m.keys().cloned().collect())
        .unwrap_or_default()
}

// ──────────────────────────────────────────────────────────────────
// Child-realm support
// ──────────────────────────────────────────────────────────────────

/// Window constructor callback — throws per the spec ("Illegal constructor").
/// Used only to create a real, named `Window` function whose `.name === "Window"`
/// and whose `.prototype.constructor === Window`. In practice nothing calls
/// `new Window()`, so the throw body is never reached; we keep it for spec correctness.
fn _window_ctor_cb(
    scope: &mut v8::PinScope,
    _args: v8::FunctionCallbackArguments,
    mut _rv: v8::ReturnValue,
) {
    if let Some(msg) = v8::String::new(scope, "Illegal constructor") {
        let e = v8::Exception::type_error(scope, msg);
        scope.throw_exception(e);
    }
}

/// Create (or return cached) a genuine `v8::Context` child realm for an iframe's
/// `contentWindow`.  Returns the child global as a live JS object — NOT a Proxy.
///
/// The child context gets:
/// - Real, realm-distinct native intrinsics (`Object`/`Function`/`Array`/… ≠ parent's)
///   — matching real Chrome, where contentWindow is a genuine realm, not a Proxy
///   or a parent alias.
/// - `[[Prototype]] === Window.prototype` → `cw.constructor.name === "Window"`.
/// - Genuine-native `Function.prototype.toString` (same API-fn recipe as the main window).
/// - Standard self-referential globals (`window`, `self`, `globalThis`, `frames`).
///
/// JS completes the setup by setting `document`, `location`, `navigator`, `fetch`,
/// `devicePixelRatio` (accessor), etc. on the returned object.
#[op2]
pub fn op_create_child_realm<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    #[smi] realm_id: i32,
) -> v8::Local<'s, v8::Value> {
    let rid = realm_id as u32;

    // Access OpState via the isolate-level state (public, stable in 0.311).
    // op_state_from takes &Isolate; HandleScope auto-derefs there.
    let op_state_rc = JsRuntime::op_state_from(scope);

    // Fast path: cached realm — return the previously-created global.
    {
        let op_state = op_state_rc.borrow();
        if let Some(store) = op_state.try_borrow::<IframeRealmStore>() {
            if let Some(global) = store.globals.get(&rid) {
                return v8::Local::new(scope, global).into();
            }
        }
    }

    // Clone the `orig_fp_tostring` and `native_tag_sym` Globals into new
    // handles BEFORE entering the child ContextScope (requires parent scope).
    let orig_fpt: Option<v8::Global<v8::Function>>;
    let native_tag_sym: Option<v8::Global<v8::Symbol>>;
    {
        let op_state = op_state_rc.borrow();
        if let Some(store) = op_state.try_borrow::<IframeRealmStore>() {
            orig_fpt = store.orig_fp_tostring.as_ref().map(|g| {
                let local = v8::Local::new(scope, g);
                v8::Global::new(scope, local)
            });
            native_tag_sym = store.native_tag_sym.as_ref().map(|g| {
                let local = v8::Local::new(scope, g);
                v8::Global::new(scope, local)
            });
        } else {
            orig_fpt = None;
            native_tag_sym = None;
        }
    }

    // Create the child context (vanilla v8::Context — full native intrinsics).
    let child_ctx = v8::Context::new(scope, v8::ContextOptions::default());

    // Copy parent's security token to child so V8 treats the contexts as
    // same-origin (about:blank inherits the parent origin in Chrome).
    // Without this, accessing child-realm objects from the parent scope
    // throws "TypeError: no access" via V8's cross-context security check.
    let parent_ctx = scope.get_current_context();
    let parent_tok = parent_ctx.get_security_token(scope);
    child_ctx.set_security_token(parent_tok);

    // Set up the child context.  Returns None on any fatal V8 allocation
    // failure (extremely rare); the outer code falls back to undefined.
    let child_global_g: Option<v8::Global<v8::Object>> = {
        let cs = &mut v8::ContextScope::new(scope, child_ctx);

        // Build a real `Window` function (FunctionTemplate → native `[native code]`)
        // so the child global is typed: `constructor.name === "Window"`.
        let window_tmpl = v8::FunctionTemplate::new(cs, _window_ctor_cb);
        if let Some(n) = v8::String::new(cs, "Window") {
            window_tmpl.set_class_name(n);
        }
        let window_fn = match window_tmpl.get_function(cs) {
            Some(f) => f,
            None => return v8::undefined(cs).into(),
        };
        if let Some(n) = v8::String::new(cs, "Window") {
            window_fn.set_name(n);
        }

        // child_global.[[Prototype]] = Window.prototype
        // → child_global.constructor.name === "Window"
        if let Some(pk) = v8::String::new(cs, "prototype") {
            if let Some(proto_val) = window_fn.get(cs, pk.into()) {
                let child_global = child_ctx.global(cs);
                child_global.set_prototype(cs, proto_val);
            }
        }

        let child_global = child_ctx.global(cs);

        // Expose Window on child global (scripts may read `contentWindow.Window`).
        if let Some(k) = v8::String::new(cs, "Window") {
            child_global.set(cs, k.into(), window_fn.into());
        }

        // Standard self-referential globals (all point to child_global).
        for key in &["window", "self", "globalThis", "frames"] {
            if let Some(k) = v8::String::new(cs, key) {
                child_global.set(cs, k.into(), child_global.into());
            }
        }
        // length = 0  (avoid borrow-twice by staging the value first)
        if let Some(k) = v8::String::new(cs, "length") {
            let zero = v8::Integer::new(cs, 0);
            child_global.set(cs, k.into(), zero.into());
        }
        // opener = null
        if let Some(k) = v8::String::new(cs, "opener") {
            let null = v8::null(cs);
            child_global.set(cs, k.into(), null.into());
        }

        // Install genuine-native Function.prototype.toString in child realm.
        // Closes the [[SourceText]] leak for child-realm functions too.
        // Pass native_tag_sym (JS global registry) so tagged host fns
        // in the child realm stringify correctly via the Array-data path.
        if let Some(ref orig) = orig_fpt {
            install_native_fp_tostring(cs, orig, native_tag_sym.as_ref());
        }

        Some(v8::Global::new(cs, child_global))
    };

    let child_global_g = match child_global_g {
        Some(g) => g,
        None => return v8::undefined(scope).into(),
    };

    // Build Local from Global BEFORE moving Global into the store.
    let local: v8::Local<'s, v8::Value> = v8::Local::new(scope, &child_global_g).into();

    // Persist context (keeps it alive) and cache global in OpState.
    {
        let mut op_state = op_state_rc.borrow_mut();
        if let Some(store) = op_state.try_borrow_mut::<IframeRealmStore>() {
            store
                .contexts
                .insert(rid, v8::Global::new(scope, child_ctx));
            store.globals.insert(rid, child_global_g);
        }
    }

    local
}

/// Set a property on the INNER GLOBAL of a child realm.
///
/// The global proxy's own property dict is NOT visible to code running inside
/// the child realm (which reads from the inner global's scope chain). Setting
/// on the proxy via `proxy.set()` from Rust only writes to the proxy's own
/// Two-path write to guarantee visibility from both inside and outside the realm:
///
/// 1. `create_data_property` on the inner global (the JSGlobalObject behind the
///    GlobalProxy): makes the property an own property of the inner global, so
///    scope-chain lookups from scripts running INSIDE the realm find it.
///
/// 2. `proxy.set()` on the GlobalProxy: puts the property in the proxy's own
///    dictionary, so cross-context reads from the parent (`cw.screen`) find it.
///
/// Both paths are necessary: V8's API `Object::Set()` on a GlobalProxy writes to
/// the proxy's own dict (not the inner global), so scope-chain lookups inside the
/// realm miss it. Conversely, `create_data_property` on the inner global is NOT
/// reachable from a cross-context `proxy.property` read (the proxy's own dict is
/// checked first and exclusively for cross-context callers without the interceptor).
#[op2]
pub fn op_set_child_realm_prop<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    #[smi] realm_id: i32,
    key: v8::Local<v8::Value>,
    value: v8::Local<v8::Value>,
) -> v8::Local<'s, v8::Value> {
    let rid = realm_id as u32;
    let op_state_rc = JsRuntime::op_state_from(scope);

    let child_ctx_g: Option<v8::Global<v8::Context>> = {
        let op_state = op_state_rc.borrow();
        op_state.try_borrow::<IframeRealmStore>().and_then(|store| {
            store.contexts.get(&rid).map(|g| {
                let local = v8::Local::new(scope, g);
                v8::Global::new(scope, local)
            })
        })
    };
    let child_ctx_g = match child_ctx_g {
        Some(g) => g,
        None => return v8::undefined(scope).into(),
    };

    let child_ctx = v8::Local::new(scope, &child_ctx_g);
    let cs = &mut v8::ContextScope::new(scope, child_ctx);
    let child_proxy = child_ctx.global(cs);

    // Path 1: inner global own property (inside-realm scope chain visibility).
    if let Some(inner) = child_proxy
        .get_prototype(cs)
        .and_then(|p| v8::Local::<v8::Object>::try_from(p).ok())
    {
        if let Ok(k) = v8::Local::<v8::Name>::try_from(key) {
            inner.create_data_property(cs, k, value);
        }
    }

    // Path 2: proxy own property (cross-context parent-side visibility).
    child_proxy.set(cs, key, value);

    v8::undefined(cs).into()
}

/// Execute a JavaScript string inside a child realm's context.
///
/// Compiles and runs `code` in the child context scope. Returns the result
/// (coerced to string) or `undefined` on compile/runtime error. Used for
/// cases where `op_set_child_realm_prop` cannot express the required
/// descriptor shape (e.g. accessor properties with a getter function).
#[op2]
#[string]
pub fn op_eval_in_child_realm<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    #[smi] realm_id: i32,
    #[string] code: String,
) -> Option<String> {
    let rid = realm_id as u32;
    let op_state_rc = JsRuntime::op_state_from(scope);

    let child_ctx_g: Option<v8::Global<v8::Context>> = {
        let op_state = op_state_rc.borrow();
        op_state.try_borrow::<IframeRealmStore>().and_then(|store| {
            store.contexts.get(&rid).map(|g| {
                let local = v8::Local::new(scope, g);
                v8::Global::new(scope, local)
            })
        })
    };
    let child_ctx_g = child_ctx_g?;

    let child_ctx = v8::Local::new(scope, &child_ctx_g);
    let cs = &mut v8::ContextScope::new(scope, child_ctx);

    let src = v8::String::new(cs, &code)?;
    // A swallowed compile/runtime error here means the child realm is
    // silently under-populated (a missing shim can make site scripts
    // bail or hit an undefined receiver). Surface it to an opt-in
    // diagnostic channel
    // (`BROWSER_OXIDE_DEBUG_CHILD_REALM`) WITHOUT changing behavior: still
    // best-effort runs the script, still returns `None`.
    v8::tc_scope!(let tc, cs);
    let ok = match v8::Script::compile(tc, src, None) {
        Some(script) => script.run(tc).is_some(),
        None => false,
    };
    if !ok && std::env::var("BROWSER_OXIDE_DEBUG_CHILD_REALM").is_ok() {
        let msg = tc
            .exception()
            .and_then(|e| e.to_string(tc))
            .map(|s| s.to_rust_string_lossy(tc))
            .unwrap_or_else(|| "<no exception object>".to_string());
        let snippet: String = code.chars().take(160).collect();
        eprintln!("[child-realm:{rid}] eval error: {msg} | code[..160]={snippet:?}");
    }
    None
}

deno_core::extension!(
    dom_extension,
    ops = [
        op_dom_document_node,
        op_dom_get_tag_name,
        op_dom_get_node_type,
        op_dom_get_text_content,
        op_dom_get_inner_html,
        op_dom_get_outer_html,
        op_dom_get_attribute,
        op_dom_has_attribute,
        op_dom_get_attribute_names,
        op_dom_get_parent,
        op_dom_get_children,
        op_dom_get_children_with_types,
        op_dom_get_child_elements,
        op_dom_get_child_elements_with_types,
        op_dom_get_first_child,
        op_dom_get_last_child,
        op_dom_get_next_sibling,
        op_dom_get_prev_sibling,
        op_dom_query_selector,
        op_dom_query_selector_all,
        op_dom_get_element_by_id,
        op_dom_get_elements_by_tag_name,
        op_dom_get_elements_by_class_name,
        op_dom_create_element,
        op_dom_create_text_node,
        op_dom_create_document_fragment,
        op_dom_append_child,
        op_dom_insert_before,
        op_dom_remove_child,
        op_dom_set_attribute,
        op_dom_remove_attribute,
        op_dom_set_text_content,
        op_dom_set_inner_html,
        op_dom_document_write,
        op_dom_clone_node,
        op_dom_insert_adjacent_html,
        op_dom_class_list_add,
        op_dom_class_list_remove,
        op_dom_get_computed_style,
        op_dom_get_all_computed_styles,
        op_dom_get_stylesheet_count,
        op_dom_get_stylesheet_rules,
        op_dom_attach_shadow,
        op_dom_get_shadow_root,
        op_dom_get_base_url,
        op_dom_storage_get,
        op_dom_storage_set,
        op_dom_storage_remove,
        op_dom_storage_clear,
        op_dom_storage_keys,
        op_create_child_realm,
        op_set_child_realm_prop,
        op_eval_in_child_realm,
    ],
);