euv-core 0.48.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Computes a deterministic 64-bit FNV-1a checksum over raw `.wasm` binary bytes.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.wasm` binary slice.
///
/// # Returns
///
/// - `u64` - Deterministic non-zero digest.
#[must_use]
#[inline]
pub fn compute_wasm_checksum(bytes: &[u8]) -> u64 {
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0100_0000_01b3;
    let mut hash: u64 = FNV_OFFSET;
    let mut slice: &[u8] = bytes;
    while let Some((chunk, rest)) = slice.split_first_chunk::<8>() {
        hash = (hash ^ (chunk[0] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[1] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[2] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[3] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[4] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[5] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[6] as u64)).wrapping_mul(FNV_PRIME);
        hash = (hash ^ (chunk[7] as u64)).wrapping_mul(FNV_PRIME);
        slice = rest;
    }
    for byte in slice.iter().copied() {
        hash = (hash ^ (byte as u64)).wrapping_mul(FNV_PRIME);
    }
    hash.max(1)
}

/// Computes a deterministic keyed integrity signature tag for a `.wasm` binary and release version.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.wasm` binary bytes.
/// - `u64` - Release version number.
/// - `&str` - Shared verification key or signing secret.
///
/// # Returns
///
/// - `String` - Formatted signature tag (`"euv-sig-v1:<hex>"`).
#[must_use]
pub fn compute_wasm_signature(bytes: &[u8], version: u64, signing_key: &str) -> String {
    const FNV_PRIME: u64 = 0x0100_0000_01b3;
    const SIG_MIX: u64 = 0x517c_c1b7_2722_0a95;
    let mut h1: u64 = 0xcbf2_9ce4_8422_2325 ^ version.wrapping_mul(0x9E37_79B9_7F4A_7C15);
    let mut h2: u64 = 0x8422_2325_cbf2_9ce4 ^ (bytes.len() as u64);
    for byte in signing_key.as_bytes().iter().copied() {
        let b: u64 = byte as u64;
        h1 = (h1 ^ b).wrapping_mul(FNV_PRIME);
        h2 = h2.rotate_left(7) ^ b;
    }
    let mut slice: &[u8] = bytes;
    while let Some((chunk, rest)) = slice.split_first_chunk::<4>() {
        let b0: u64 = chunk[0] as u64;
        h1 = (h1 ^ b0).wrapping_mul(FNV_PRIME);
        h2 = (h2 ^ b0.wrapping_mul(SIG_MIX)).rotate_left(13);
        let b1: u64 = chunk[1] as u64;
        h1 = (h1 ^ b1).wrapping_mul(FNV_PRIME);
        h2 = (h2 ^ b1.wrapping_mul(SIG_MIX)).rotate_left(13);
        let b2: u64 = chunk[2] as u64;
        h1 = (h1 ^ b2).wrapping_mul(FNV_PRIME);
        h2 = (h2 ^ b2.wrapping_mul(SIG_MIX)).rotate_left(13);
        let b3: u64 = chunk[3] as u64;
        h1 = (h1 ^ b3).wrapping_mul(FNV_PRIME);
        h2 = (h2 ^ b3.wrapping_mul(SIG_MIX)).rotate_left(13);
        slice = rest;
    }
    for byte in slice.iter().copied() {
        let b: u64 = byte as u64;
        h1 = (h1 ^ b).wrapping_mul(FNV_PRIME);
        h2 = (h2 ^ b.wrapping_mul(SIG_MIX)).rotate_left(13);
    }
    format!("{WASM_SIGNATURE_PREFIX}{h1:016x}{h2:016x}")
}

/// Encodes an unsigned 32-bit integer as LEB128 into `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination byte vector.
/// - `u32` - Unsigned integer to encode.
pub(crate) fn write_uleb128(out: &mut Vec<u8>, mut value: u32) {
    loop {
        let mut byte: u8 = (value & 0x7F) as u8;
        value >>= 7;
        if value != 0 {
            byte |= 0x80;
        }
        out.push(byte);
        if value == 0 {
            break;
        }
    }
}

/// Encodes a signed 32-bit integer as SLEB128 into `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination byte vector.
/// - `i32` - Signed integer to encode.
pub(crate) fn write_sleb128(out: &mut Vec<u8>, mut value: i32) {
    loop {
        let byte: u8 = (value & 0x7F) as u8;
        value >>= 7;
        let done: bool = (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0);
        if done {
            out.push(byte);
            break;
        }
        out.push(byte | 0x80);
    }
}

/// Decodes an unsigned 32-bit LEB128 integer starting at `*cursor` in `bytes`.
///
/// # Arguments
///
/// - `&[u8]` - Source WASM byte slice.
/// - `&mut usize` - Read cursor advanced past the encoded integer.
///
/// # Returns
///
/// - `Result<u32, WasmDynamicError>` - Decoded integer or `InvalidWasmBinary`.
pub(crate) fn read_uleb128(bytes: &[u8], cursor: &mut usize) -> Result<u32, WasmDynamicError> {
    let mut result: u32 = 0;
    let mut shift: u32 = 0;
    loop {
        let byte: u8 = *bytes.get(*cursor).ok_or_else(|| {
            WasmDynamicError::InvalidWasmBinary("unexpected EOF in uleb128".to_string())
        })?;
        *cursor += 1;
        if shift >= 35 {
            return Err(WasmDynamicError::InvalidWasmBinary(
                "uleb128 integer overflow".to_string(),
            ));
        }
        result |= ((byte & 0x7F) as u32).wrapping_shl(shift);
        if (byte & 0x80) == 0 {
            return Ok(result);
        }
        shift += 7;
    }
}

/// Decodes a signed 32-bit SLEB128 integer starting at `*cursor` in `bytes`.
///
/// # Arguments
///
/// - `&[u8]` - Source WASM byte slice.
/// - `&mut usize` - Read cursor advanced past the encoded integer.
///
/// # Returns
///
/// - `Result<i32, WasmDynamicError>` - Decoded signed integer or `InvalidWasmBinary`.
pub(crate) fn read_sleb128(bytes: &[u8], cursor: &mut usize) -> Result<i32, WasmDynamicError> {
    let mut result: i32 = 0;
    let mut shift: u32 = 0;
    loop {
        let byte: u8 = *bytes.get(*cursor).ok_or_else(|| {
            WasmDynamicError::InvalidWasmBinary("unexpected EOF in sleb128".to_string())
        })?;
        *cursor += 1;
        if shift >= 35 {
            return Err(WasmDynamicError::InvalidWasmBinary(
                "sleb128 integer overflow".to_string(),
            ));
        }
        result |= ((byte & 0x7F) as i32).wrapping_shl(shift);
        shift += 7;
        if (byte & 0x80) == 0 {
            if shift < 32 && (byte & 0x40) != 0 {
                result |= !0_i32 << shift;
            }
            return Ok(result);
        }
    }
}

/// Reads a length-prefixed UTF-8 WebAssembly name string from `bytes`.
///
/// # Arguments
///
/// - `&[u8]` - Source WASM byte slice.
/// - `&mut usize` - Read cursor advanced past the string.
///
/// # Returns
///
/// - `Result<String, WasmDynamicError>` - Decoded UTF-8 identifier or `InvalidWasmBinary`.
fn read_wasm_name(bytes: &[u8], cursor: &mut usize) -> Result<String, WasmDynamicError> {
    let len: usize = read_uleb128(bytes, cursor)? as usize;
    let end: usize = cursor.saturating_add(len);
    let slice: &[u8] = bytes
        .get(*cursor..end)
        .ok_or_else(|| WasmDynamicError::InvalidWasmBinary("truncated wasm name".to_string()))?;
    *cursor = end;
    from_utf8(slice)
        .map(str::to_string)
        .map_err(|_| WasmDynamicError::InvalidWasmBinary("non-UTF8 wasm name".to_string()))
}

/// Parses and validates a standard WebAssembly binary (`.wasm`) into a `WasmParsedModule`.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.wasm` binary bytes.
/// - `&WasmSandboxConfig` - Sandbox memory and binary limits enforced during validation.
///
/// # Returns
///
/// - `Result<WasmParsedModule, WasmDynamicError>` - Validated executable module or typed error.
pub fn parse_wasm_binary(
    bytes: &[u8],
    config: &WasmSandboxConfig,
) -> Result<WasmParsedModule, WasmDynamicError> {
    if bytes.len() > config.get_max_binary_bytes() {
        return Err(WasmDynamicError::BinaryTooLarge {
            actual: bytes.len(),
            limit: config.get_max_binary_bytes(),
        });
    }
    if bytes.len() < 8 || &bytes[0..4] != WASM_BINARY_MAGIC || &bytes[4..8] != WASM_BINARY_VERSION {
        return Err(WasmDynamicError::InvalidWasmBinary(
            "missing \\0asm v1 header".to_string(),
        ));
    }
    let mut module: WasmParsedModule = WasmParsedModule::default();
    let mut func_type_indices: Vec<u32> = Vec::new();
    let mut cursor: usize = 8;
    while cursor < bytes.len() {
        let sec_id: u8 = bytes[cursor];
        cursor += 1;
        let sec_len: usize = read_uleb128(bytes, &mut cursor)? as usize;
        let sec_end: usize = cursor.saturating_add(sec_len);
        if sec_end > bytes.len() {
            return Err(WasmDynamicError::InvalidWasmBinary(
                "truncated section payload".to_string(),
            ));
        }
        let sec_slice: &[u8] = &bytes[cursor..sec_end];
        cursor = sec_end;
        let mut sc: usize = 0;
        match sec_id {
            WASM_SEC_CUSTOM => {
                let sec_name: String = read_wasm_name(sec_slice, &mut sc)?;
                let payload: Vec<u8> = sec_slice[sc..].to_vec();
                let _: Option<Vec<u8>> = module.get_mut_custom_sections().insert(sec_name, payload);
            }
            WASM_SEC_TYPE => {
                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
                for _ in 0..count {
                    let tag: u8 = *sec_slice.get(sc).ok_or_else(|| {
                        WasmDynamicError::InvalidWasmBinary("truncated type entry".to_string())
                    })?;
                    sc += 1;
                    if tag != WASM_FUNCTYPE_TAG {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "unsupported wasm type tag".to_string(),
                        ));
                    }
                    let params: usize = read_uleb128(sec_slice, &mut sc)? as usize;
                    sc = sc.saturating_add(params);
                    let results: usize = read_uleb128(sec_slice, &mut sc)? as usize;
                    sc = sc.saturating_add(results);
                    if sc > sec_slice.len() {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "truncated type signature".to_string(),
                        ));
                    }
                    module
                        .get_mut_types()
                        .push(WasmFuncSignature::new(params, results));
                }
            }
            WASM_SEC_IMPORT => {
                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
                for _ in 0..count {
                    let mod_name: String = read_wasm_name(sec_slice, &mut sc)?;
                    let field_name: String = read_wasm_name(sec_slice, &mut sc)?;
                    let kind: u8 = *sec_slice.get(sc).ok_or_else(|| {
                        WasmDynamicError::InvalidWasmBinary("truncated import kind".to_string())
                    })?;
                    sc += 1;
                    if kind == 0x00 {
                        let type_idx: u32 = read_uleb128(sec_slice, &mut sc)?;
                        module
                            .get_mut_imports()
                            .push(WasmImportEntry::new(mod_name, field_name, type_idx));
                    } else {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "unsupported non-function import kind".to_string(),
                        ));
                    }
                }
            }
            WASM_SEC_FUNCTION => {
                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
                for _ in 0..count {
                    func_type_indices.push(read_uleb128(sec_slice, &mut sc)?);
                }
            }
            WASM_SEC_MEMORY => {
                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
                if count > 0 {
                    let flags: u8 = *sec_slice.get(sc).ok_or_else(|| {
                        WasmDynamicError::InvalidWasmBinary("truncated memory limits".to_string())
                    })?;
                    sc += 1;
                    let min_pages: u32 = read_uleb128(sec_slice, &mut sc)?;
                    if (flags & 0x01) != 0 {
                        let _: u32 = read_uleb128(sec_slice, &mut sc)?;
                    }
                    let req_bytes: usize = (min_pages as usize).saturating_mul(WASM_PAGE_BYTES);
                    if req_bytes > config.get_max_memory_bytes() {
                        return Err(WasmDynamicError::MemoryLimitExceeded {
                            requested: req_bytes,
                            limit: config.get_max_memory_bytes(),
                        });
                    }
                    module.set_memory_min_pages(min_pages.max(1));
                }
            }
            WASM_SEC_EXPORT => {
                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
                for _ in 0..count {
                    let exp_name: String = read_wasm_name(sec_slice, &mut sc)?;
                    let kind: u8 = *sec_slice.get(sc).ok_or_else(|| {
                        WasmDynamicError::InvalidWasmBinary("truncated export kind".to_string())
                    })?;
                    sc += 1;
                    let idx: u32 = read_uleb128(sec_slice, &mut sc)?;
                    if kind == 0x00 {
                        let _: Option<u32> = module.get_mut_exports().insert(exp_name, idx);
                    }
                }
            }
            WASM_SEC_CODE => {
                let count: usize = read_uleb128(sec_slice, &mut sc)? as usize;
                if count != func_type_indices.len() {
                    return Err(WasmDynamicError::InvalidWasmBinary(
                        "function/code count mismatch".to_string(),
                    ));
                }
                for type_idx in func_type_indices.iter().copied() {
                    let body_len: usize = read_uleb128(sec_slice, &mut sc)? as usize;
                    let body_end: usize = sc.saturating_add(body_len);
                    if body_end > sec_slice.len() {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "truncated code body".to_string(),
                        ));
                    }
                    let local_decl_groups: u32 = read_uleb128(sec_slice, &mut sc)?;
                    let mut extra_locals: usize = 0;
                    for _ in 0..local_decl_groups {
                        let lcount: usize = read_uleb128(sec_slice, &mut sc)? as usize;
                        sc = sc.saturating_add(1);
                        extra_locals = extra_locals.saturating_add(lcount);
                    }
                    if sc > body_end {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "invalid local declarations".to_string(),
                        ));
                    }
                    let code: Vec<u8> = sec_slice[sc..body_end].to_vec();
                    let is_pure_no_mem: bool = wasm_body_is_pure_no_memory(code.as_slice());
                    sc = body_end;
                    let mut parsed_fn: WasmParsedFunction =
                        WasmParsedFunction::new(type_idx, extra_locals, code);
                    parsed_fn.set_pure_no_memory(is_pure_no_mem);
                    module.get_mut_functions().push(parsed_fn);
                }
            }
            WASM_SEC_DATA => {
                let count: u32 = read_uleb128(sec_slice, &mut sc)?;
                for _ in 0..count {
                    let flags: u32 = read_uleb128(sec_slice, &mut sc)?;
                    if flags != 0 {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "unsupported passive data segment".to_string(),
                        ));
                    }
                    let op: u8 = *sec_slice.get(sc).ok_or_else(|| {
                        WasmDynamicError::InvalidWasmBinary("truncated data offset".to_string())
                    })?;
                    sc += 1;
                    if op != OP_I32_CONST {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "expected i32.const in data offset".to_string(),
                        ));
                    }
                    let offset: u32 = read_sleb128(sec_slice, &mut sc)?.max(0) as u32;
                    let end_op: u8 = *sec_slice.get(sc).ok_or_else(|| {
                        WasmDynamicError::InvalidWasmBinary(
                            "missing end in data offset".to_string(),
                        )
                    })?;
                    sc += 1;
                    if end_op != OP_END {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "malformed data offset expr".to_string(),
                        ));
                    }
                    let data_len: usize = read_uleb128(sec_slice, &mut sc)? as usize;
                    let data_end: usize = sc.saturating_add(data_len);
                    if data_end > sec_slice.len() {
                        return Err(WasmDynamicError::InvalidWasmBinary(
                            "truncated data segment bytes".to_string(),
                        ));
                    }
                    let seg_bytes: Vec<u8> = sec_slice[sc..data_end].to_vec();
                    sc = data_end;
                    module
                        .get_mut_data_segments()
                        .push(WasmDataSegment::new(offset, seg_bytes));
                }
            }
            _ => {}
        }
    }
    if module.get_memory_min_pages() == 0 {
        module.set_memory_min_pages(1);
    }
    Ok(module)
}

/// Reads a bounded UTF-8 slice from WASM linear memory, returning `MemoryOutOfBounds` on invalid ranges.
///
/// # Arguments
///
/// - `&[u8]` - Active linear memory buffer.
/// - `u32` - Start pointer offset.
/// - `u32` - Byte length to read.
///
/// # Returns
///
/// - `Result<&str, WasmDynamicError>` - Validated UTF-8 slice or memory error.
fn read_memory_str(memory: &[u8], ptr: u32, len: u32) -> Result<&str, WasmDynamicError> {
    let start: usize = ptr as usize;
    let end: usize = start.saturating_add(len as usize);
    if end > memory.len() {
        return Err(WasmDynamicError::MemoryOutOfBounds {
            addr: ptr,
            len,
            memory_size: memory.len(),
        });
    }
    from_utf8(&memory[start..end])
        .map_err(|_| WasmDynamicError::InvalidUiPayload("non-UTF8 memory buffer".to_string()))
}

/// Statically inspects a WebAssembly function bytecode body and returns `true` when it touches zero linear memory and performs zero calls.
///
/// # Arguments
///
/// - `&[u8]` - Raw bytecode instruction slice for one defined function.
///
/// # Returns
///
/// - `bool` - `true` when linear memory allocation and data segment copying may be skipped safely.
#[must_use]
fn wasm_body_is_pure_no_memory(code: &[u8]) -> bool {
    const MEMORY_OR_CALL_OPS: [u8; 3] = [OP_CALL, OP_I32_LOAD, OP_I32_STORE];
    const BLOCK_OPS: [u8; 3] = [OP_BLOCK, OP_LOOP, OP_IF];
    const ULEB_IMM_OPS: [u8; 4] = [OP_LOCAL_GET, OP_LOCAL_SET, OP_BR, OP_BR_IF];
    const ZERO_IMM_OPS: [u8; 15] = [
        OP_UNREACHABLE,
        OP_NOP,
        OP_ELSE,
        OP_END,
        OP_RETURN,
        OP_DROP,
        OP_I32_EQZ,
        OP_I32_EQ,
        OP_I32_NE,
        OP_I32_LT_S,
        OP_I32_GT_S,
        OP_I32_ADD,
        OP_I32_SUB,
        OP_I32_MUL,
        OP_I32_DIV_S,
    ];
    let mut pc: usize = 0;
    while pc < code.len() {
        let op: u8 = code[pc];
        pc += 1;
        if MEMORY_OR_CALL_OPS.contains(&op) {
            return false;
        }
        if BLOCK_OPS.contains(&op) {
            if pc >= code.len() {
                return false;
            }
            pc += 1;
        } else if op == OP_I32_CONST {
            if read_sleb128(code, &mut pc).is_err() {
                return false;
            }
        } else if ULEB_IMM_OPS.contains(&op) {
            if read_uleb128(code, &mut pc).is_err() {
                return false;
            }
        } else if !ZERO_IMM_OPS.contains(&op) {
            return false;
        }
    }
    true
}

/// Executes a single WASM export against an explicit zeroed linear memory slice and reports the high-water dirty byte offset.
///
/// # Arguments
///
/// - `&WasmParsedModule` - Validated `.wasm` module.
/// - `u32` - Absolute function index resolved from exports.
/// - `&[i32]` - Positional `i32` arguments.
/// - `&WasmSandboxConfig` - Fuel and memory limits.
/// - `&mut [u8]` - Pre-zeroed linear memory slice sized to `mem_bytes`.
///
/// # Returns
///
/// - `(Result<WasmExecutionOutput, WasmDynamicError>, usize)` - Execution result paired with the dirty prefix length to re-zero.
fn execute_wasm_with_memory_slice(
    module: &WasmParsedModule,
    func_idx: u32,
    args: &[i32],
    config: &WasmSandboxConfig,
    memory: &mut [u8],
) -> (Result<WasmExecutionOutput, WasmDynamicError>, usize) {
    let mut dirty_end: usize = 0;
    for seg in module.get_data_segments().iter() {
        let start: usize = seg.get_offset() as usize;
        let end: usize = start.saturating_add(seg.get_bytes().len());
        if end > memory.len() {
            return (
                Err(WasmDynamicError::MemoryOutOfBounds {
                    addr: seg.get_offset(),
                    len: seg.get_bytes().len() as u32,
                    memory_size: memory.len(),
                }),
                dirty_end,
            );
        }
        memory[start..end].copy_from_slice(seg.get_bytes().as_slice());
        if end > dirty_end {
            dirty_end = end;
        }
    }
    let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
    let mut exec: WasmExecContext<'_> = WasmExecContext {
        memory,
        out: &mut out,
        fuel_used: 0,
        max_fuel: config.get_max_fuel(),
        depth: 0,
        dirty_end,
    };
    let ret_res: Result<i32, WasmDynamicError> =
        execute_wasm_func_index(module, func_idx, args, &mut exec);
    let final_dirty: usize = exec.dirty_end;
    let fuel_used: u64 = exec.fuel_used;
    match ret_res {
        Ok(ret) => {
            out.set_return_value(ret);
            out.set_fuel_used(fuel_used);
            (Ok(out), final_dirty)
        }
        Err(err) => (Err(err), final_dirty),
    }
}

/// Executes an exported WebAssembly function inside a fuel-metered, memory-bounded sandbox.
///
/// # Arguments
///
/// - `&WasmParsedModule` - Validated `.wasm` module.
/// - `&str` - Exported function name (e.g. `"euv_render"`, `"euv_on_event"`, `"euv_abi_version"`).
/// - `&[i32]` - Positional `i32` arguments passed to the export.
/// - `&WasmSandboxConfig` - Fuel and memory limits.
///
/// # Returns
///
/// - `Result<WasmExecutionOutput, WasmDynamicError>` - Execution output including emitted native UI spec or bundle.
pub fn execute_wasm_export(
    module: &WasmParsedModule,
    export_name: &str,
    args: &[i32],
    config: &WasmSandboxConfig,
) -> Result<WasmExecutionOutput, WasmDynamicError> {
    let func_idx: u32 = *module
        .get_exports()
        .get(export_name)
        .ok_or_else(|| WasmDynamicError::MissingExport(export_name.to_string()))?;
    let mem_bytes: usize =
        (module.get_memory_min_pages().max(1) as usize).saturating_mul(WASM_PAGE_BYTES);
    if mem_bytes > config.get_max_memory_bytes() {
        return Err(WasmDynamicError::MemoryLimitExceeded {
            requested: mem_bytes,
            limit: config.get_max_memory_bytes(),
        });
    }
    let import_count: usize = module.get_imports().len();
    let is_pure_no_memory: bool = (func_idx as usize) >= import_count
        && module
            .get_functions()
            .get((func_idx as usize) - import_count)
            .is_some_and(WasmParsedFunction::get_pure_no_memory);
    if is_pure_no_memory {
        for seg in module.get_data_segments().iter() {
            let start: usize = seg.get_offset() as usize;
            let end: usize = start.saturating_add(seg.get_bytes().len());
            if end > mem_bytes {
                return Err(WasmDynamicError::MemoryOutOfBounds {
                    addr: seg.get_offset(),
                    len: seg.get_bytes().len() as u32,
                    memory_size: mem_bytes,
                });
            }
        }
        let mut out: WasmExecutionOutput = WasmExecutionOutput::default();
        let mut empty_mem: [u8; 0] = [];
        let mut exec: WasmExecContext<'_> = WasmExecContext {
            memory: &mut empty_mem,
            out: &mut out,
            fuel_used: 0,
            max_fuel: config.get_max_fuel(),
            depth: 0,
            dirty_end: 0,
        };
        let ret: i32 = execute_wasm_func_index(module, func_idx, args, &mut exec)?;
        let fuel_used: u64 = exec.fuel_used;
        out.set_return_value(ret);
        out.set_fuel_used(fuel_used);
        return Ok(out);
    }
    WASM_LINEAR_MEMORY_POOL.with(|cell: &RefCell<WasmMemoryPool>| {
        if let Ok(mut pool) = cell.try_borrow_mut() {
            if pool.buffer.len() < mem_bytes {
                pool.buffer.resize(mem_bytes, 0);
            }
            let (res, dirty_end): (Result<WasmExecutionOutput, WasmDynamicError>, usize) =
                execute_wasm_with_memory_slice(
                    module,
                    func_idx,
                    args,
                    config,
                    &mut pool.buffer[..mem_bytes],
                );
            let clear_len: usize = dirty_end.min(pool.buffer.len());
            if clear_len > 0 {
                pool.buffer[..clear_len].fill(0);
            }
            let max_retained_bytes: usize = WASM_PAGE_BYTES.saturating_mul(4);
            if pool.buffer.len() > max_retained_bytes {
                pool.buffer.truncate(max_retained_bytes);
                pool.buffer.shrink_to_fit();
            }
            res
        } else {
            let mut local_mem: Vec<u8> = vec![0; mem_bytes];
            let (res, _): (Result<WasmExecutionOutput, WasmDynamicError>, usize) =
                execute_wasm_with_memory_slice(
                    module,
                    func_idx,
                    args,
                    config,
                    local_mem.as_mut_slice(),
                );
            res
        }
    })
}

/// Evaluates an `i32` binary WebAssembly opcode if `op` matches one.
///
/// # Arguments
///
/// - `u8` - Bytecode opcode.
/// - `&mut Vec<i32>` - Active operand stack.
///
/// # Returns
///
/// - `Result<Option<i32>, WasmDynamicError>` - Computed result if `op` is a supported binop, `None` otherwise.
fn eval_i32_binop(op: u8, stack: &mut Vec<i32>) -> Result<Option<i32>, WasmDynamicError> {
    let is_binop: bool = op == OP_I32_EQ
        || op == OP_I32_NE
        || op == OP_I32_LT_S
        || op == OP_I32_GT_S
        || op == OP_I32_ADD
        || op == OP_I32_SUB
        || op == OP_I32_MUL
        || op == OP_I32_DIV_S;
    if !is_binop {
        return Ok(None);
    }
    let b: i32 = stack
        .pop()
        .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
    let a: i32 = stack
        .pop()
        .ok_or_else(|| WasmDynamicError::ExecutionTrap(WASM_ERR_STACK_BINOP.to_string()))?;
    let res: i32 = match op {
        OP_I32_EQ => i32::from(a == b),
        OP_I32_NE => i32::from(a != b),
        OP_I32_LT_S => i32::from(a < b),
        OP_I32_GT_S => i32::from(a > b),
        OP_I32_ADD => a.wrapping_add(b),
        OP_I32_SUB => a.wrapping_sub(b),
        OP_I32_MUL => a.wrapping_mul(b),
        OP_I32_DIV_S => {
            if b == 0 {
                return Err(WasmDynamicError::ExecutionTrap(
                    "integer divide by zero".to_string(),
                ));
            }
            a.wrapping_div(b)
        }
        _ => 0,
    };
    Ok(Some(res))
}

/// Internal recursive bytecode interpreter executing a single WASM function or host import call.
///
/// # Arguments
///
/// - `&WasmParsedModule` - Active parsed module.
/// - `u32` - Absolute function index (imports first, then defined functions).
/// - `&[i32]` - Call arguments.
/// - `&mut WasmExecContext<'_>` - Shared mutable memory, host output, fuel, and depth state.
///
/// # Returns
///
/// - `Result<i32, WasmDynamicError>` - Return value or sandbox error.
fn execute_wasm_func_index(
    module: &WasmParsedModule,
    func_idx: u32,
    args: &[i32],
    exec: &mut WasmExecContext<'_>,
) -> Result<i32, WasmDynamicError> {
    if exec.depth > 32 {
        return Err(WasmDynamicError::ExecutionTrap(
            "call stack depth overflow".to_string(),
        ));
    }
    let import_count: usize = module.get_imports().len();
    if (func_idx as usize) < import_count {
        let imp: &WasmImportEntry = &module.get_imports()[func_idx as usize];
        let ptr: u32 = args.first().copied().unwrap_or(0).max(0) as u32;
        let len: u32 = args.get(1).copied().unwrap_or(0).max(0) as u32;
        let text: &str = read_memory_str(exec.memory, ptr, len)?;
        if imp.get_name() == WASM_IMPORT_EMIT_UI {
            let spec: DynamicNodeSpec =
                from_str::<DynamicNodeSpec>(text).map_err(|err: serde_json::Error| {
                    WasmDynamicError::InvalidUiPayload(err.to_string())
                })?;
            exec.out.set_emitted_spec(Some(spec));
            return Ok(1);
        }
        if imp.get_name() == WASM_IMPORT_EMIT_BUNDLE {
            let bundle: DynamicUpdateBundle =
                from_str::<DynamicUpdateBundle>(text).map_err(|err: serde_json::Error| {
                    WasmDynamicError::InvalidUiPayload(err.to_string())
                })?;
            exec.out.set_emitted_bundle(Some(bundle));
            return Ok(1);
        }
        if imp.get_name() == WASM_IMPORT_LOG {
            exec.out.get_mut_logs().push(text.to_string());
            return Ok(1);
        }
        return Err(WasmDynamicError::ExecutionTrap(format!(
            "unknown host import {}::{}",
            imp.get_module(),
            imp.get_name()
        )));
    }
    let local_idx: usize = (func_idx as usize) - import_count;
    let func: &WasmParsedFunction = module
        .get_functions()
        .get(local_idx)
        .ok_or_else(|| WasmDynamicError::ExecutionTrap("invalid function index".to_string()))?;
    let sig: WasmFuncSignature = module
        .get_types()
        .get(func.get_type_index() as usize)
        .copied()
        .unwrap_or_default();
    let total_locals: usize = sig
        .get_param_count()
        .saturating_add(func.get_extra_locals())
        .max(args.len());
    let mut inline_locals: [i32; 16] = [0; 16];
    let mut spill_locals: Vec<i32> = if total_locals > inline_locals.len() {
        vec![0; total_locals]
    } else {
        Vec::new()
    };
    let locals: &mut [i32] = if spill_locals.is_empty() {
        &mut inline_locals[..total_locals]
    } else {
        spill_locals.as_mut_slice()
    };
    for (idx, val) in args.iter().copied().enumerate() {
        if idx < locals.len() {
            locals[idx] = val;
        }
    }
    let code: &[u8] = func.get_body().as_slice();
    let mut stack: Vec<i32> = Vec::with_capacity(32);
    let mut labels: Vec<(u8, usize)> = Vec::with_capacity(16);
    let mut pc: usize = 0;
    while pc < code.len() {
        exec.fuel_used = exec.fuel_used.saturating_add(1);
        if exec.fuel_used > exec.max_fuel {
            return Err(WasmDynamicError::OutOfFuel {
                limit: exec.max_fuel,
            });
        }
        let op: u8 = code[pc];
        pc += 1;
        match op {
            OP_UNREACHABLE => {
                return Err(WasmDynamicError::ExecutionTrap(
                    "wasm unreachable instruction trapped".to_string(),
                ));
            }
            OP_NOP => {}
            OP_BLOCK | OP_LOOP => {
                let _: u8 = *code.get(pc).unwrap_or(&0x40);
                pc = pc.saturating_add(1);
                labels.push((op, pc));
            }
            OP_IF => {
                let _: u8 = *code.get(pc).unwrap_or(&0x40);
                pc = pc.saturating_add(1);
                let cond: i32 = stack.pop().ok_or_else(|| {
                    WasmDynamicError::ExecutionTrap("stack underflow on if".to_string())
                })?;
                if cond != 0 {
                    labels.push((OP_IF, pc));
                } else {
                    let mut nesting: usize = 0;
                    while pc < code.len() {
                        let scan: u8 = code[pc];
                        pc += 1;
                        if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
                            nesting += 1;
                            pc = pc.saturating_add(1);
                        } else if scan == OP_ELSE && nesting == 0 {
                            labels.push((OP_ELSE, pc));
                            break;
                        } else if scan == OP_END {
                            if nesting == 0 {
                                break;
                            }
                            nesting -= 1;
                        } else if scan == OP_I32_CONST {
                            let _: i32 = read_sleb128(code, &mut pc)?;
                        } else if scan == OP_LOCAL_GET
                            || scan == OP_LOCAL_SET
                            || scan == OP_CALL
                            || scan == OP_BR
                            || scan == OP_BR_IF
                        {
                            let _: u32 = read_uleb128(code, &mut pc)?;
                        } else if scan == OP_I32_LOAD || scan == OP_I32_STORE {
                            let _: u32 = read_uleb128(code, &mut pc)?;
                            let _: u32 = read_uleb128(code, &mut pc)?;
                        }
                    }
                }
            }
            OP_ELSE => {
                let _: Option<(u8, usize)> = labels.pop();
                let mut nesting: usize = 0;
                while pc < code.len() {
                    let scan: u8 = code[pc];
                    pc += 1;
                    if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
                        nesting += 1;
                        pc = pc.saturating_add(1);
                    } else if scan == OP_END {
                        if nesting == 0 {
                            break;
                        }
                        nesting -= 1;
                    } else if scan == OP_I32_CONST {
                        let _: i32 = read_sleb128(code, &mut pc)?;
                    } else if scan == OP_LOCAL_GET
                        || scan == OP_LOCAL_SET
                        || scan == OP_CALL
                        || scan == OP_BR
                        || scan == OP_BR_IF
                    {
                        let _: u32 = read_uleb128(code, &mut pc)?;
                    } else if scan == OP_I32_LOAD || scan == OP_I32_STORE {
                        let _: u32 = read_uleb128(code, &mut pc)?;
                        let _: u32 = read_uleb128(code, &mut pc)?;
                    }
                }
            }
            OP_END => {
                if labels.pop().is_none() {
                    break;
                }
            }
            OP_BR | OP_BR_IF => {
                let target_depth: usize = read_uleb128(code, &mut pc)? as usize;
                let take_branch: bool = if op == OP_BR_IF {
                    stack.pop().unwrap_or(0) != 0
                } else {
                    true
                };
                if take_branch {
                    if target_depth >= labels.len() {
                        break;
                    }
                    let keep_len: usize = labels.len() - target_depth;
                    let (lbl_op, lbl_pc): (u8, usize) = labels[keep_len - 1];
                    if lbl_op == OP_LOOP {
                        labels.truncate(keep_len);
                        pc = lbl_pc;
                    } else {
                        labels.truncate(keep_len - 1);
                        let mut nesting: usize = 0;
                        while pc < code.len() {
                            let scan: u8 = code[pc];
                            pc += 1;
                            if scan == OP_BLOCK || scan == OP_LOOP || scan == OP_IF {
                                nesting += 1;
                                pc = pc.saturating_add(1);
                            } else if scan == OP_END {
                                if nesting == 0 {
                                    break;
                                }
                                nesting -= 1;
                            }
                        }
                    }
                }
            }
            OP_RETURN => break,
            OP_CALL => {
                let callee: u32 = read_uleb128(code, &mut pc)?;
                let callee_type: u32 = if (callee as usize) < import_count {
                    module.get_imports()[callee as usize].get_type_index()
                } else {
                    module
                        .get_functions()
                        .get((callee as usize) - import_count)
                        .map(WasmParsedFunction::get_type_index)
                        .unwrap_or(0)
                };
                let csig: WasmFuncSignature = module
                    .get_types()
                    .get(callee_type as usize)
                    .copied()
                    .unwrap_or_default();
                let param_count: usize = csig.get_param_count();
                let mut inline_args: [i32; 8] = [0; 8];
                let mut spill_args: Vec<i32> = if param_count > inline_args.len() {
                    vec![0; param_count]
                } else {
                    Vec::new()
                };
                let call_args: &mut [i32] = if spill_args.is_empty() {
                    &mut inline_args[..param_count]
                } else {
                    spill_args.as_mut_slice()
                };
                for idx in (0..param_count).rev() {
                    call_args[idx] = stack.pop().ok_or_else(|| {
                        WasmDynamicError::ExecutionTrap("stack underflow on call".to_string())
                    })?;
                }
                exec.depth = exec.depth.saturating_add(1);
                let call_res: Result<i32, WasmDynamicError> =
                    execute_wasm_func_index(module, callee, call_args, exec);
                exec.depth = exec.depth.saturating_sub(1);
                let call_ret: i32 = call_res?;
                if csig.get_result_count() > 0 {
                    stack.push(call_ret);
                }
            }
            OP_DROP => {
                let _: Option<i32> = stack.pop();
            }
            OP_LOCAL_GET => {
                let idx: usize = read_uleb128(code, &mut pc)? as usize;
                let val: i32 = *locals.get(idx).unwrap_or(&0);
                stack.push(val);
            }
            OP_LOCAL_SET => {
                let idx: usize = read_uleb128(code, &mut pc)? as usize;
                let val: i32 = stack.pop().ok_or_else(|| {
                    WasmDynamicError::ExecutionTrap("stack underflow on local.set".to_string())
                })?;
                if idx < locals.len() {
                    locals[idx] = val;
                }
            }
            OP_I32_LOAD => {
                let _: u32 = read_uleb128(code, &mut pc)?;
                let offset: u32 = read_uleb128(code, &mut pc)?;
                let base: u32 = stack.pop().unwrap_or(0).max(0) as u32;
                let addr: usize = (base.saturating_add(offset)) as usize;
                if addr.saturating_add(4) > exec.memory.len() {
                    return Err(WasmDynamicError::MemoryOutOfBounds {
                        addr: addr as u32,
                        len: 4,
                        memory_size: exec.memory.len(),
                    });
                }
                let val: i32 = i32::from_le_bytes([
                    exec.memory[addr],
                    exec.memory[addr + 1],
                    exec.memory[addr + 2],
                    exec.memory[addr + 3],
                ]);
                stack.push(val);
            }
            OP_I32_STORE => {
                let _: u32 = read_uleb128(code, &mut pc)?;
                let offset: u32 = read_uleb128(code, &mut pc)?;
                let val: i32 = stack.pop().unwrap_or(0);
                let base: u32 = stack.pop().unwrap_or(0).max(0) as u32;
                let addr: usize = (base.saturating_add(offset)) as usize;
                if addr.saturating_add(4) > exec.memory.len() {
                    return Err(WasmDynamicError::MemoryOutOfBounds {
                        addr: addr as u32,
                        len: 4,
                        memory_size: exec.memory.len(),
                    });
                }
                let write_end: usize = addr + 4;
                exec.memory[addr..write_end].copy_from_slice(&val.to_le_bytes());
                if write_end > exec.dirty_end {
                    exec.dirty_end = write_end;
                }
            }
            OP_I32_CONST => {
                let val: i32 = read_sleb128(code, &mut pc)?;
                stack.push(val);
            }
            OP_I32_EQZ => {
                let a: i32 = stack.pop().unwrap_or(0);
                stack.push(if a == 0 { 1 } else { 0 });
            }
            other => {
                if let Some(res) = eval_i32_binop(other, &mut stack)? {
                    stack.push(res);
                } else {
                    return Err(WasmDynamicError::ExecutionTrap(format!(
                        "unsupported wasm opcode 0x{other:02x}"
                    )));
                }
            }
        }
    }
    Ok(stack.pop().unwrap_or(0))
}

/// Builds a genuine signed partial-slot `.wasm` binary rendering a rich native `DynamicNodeSpec` with live interactive state.
///
/// # Arguments
///
/// - `&str` - Display title rendered by the WASM widget.
/// - `u64` - Release version number.
/// - `u32` - Accent RGB hex color.
///
/// # Returns
///
/// - `Vec<u8>` - Spec-compliant executable `.wasm` binary bytes.
#[must_use]
pub fn build_partial_widget_wasm(title: &str, version: u64, accent_hex: u32) -> Vec<u8> {
    let mut badge: DynamicNodeSpec = DynamicNodeSpec::badge(format!("WASM v{version} · NATIVE"));
    badge
        .get_mut_style()
        .set_background_hex(Some(accent_hex))
        .set_color_hex(Some(0xFFFFFF));
    let mut heading: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
    heading
        .get_mut_style()
        .set_bold(true)
        .set_font_size(Some(14.0));
    let sub: DynamicNodeSpec = DynamicNodeSpec::text(format!(
        "Downloaded .wasm binary executed in sandboxed VM and rendered directly to native SceneTree (rev v{version}, state=0)."
    ));
    let mut btn_interact: DynamicNodeSpec = DynamicNodeSpec::button(
        "Invoke WASM euv_on_event (+1)".to_string(),
        "wasm_interact".to_string(),
    );
    btn_interact.get_mut_style().set_full_width(true);
    btn_interact.set_payload(format!("wasm-partial-v{version}"));
    let mut root_even: DynamicNodeSpec = DynamicNodeSpec::column()
        .child(
            DynamicNodeSpec::row()
                .child(badge.clone())
                .child(heading.clone()),
        )
        .child(sub)
        .child(btn_interact.clone());
    root_even
        .get_mut_style()
        .set_full_width(true)
        .set_padding(Some(14.0))
        .set_gap(Some(10.0))
        .set_radius(Some(10.0))
        .set_border_width(Some(1.0))
        .set_border_hex(Some(accent_hex));
    let sub_alt: DynamicNodeSpec = DynamicNodeSpec::text(format!(
        "Interactive WASM state toggled inside sandbox (rev v{version}, active pulse state=1) — zero host rebuild!"
    ));
    let mut root_odd: DynamicNodeSpec = DynamicNodeSpec::column()
        .child(DynamicNodeSpec::row().child(badge).child(heading))
        .child(sub_alt)
        .child(btn_interact);
    root_odd
        .get_mut_style()
        .set_full_width(true)
        .set_padding(Some(14.0))
        .set_gap(Some(10.0))
        .set_radius(Some(10.0))
        .set_background_hex(Some(0xECFDF5))
        .set_border_width(Some(1.0))
        .set_border_hex(Some(0x10B981));
    WasmModuleBuilder::partial_spec(&root_even)
        .with_alt_spec(&root_odd)
        .with_log(format!("partial wasm v{version} rendered natively"))
        .build()
}

/// Builds one deterministic state bundle (`state_idx = 0 | 1`) embedded inside a global full-app `.wasm` release.
///
/// # Arguments
///
/// - `&str` - Global release title.
/// - `u64` - Monotonic global release version.
/// - `u8` - Interactive toggle state index (`0` or `1`).
///
/// # Returns
///
/// - `DynamicUpdateBundle` - Signed bundle targeting both global root component and page routes.
#[must_use]
fn build_global_state_bundle(title: &str, version: u64, state_idx: u8) -> DynamicUpdateBundle {
    let mut badge: DynamicNodeSpec =
        DynamicNodeSpec::badge(format!("GLOBAL WASM APP v{version} · STATE #{state_idx}"));
    badge
        .get_mut_style()
        .set_background_hex(Some(if state_idx == 0 { 0x0F766E } else { 0x1D4ED8 }))
        .set_color_hex(Some(0xFFFFFF));
    let mut hero_title: DynamicNodeSpec = DynamicNodeSpec::text(title.to_string());
    hero_title
        .get_mut_style()
        .set_bold(true)
        .set_font_size(Some(20.0));
    let hero_sub: DynamicNodeSpec = DynamicNodeSpec::text(if state_idx == 0 {
        format!(
            "Entire native UI shell hot-replaced atomically from downloaded global .wasm release v{version}. Tap any button below to invoke sandboxed WASM events or return."
        )
    } else {
        format!(
            "Global WASM euv_on_event executed live inside sandbox (v{version}, active pulse state=1)! Zero restart — tap Restore Native Shell anytime to roll back."
        )
    });
    let mut kpi_col: DynamicNodeSpec =
        DynamicNodeSpec::column()
            .child(DynamicNodeSpec::card("Execution Mode".to_string()).child(
                DynamicNodeSpec::text("Sandboxed WASM -> Native SceneTree".to_string()),
            ))
            .child(
                DynamicNodeSpec::card("Integrity Gate".to_string())
                    .child(DynamicNodeSpec::text(format!("Verified Signed v{version}"))),
            )
            .child(
                DynamicNodeSpec::card("Safety Guard".to_string()).child(DynamicNodeSpec::text(
                    "Fuel + Memory + Atomic LKG Rollback".to_string(),
                )),
            );
    kpi_col
        .get_mut_style()
        .set_full_width(true)
        .set_gap(Some(10.0));
    let mut btn_action: DynamicNodeSpec = DynamicNodeSpec::button(
        "Invoke Global WASM Action (+1)".to_string(),
        "global_wasm_action".to_string(),
    );
    btn_action.get_mut_style().set_full_width(true);
    btn_action.set_payload(format!("global-v{version}-state-{state_idx}"));
    let mut btn_rollback: DynamicNodeSpec = DynamicNodeSpec::button(
        "Rollback Previous Version".to_string(),
        "global_wasm_rollback".to_string(),
    );
    btn_rollback
        .get_mut_style()
        .set_full_width(true)
        .set_background_hex(Some(0x334155))
        .set_color_hex(Some(0xFFFFFF));
    btn_rollback.set_payload("rollback-global".to_string());
    let mut btn_restore: DynamicNodeSpec = DynamicNodeSpec::button(
        "Return to Native Shell".to_string(),
        "global_wasm_restore".to_string(),
    );
    btn_restore
        .get_mut_style()
        .set_full_width(true)
        .set_background_hex(Some(0x0F766E))
        .set_color_hex(Some(0xFFFFFF));
    btn_restore.set_payload("restore-native".to_string());
    let mut action_row: DynamicNodeSpec = DynamicNodeSpec::column()
        .child(btn_action)
        .child(btn_rollback)
        .child(btn_restore);
    action_row
        .get_mut_style()
        .set_full_width(true)
        .set_gap(Some(10.0));
    let mut root_spec: DynamicNodeSpec = DynamicNodeSpec::column()
        .child(badge)
        .child(hero_title)
        .child(hero_sub)
        .child(action_row)
        .child(kpi_col);
    root_spec
        .get_mut_style()
        .set_full_width(true)
        .set_padding(Some(20.0))
        .set_gap(Some(14.0))
        .set_radius(Some(12.0))
        .set_background_hex(Some(if state_idx == 0 { 0xFFFFFF } else { 0xEFF6FF }))
        .set_border_width(Some(1.0))
        .set_border_hex(Some(if state_idx == 0 { 0x14B8A6 } else { 0x2563EB }));
    let mut global_comp: DynamicComponentUpdate = DynamicComponentUpdate::new(
        WASM_GLOBAL_ROOT_SLOT.to_string(),
        version,
        root_spec.clone(),
    );
    global_comp.set_allow_downgrade(true);
    global_comp.sign();
    let mut global_page: DynamicPageUpdate = DynamicPageUpdate::new(
        "/wasm-global-live".to_string(),
        format!("Global WASM v{version}"),
        version,
        root_spec,
    );
    global_page.set_allow_downgrade(true);
    global_page.sign();
    let mut bundle: DynamicUpdateBundle =
        DynamicUpdateBundle::new(format!("global-wasm-v{version}"), version);
    bundle.get_mut_components().push(global_comp);
    bundle.get_mut_pages().push(global_page);
    bundle
}

/// Builds a genuine global full-app `.wasm` binary emitting a complete `DynamicUpdateBundle` that atomically takes over the root shell.
///
/// # Arguments
///
/// - `&str` - Global release title.
/// - `u64` - Monotonic global release version.
///
/// # Returns
///
/// - `Vec<u8>` - Spec-compliant executable global `.wasm` binary bytes.
#[must_use]
pub fn build_global_app_wasm(title: &str, version: u64) -> Vec<u8> {
    let bundle_even: DynamicUpdateBundle = build_global_state_bundle(title, version, 0);
    let bundle_odd: DynamicUpdateBundle = build_global_state_bundle(title, version, 1);
    WasmModuleBuilder::global_bundle(&bundle_even)
        .with_alt_bundle(&bundle_odd)
        .with_log(format!("global wasm bundle v{version} mounted natively"))
        .build()
}

/// Builds a faulty `.wasm` binary exercising a specific security, integrity, ABI, or sandbox trap case.
///
/// # Arguments
///
/// - `WasmFaultKind` - Specific failure case to compile into the test binary.
///
/// # Returns
///
/// - `Vec<u8>` - Crafted `.wasm` binary bytes triggering `fault`.
#[must_use]
pub fn build_faulty_wasm(fault: WasmFaultKind) -> Vec<u8> {
    match fault {
        WasmFaultKind::CorruptedMagic => b"NOT_A_VALID_WASM_BINARY".to_vec(),
        WasmFaultKind::AbiMismatch => {
            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Incompatible ABI".to_string()))
                .with_abi_version(99)
                .build()
        }
        WasmFaultKind::MissingExport => {
            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Missing Export".to_string()))
                .without_render_export()
                .build()
        }
        WasmFaultKind::InfiniteLoopOutOfFuel => {
            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Infinite Loop".to_string()))
                .with_fault(WasmFaultKind::InfiniteLoopOutOfFuel)
                .build()
        }
        WasmFaultKind::ExecutionTrap => {
            WasmModuleBuilder::partial_spec(&DynamicNodeSpec::text("Trap".to_string()))
                .with_fault(WasmFaultKind::ExecutionTrap)
                .build()
        }
        WasmFaultKind::OversizedBinary => {
            let mut big: Vec<u8> = build_partial_widget_wasm("Oversized", 1, 0xDC2626);
            big.resize(WASM_DEFAULT_MAX_BINARY_BYTES + 64, 0);
            big
        }
        _ => build_partial_widget_wasm("Fault Fixture", 1, 0x2563EB),
    }
}