verter_core 0.0.1-beta.1

Vue 3 SFC compiler - transforms Vue Single File Components to render functions with TypeScript support
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
//! Scoped CSS visitor using lightningcss.
//!
//! Walks the CSS AST and inserts `[data-v-{scopeId}]` attribute selectors
//! to scope styles to a specific Vue component.
//!
//! Also handles pre-pass markers:
//! - `[__v_deep__]` → `[data-v-{scopeId}]` (scope parent only)
//! - `[__v_slotted__]` → `[data-v-{scopeId}-s]` (slot scope)

use smallvec::SmallVec;

use super::prepass::{DEEP_MARKER, SLOTTED_MARKER};

/// Apply scoped selectors on already-normalized CSS (no lightningcss re-parse).
///
/// **Precondition:** `normalized_css` must have been parsed and serialized by
/// lightningcss (via [`super::normalize_css`]). This ensures nested rules are
/// flattened and comments/strings are well-formed. Calling this on raw CSS may
/// skip selectors inside `@media` or `@supports` blocks.
#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub fn apply_scoped_normalized(normalized_css: &str, scope_id: &str) -> String {
    let scope_attr = format!("[data-v-{}]", scope_id);
    let slotted_attr = format!("[data-v-{}-s]", scope_id);
    apply_scoped_to_normalized(normalized_css, &scope_attr, &slotted_attr)
}

/// Apply scoped attribute selectors to CSS.
///
/// Standalone entry point that normalizes CSS internally.
/// Replaces pre-pass markers and adds `[data-v-{scopeId}]` to all selectors
/// that don't contain `:global()`.
pub fn apply_scoped(css: &str, scope_id: &str) -> Result<String, super::CssError> {
    let normalized = super::normalize_css(css)?;
    Ok(apply_scoped_normalized(&normalized, scope_id))
}

/// Apply scoped attribute selectors to raw CSS without lightningcss normalization.
///
/// This is a faster alternative to [`apply_scoped`] that skips the
/// lightningcss parse/serialize step. The walker handles comments, strings,
/// @-rules, and @keyframes directly.
///
/// **Trade-off:** CSS values are not normalized (colors, units, shorthand).
/// CSS nesting (`&`) is not flattened. For scoped styles in Vue SFCs, this
/// is typically fine — the browser handles nesting natively.
pub fn apply_scoped_raw(css: &str, scope_id: &str) -> String {
    let scope_attr = format!("[data-v-{}]", scope_id);
    let slotted_attr = format!("[data-v-{}-s]", scope_id);
    apply_scoped_to_normalized(css, &scope_attr, &slotted_attr)
}

/// Apply scoped selectors to normalized CSS (already parsed and serialized by lightningcss).
///
/// This function handles:
/// 1. Replacing `[__v_deep__]` markers with `[data-v-xxx]`
/// 2. Replacing `[__v_slotted__]` markers with `[data-v-xxx-s]`
/// 3. Adding `[data-v-xxx]` to all other selectors (at the right position)
fn apply_scoped_to_normalized(css: &str, scope_attr: &str, slotted_attr: &str) -> String {
    super::walk::walk_and_transform_selectors(css, |selectors| {
        transform_selector_list(selectors, scope_attr, slotted_attr)
    })
}

/// Transform a comma-separated selector list.
fn transform_selector_list(selectors: &str, scope_attr: &str, slotted_attr: &str) -> String {
    let mut result = String::with_capacity(selectors.len() + scope_attr.len() * 2);
    for (i, s) in selectors.split(',').enumerate() {
        if i > 0 {
            result.push_str(", ");
        }
        result.push_str(&transform_single_selector(
            s.trim(),
            scope_attr,
            slotted_attr,
        ));
    }
    result
}

/// Transform a single selector, adding scope attributes.
fn transform_single_selector(selector: &str, scope_attr: &str, slotted_attr: &str) -> String {
    // Handle __v_deep__ marker: replace with scope attr (already positioned correctly by prepass)
    if selector.contains(DEEP_MARKER) {
        return selector.replace(DEEP_MARKER, scope_attr);
    }

    // Handle __v_slotted__ marker: replace with slotted scope attr
    if selector.contains(SLOTTED_MARKER) {
        return selector.replace(SLOTTED_MARKER, slotted_attr);
    }

    // Handle :global() — lightningcss may have parsed this; just strip the wrapper
    if selector.contains(":global(") {
        return transform_global(selector);
    }

    // WS 5.3: Strip :deep() with empty parens — prepass leaves it unchanged,
    // lightningcss preserves it. Remove the pseudo-class and scope normally.
    if selector.contains(":deep()") {
        let stripped = selector.replace(":deep()", "");
        let trimmed = stripped.trim();
        if trimmed.is_empty() {
            // Bare `:deep()` with no other selector — just scope the universal selector
            return scope_attr.to_string();
        }
        return add_scope_to_selector(trimmed, scope_attr);
    }

    // Regular selector: add scope to each compound selector
    add_scope_to_selector(selector, scope_attr)
}

/// Strip `:global()` wrapper from selector.
fn transform_global(selector: &str) -> String {
    let mut result = String::with_capacity(selector.len());
    let mut remaining = selector;

    while let Some(pos) = remaining.find(":global(") {
        result.push_str(&remaining[..pos]);
        let after = &remaining[pos + 8..]; // skip ":global("

        // Find matching closing paren
        let mut depth = 1u32;
        let mut end = 0;
        for (i, c) in after.char_indices() {
            match c {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        end = i;
                        break;
                    }
                }
                _ => {}
            }
        }

        let inner = &after[..end];
        result.push_str(inner.trim());
        remaining = &after[end + 1..]; // skip past closing ')'
    }

    result.push_str(remaining);
    result
}

/// Add scope attribute to the last compound selector in a complex selector.
///
/// Matches Vue's official compiler behavior: only the rightmost compound selector
/// receives the scope attribute (e.g., `.parent .child` → `.parent .child[data-v-xxx]`).
///
/// Uses byte-offset spans into the original selector string to avoid allocating
/// intermediate `String`s for each segment and combinator.
fn add_scope_to_selector(selector: &str, scope_attr: &str) -> String {
    let bytes = selector.as_bytes();
    // Segment and combinator byte ranges — stack-allocated for typical selectors.
    let mut segments: SmallVec<[(usize, usize); 4]> = SmallVec::new();
    let mut combinators: SmallVec<[(usize, usize); 4]> = SmallVec::new();
    let mut seg_start = 0usize;
    let mut i = 0usize;

    while i < bytes.len() {
        match bytes[i] {
            b' ' | b'>' | b'+' | b'~' => {
                // Record segment (trimmed)
                let seg = selector[seg_start..i].trim();
                if !seg.is_empty() {
                    let offset = seg.as_ptr() as usize - selector.as_ptr() as usize;
                    segments.push((offset, offset + seg.len()));
                }
                // Record combinator span — consume all adjacent space/combinator chars.
                // Merges ` > ` into a single combinator span (matching original behavior).
                let comb_start = i;
                let first = bytes[i];
                i += 1;
                while i < bytes.len() {
                    match bytes[i] {
                        b' ' => i += 1,
                        b'>' | b'+' | b'~'
                            if first == b' ' || (i > comb_start + 1 && bytes[i - 1] == b' ') =>
                        {
                            i += 1;
                        }
                        _ => break,
                    }
                }
                combinators.push((comb_start, i));
                seg_start = i;
            }
            _ => i += 1,
        }
    }
    // Final segment
    let seg = selector[seg_start..].trim();
    if !seg.is_empty() {
        let offset = seg.as_ptr() as usize - selector.as_ptr() as usize;
        segments.push((offset, offset + seg.len()));
    }

    // Build result — only the last segment gets the scope attribute
    let mut result = String::with_capacity(selector.len() + scope_attr.len());
    for (idx, &(start, end)) in segments.iter().enumerate() {
        if idx == segments.len() - 1 {
            result.push_str(&scope_simple_selector(&selector[start..end], scope_attr));
        } else {
            result.push_str(&selector[start..end]);
        }
        if idx < combinators.len() {
            let (cs, ce) = combinators[idx];
            result.push_str(&selector[cs..ce]);
        }
    }
    result
}

/// Add scope attribute to a simple (compound) selector.
/// Inserts before pseudo-classes and pseudo-elements.
fn scope_simple_selector(selector: &str, scope_attr: &str) -> String {
    let selector = selector.trim();
    if selector.is_empty() {
        return selector.to_string();
    }

    // Find where to insert the scope attribute
    // It should go after element/class/id selectors, before pseudo-classes/elements
    let mut insert_pos = selector.len();

    if let Some(pos) = find_pseudo_class_pos(selector) {
        insert_pos = pos;
    }

    let mut result = String::with_capacity(selector.len() + scope_attr.len());
    result.push_str(&selector[..insert_pos]);
    result.push_str(scope_attr);
    result.push_str(&selector[insert_pos..]);
    result
}

/// Find the position of the first `:` in the selector, skipping attribute
/// selectors (`[...]`) and backslash-escaped characters.
fn find_pseudo_class_pos(selector: &str) -> Option<usize> {
    let bytes = selector.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        // Skip backslash-escaped characters (e.g., `\:` in class names)
        if bytes[i] == b'\\' && i + 1 < bytes.len() {
            i += 2;
            continue;
        }
        if bytes[i] == b':' {
            return Some(i);
        }
        // Skip attribute selectors
        if bytes[i] == b'[' {
            let mut depth = 1;
            i += 1;
            while i < bytes.len() && depth > 0 {
                match bytes[i] {
                    b'[' => depth += 1,
                    b']' => depth -= 1,
                    _ => {}
                }
                i += 1;
            }
            continue;
        }
        i += 1;
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scoped(css: &str) -> String {
        apply_scoped(css, "a4f2eed6").unwrap()
    }

    #[test]
    fn test_basic_class() {
        let result = scoped(".box { color: red; }");
        assert!(result.contains(".box[data-v-a4f2eed6]"), "Got: {}", result);
    }

    #[test]
    fn test_element_selector() {
        let result = scoped("div { color: red; }");
        assert!(result.contains("div[data-v-a4f2eed6]"), "Got: {}", result);
    }

    #[test]
    fn test_id_selector() {
        let result = scoped("#app { color: red; }");
        assert!(result.contains("#app[data-v-a4f2eed6]"), "Got: {}", result);
    }

    #[test]
    fn test_multiple_selectors() {
        let result = scoped(".a, .b { color: red; }");
        assert!(result.contains(".a[data-v-a4f2eed6]"), "Got: {}", result);
        assert!(result.contains(".b[data-v-a4f2eed6]"), "Got: {}", result);
    }

    #[test]
    fn test_descendant_selector() {
        // Vue behavior: only the last compound selector gets the scope attribute
        let result = scoped(".parent .child { color: red; }");
        assert!(
            !result.contains(".parent[data-v-a4f2eed6]"),
            "Parent should not be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".child[data-v-a4f2eed6]"),
            "Got: {}",
            result
        );
    }

    #[test]
    fn test_pseudo_class_ordering() {
        let result = scoped(".btn:hover { color: red; }");
        assert!(
            result.contains(".btn[data-v-a4f2eed6]:hover"),
            "Got: {}",
            result
        );
    }

    #[test]
    fn test_pseudo_element_ordering() {
        let result = scoped(".text::before { content: ''; }");
        // lightningcss may normalize ::before to :before
        assert!(
            result.contains(".text[data-v-a4f2eed6]:before")
                || result.contains(".text[data-v-a4f2eed6]::before"),
            "Got: {}",
            result
        );
    }

    #[test]
    fn test_deep_marker() {
        // After prepass, :deep(.inner) becomes [__v_deep__] .inner
        let css = "[__v_deep__] .inner { color: red; }";
        let result = apply_scoped(css, "a4f2eed6").unwrap();
        assert!(
            result.contains("[data-v-a4f2eed6] .inner"),
            "Got: {}",
            result
        );
        // Inner should NOT be scoped
        assert!(
            !result.contains(".inner[data-v"),
            "Inner should not be scoped. Got: {}",
            result
        );
    }

    #[test]
    fn test_deep_with_parent() {
        // After prepass, .parent :deep(.inner) becomes .parent [__v_deep__] .inner
        let css = ".parent [__v_deep__] .inner { color: red; }";
        let result = apply_scoped(css, "a4f2eed6").unwrap();
        assert!(result.contains("[data-v-a4f2eed6]"), "Got: {}", result);
    }

    #[test]
    fn test_slotted_marker() {
        // After prepass, :slotted(.slot) becomes .slot[__v_slotted__]
        let css = ".slot[__v_slotted__] { color: red; }";
        let result = apply_scoped(css, "a4f2eed6").unwrap();
        assert!(
            result.contains(".slot[data-v-a4f2eed6-s]"),
            "Got: {}",
            result
        );
    }

    #[test]
    fn test_global_no_scope() {
        let css = ":global(.reset) { margin: 0; }";
        let result = apply_scoped(css, "a4f2eed6").unwrap();
        assert!(result.contains(".reset"), "Got: {}", result);
        assert!(
            !result.contains("[data-v"),
            "Should not have scope attr. Got: {}",
            result
        );
    }

    #[test]
    fn test_media_query_inner_selectors_scoped() {
        let result = scoped("@media (min-width: 600px) { .box { color: red; } }");
        // The @media rule itself should not be scoped
        assert!(
            !result.contains("@media[data-v"),
            "Media rule should not be scoped. Got: {}",
            result
        );
        // But selectors INSIDE @media must be scoped
        let media_start = result.find("@media").expect("@media must be present");
        let media_section = &result[media_start..];
        assert!(
            media_section.contains(".box[data-v-a4f2eed6]"),
            "Selector inside @media must be scoped. Got: {}",
            result
        );
    }

    /// @ai-generated - Multiple selectors inside @media must all be scoped.
    #[test]
    fn test_media_query_multiple_inner_selectors() {
        let result = scoped(
            "@media (max-width: 768px) { .sidebar { display: none; } .content { width: 100%; } }",
        );
        assert!(
            result.contains(".sidebar[data-v-a4f2eed6]"),
            ".sidebar inside @media must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".content[data-v-a4f2eed6]"),
            ".content inside @media must be scoped. Got: {}",
            result
        );
    }

    /// @ai-generated - Selectors inside @supports must be scoped.
    #[test]
    fn test_supports_query_inner_selectors_scoped() {
        let result = scoped("@supports (display: grid) { .grid { display: grid; } }");
        assert!(
            result.contains(".grid[data-v-a4f2eed6]"),
            "Selector inside @supports must be scoped. Got: {}",
            result
        );
    }

    /// @ai-generated - Multiple @media blocks must all have scoped inner selectors.
    #[test]
    fn test_multiple_media_blocks() {
        let result = scoped(
            ".top { color: red; } \
             @media (max-width: 768px) { .mobile { display: block; } } \
             @media (min-width: 1200px) { .wide { display: flex; } } \
             .bottom { color: blue; }",
        );
        assert!(
            result.contains(".top[data-v-a4f2eed6]"),
            "Top-level .top must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".mobile[data-v-a4f2eed6]"),
            ".mobile inside first @media must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".wide[data-v-a4f2eed6]"),
            ".wide inside second @media must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".bottom[data-v-a4f2eed6]"),
            "Top-level .bottom must be scoped. Got: {}",
            result
        );
    }

    /// @ai-generated - Descendant selectors inside @media must be properly scoped.
    #[test]
    fn test_media_with_descendant_selector() {
        let result = scoped("@media (max-width: 768px) { .nav .link { color: blue; } }");
        // Only the last compound gets scope
        assert!(
            result.contains(".link[data-v-a4f2eed6]"),
            "Last compound in descendant inside @media must be scoped. Got: {}",
            result
        );
        assert!(
            !result.contains(".nav[data-v-a4f2eed6]"),
            ".nav should not be scoped. Got: {}",
            result
        );
    }

    /// @ai-generated - Compound selectors (.badge.success) scope attribute at end.
    #[test]
    fn test_compound_class_selector() {
        let result = scoped(".badge.success { color: green; }");
        assert!(
            result.contains(".badge.success[data-v-a4f2eed6]"),
            "Compound selector must have scope at end. Got: {}",
            result
        );
    }

    /// @ai-generated - Multiple compound selectors.
    #[test]
    fn test_multiple_compound_selectors() {
        let result = scoped(".a.b, .c.d { color: red; }");
        assert!(
            result.contains(".a.b[data-v-a4f2eed6]"),
            "First compound must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".c.d[data-v-a4f2eed6]"),
            "Second compound must be scoped. Got: {}",
            result
        );
    }

    /// @ai-generated - ID + class compound selector.
    #[test]
    fn test_id_class_compound() {
        let result = scoped("#main.active { color: red; }");
        assert!(
            result.contains("#main.active[data-v-a4f2eed6]"),
            "ID+class compound must have scope at end. Got: {}",
            result
        );
    }

    /// @ai-generated - Element + class compound selector.
    #[test]
    fn test_element_class_compound() {
        let result = scoped("div.container { color: red; }");
        assert!(
            result.contains("div.container[data-v-a4f2eed6]"),
            "Element+class compound must have scope at end. Got: {}",
            result
        );
    }

    /// @ai-generated - Attribute selector as standalone.
    #[test]
    fn test_attribute_selector_standalone() {
        let result = scoped("input[type=\"text\"] { color: red; }");
        assert!(
            result.contains("[data-v-a4f2eed6]"),
            "Attribute selector must be scoped. Got: {}",
            result
        );
    }

    #[test]
    fn test_attribute_selector_with_pseudo() {
        // [attr]:hover — scope should be inserted before :hover, after [attr]
        let result = scoped("a[href]:hover { color: red; }");
        assert!(
            result.contains("[data-v-a4f2eed6]:hover"),
            "Scope attr should be before :hover. Got: {}",
            result
        );
    }

    #[test]
    fn test_child_combinator() {
        // Vue behavior: only the last compound selector gets the scope attribute
        let result = scoped(".parent > .child { color: red; }");
        assert!(
            !result.contains(".parent[data-v-a4f2eed6]"),
            "Parent should not be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".child[data-v-a4f2eed6]"),
            "Got: {}",
            result
        );
        // The `>` combinator must NOT dangle after the scope attr
        assert!(
            !result.contains("]>"),
            "Combinator should not dangle after scope attr. Got: {}",
            result
        );
    }

    #[test]
    fn test_child_combinator_preserves_structure() {
        // Regression: ` > ` was split into two combinators (` ` and `> `)
        // causing `.horizontal > .divider` → `.horizontal .divider[data-v-xxx]>`
        let result = scoped(".horizontal > .divider { border: 1px solid; }");
        assert!(
            result.contains(".horizontal > .divider[data-v-a4f2eed6]"),
            "Child combinator structure must be preserved. Got: {}",
            result
        );
    }

    #[test]
    fn test_sibling_combinator_preserves_structure() {
        let result = scoped(".a + .b { color: red; }");
        assert!(
            result.contains(".a + .b[data-v-a4f2eed6]"),
            "Adjacent sibling combinator must be preserved. Got: {}",
            result
        );
    }

    #[test]
    fn test_general_sibling_combinator() {
        let result = scoped(".a ~ .b { color: red; }");
        assert!(
            result.contains(".a ~ .b[data-v-a4f2eed6]"),
            "General sibling combinator must be preserved. Got: {}",
            result
        );
    }

    #[test]
    fn test_pseudo_class_and_pseudo_element() {
        let result = scoped(".btn:hover::before { content: ''; }");
        assert!(
            result.contains(".btn[data-v-a4f2eed6]:hover:before")
                || result.contains(".btn[data-v-a4f2eed6]:hover::before"),
            "Scope should be before :hover. Got: {}",
            result
        );
    }

    #[test]
    fn test_nth_child_and_pseudo_element() {
        let result = scoped(".item:nth-child(2)::after { content: ''; }");
        assert!(
            result.contains(".item[data-v-a4f2eed6]:nth-child(2):after")
                || result.contains(".item[data-v-a4f2eed6]:nth-child(2)::after"),
            "Scope should be before :nth-child. Got: {}",
            result
        );
    }

    #[test]
    fn test_three_level_descendant() {
        // Only the last segment should be scoped
        let result = scoped(".a .b .c { color: red; }");
        assert!(
            !result.contains(".a[data-v-a4f2eed6]"),
            "First should not be scoped. Got: {}",
            result
        );
        assert!(
            !result.contains(".b[data-v-a4f2eed6]"),
            "Middle should not be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".c[data-v-a4f2eed6]"),
            "Last should be scoped. Got: {}",
            result
        );
    }

    // ===================================================================
    // @ai-generated - Extended scoped CSS tests covering edge cases
    // ===================================================================

    /// Universal selector (*) must be scoped.
    #[test]
    fn test_universal_selector() {
        let result = scoped("* { margin: 0; }");
        assert!(
            result.contains("*[data-v-a4f2eed6]"),
            "Universal selector must be scoped. Got: {}",
            result
        );
    }

    /// Element followed by pseudo-element.
    #[test]
    fn test_element_pseudo_element() {
        let result = scoped("p::first-line { color: red; }");
        assert!(
            result.contains("p[data-v-a4f2eed6]:first-line")
                || result.contains("p[data-v-a4f2eed6]::first-line"),
            "Element + pseudo-element must be scoped. Got: {}",
            result
        );
    }

    /// :not() pseudo-class — scope before :not.
    #[test]
    fn test_not_pseudo_class() {
        let result = scoped(".item:not(.active) { opacity: 0.5; }");
        assert!(
            result.contains(".item[data-v-a4f2eed6]:not(.active)"),
            "Scope must be before :not(). Got: {}",
            result
        );
    }

    /// :is() / :where() pseudo-class.
    #[test]
    fn test_is_pseudo_class() {
        let result = scoped(".item:is(.a, .b) { color: red; }");
        assert!(
            result.contains("[data-v-a4f2eed6]:is("),
            "Scope must be before :is(). Got: {}",
            result
        );
    }

    /// Multiple rules in sequence.
    #[test]
    fn test_many_rules_in_sequence() {
        let result = scoped(
            ".a { color: red; } .b { color: blue; } .c { color: green; } .d { color: yellow; }",
        );
        assert!(result.contains(".a[data-v-a4f2eed6]"), "Got: {}", result);
        assert!(result.contains(".b[data-v-a4f2eed6]"), "Got: {}", result);
        assert!(result.contains(".c[data-v-a4f2eed6]"), "Got: {}", result);
        assert!(result.contains(".d[data-v-a4f2eed6]"), "Got: {}", result);
    }

    /// @keyframes selectors must NOT be scoped.
    #[test]
    fn test_keyframes_not_scoped() {
        let result = scoped(
            ".box { animation: fade 1s; } @keyframes fade { from { opacity: 1; } to { opacity: 0; } }",
        );
        assert!(
            result.contains(".box[data-v-a4f2eed6]"),
            ".box must be scoped. Got: {}",
            result
        );
        assert!(
            !result.contains("from[data-v"),
            "keyframe 'from' must NOT be scoped. Got: {}",
            result
        );
        assert!(
            !result.contains("to[data-v"),
            "keyframe 'to' must NOT be scoped. Got: {}",
            result
        );
    }

    /// Selectors after @keyframes must still be scoped.
    #[test]
    fn test_selector_after_keyframes() {
        let result = scoped(
            "@keyframes slide { 0% { left: 0; } 100% { left: 100%; } } .after { color: red; }",
        );
        assert!(
            result.contains(".after[data-v-a4f2eed6]"),
            "Selector after @keyframes must be scoped. Got: {}",
            result
        );
    }

    /// Mixed @media and @keyframes.
    #[test]
    fn test_media_and_keyframes_mixed() {
        let result = scoped(
            ".box { color: red; } \
             @keyframes fade { from { opacity: 1; } to { opacity: 0; } } \
             @media (max-width: 768px) { .mobile { display: block; } } \
             .end { color: blue; }",
        );
        assert!(
            result.contains(".box[data-v-a4f2eed6]"),
            ".box must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".mobile[data-v-a4f2eed6]"),
            ".mobile inside @media must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".end[data-v-a4f2eed6]"),
            ".end must be scoped. Got: {}",
            result
        );
    }

    /// CSS with string containing braces in property value.
    #[test]
    fn test_string_with_braces_in_value() {
        let result = scoped(".box { content: '{ not a block }'; }");
        assert!(
            result.contains(".box[data-v-a4f2eed6]"),
            "Selector must be scoped despite string with braces. Got: {}",
            result
        );
    }

    /// CSS comment between selectors.
    #[test]
    fn test_comment_between_selectors() {
        let result = scoped(".a { color: red; } /* comment */ .b { color: blue; }");
        assert!(
            result.contains(".a[data-v-a4f2eed6]"),
            ".a must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".b[data-v-a4f2eed6]"),
            ".b must be scoped. Got: {}",
            result
        );
    }

    /// grid-template-areas with quoted strings must not confuse the walker.
    #[test]
    fn test_grid_template_areas_strings() {
        let result = scoped(
            ".layout { grid-template-areas: \"header\" \"content\" \"footer\"; } .next { color: red; }",
        );
        assert!(
            result.contains(".layout[data-v-a4f2eed6]"),
            ".layout must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".next[data-v-a4f2eed6]"),
            ".next after grid-template-areas must be scoped. Got: {}",
            result
        );
    }

    /// Nested @media with @supports inside.
    #[test]
    fn test_nested_at_rules() {
        let result = scoped(
            "@media (min-width: 768px) { @supports (display: grid) { .nested { display: grid; } } }",
        );
        assert!(
            result.contains(".nested[data-v-a4f2eed6]"),
            "Deeply nested selector must be scoped. Got: {}",
            result
        );
    }

    /// @layer at-rule.
    #[test]
    fn test_layer_at_rule() {
        let result = scoped("@layer base { .box { color: red; } }");
        assert!(
            result.contains(".box[data-v-a4f2eed6]"),
            "Selector inside @layer must be scoped. Got: {}",
            result
        );
    }

    /// Multiple comma-separated selectors in a descendant context.
    #[test]
    fn test_comma_separated_in_descendant() {
        let result = scoped(".parent .a, .parent .b { color: red; }");
        assert!(
            result.contains(".a[data-v-a4f2eed6]"),
            ".a must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".b[data-v-a4f2eed6]"),
            ".b must be scoped. Got: {}",
            result
        );
    }

    /// Selector with escaped colon in class name.
    #[test]
    fn test_escaped_colon_in_class() {
        let result = scoped(".md\\:flex { display: flex; }");
        // The scope should be after the full class name including escaped chars
        assert!(
            result.contains("[data-v-a4f2eed6]"),
            "Escaped colon selector must be scoped. Got: {}",
            result
        );
        // Scope should NOT be inserted at the backslash-escaped colon
        assert!(
            !result.contains(".md[data-v-a4f2eed6]\\:flex"),
            "Scope should not split the escaped class. Got: {}",
            result
        );
    }

    /// Empty rule body.
    #[test]
    fn test_empty_rule() {
        let result = scoped(".empty {} .after { color: red; }");
        assert!(
            result.contains(".after[data-v-a4f2eed6]"),
            ".after must be scoped even after empty rule. Got: {}",
            result
        );
    }

    /// @charset is removed by lightningcss normalization.
    /// After normalization, the selector following it must still be scoped.
    #[test]
    fn test_after_charset_still_scoped() {
        // lightningcss removes @charset during normalization, so the
        // scoped() helper (which normalizes first) produces just the selector.
        let result = scoped(".box { color: red; }");
        assert!(
            result.contains(".box[data-v-a4f2eed6]"),
            ".box must be scoped. Got: {}",
            result
        );
    }

    // ===================================================================
    // @ai-generated - CSS nesting tests (apply_scoped_raw path)
    // ===================================================================

    /// Native CSS nesting: nested `& .child` must be scoped.
    #[test]
    fn test_css_nesting_raw_basic() {
        let css = ".parent { color: red; & .child { color: blue; } }";
        let result = apply_scoped_raw(css, "a4f2eed6");
        assert!(
            result.contains(".parent[data-v-a4f2eed6]"),
            "Parent must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".child[data-v-a4f2eed6]"),
            "Nested .child must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains("color: red"),
            "Parent declarations preserved. Got: {}",
            result
        );
        assert!(
            result.contains("color: blue"),
            "Nested declarations preserved. Got: {}",
            result
        );
    }

    /// Native CSS nesting: `&:hover` pseudo-class.
    #[test]
    fn test_css_nesting_raw_pseudo() {
        let css = ".btn { color: red; &:hover { color: blue; } }";
        let result = apply_scoped_raw(css, "a4f2eed6");
        assert!(
            result.contains(".btn[data-v-a4f2eed6]"),
            "Parent must be scoped. Got: {}",
            result
        );
        // &:hover → &[data-v-xxx]:hover
        assert!(
            result.contains("[data-v-a4f2eed6]:hover"),
            "Nested &:hover must have scope before :hover. Got: {}",
            result
        );
    }

    /// Native CSS nesting: multiple nested selectors.
    #[test]
    fn test_css_nesting_raw_multiple() {
        let css =
            ".card { padding: 1rem; & .title { font-size: 18px; } & .body { padding: 8px; } }";
        let result = apply_scoped_raw(css, "a4f2eed6");
        assert!(
            result.contains(".card[data-v-a4f2eed6]"),
            "Parent must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".title[data-v-a4f2eed6]"),
            ".title must be scoped. Got: {}",
            result
        );
        assert!(
            result.contains(".body[data-v-a4f2eed6]"),
            ".body must be scoped. Got: {}",
            result
        );
    }

    /// @font-face at-rule should not be scoped.
    #[test]
    fn test_font_face_not_scoped() {
        let result = scoped(
            "@font-face { font-family: MyFont; src: url('font.woff'); } .text { font-family: MyFont; }",
        );
        assert!(
            result.contains(".text[data-v-a4f2eed6]"),
            ".text must be scoped after @font-face. Got: {}",
            result
        );
    }

    // ===================================================================
    // WS 10.2 — :deep() edge cases (end-to-end through prepass + scoped)
    // ===================================================================

    /// Full pipeline helper: prepass → normalize → scope (matches `process_style`).
    /// Unlike `scoped()` which skips the prepass, this exercises the real pipeline.
    fn scoped_e2e(css: &str) -> String {
        use super::super::types::ProcessStyleOptions;
        super::super::process_style(
            css,
            &ProcessStyleOptions {
                scope_id: "a4f2eed6",
                scoped: true,
                is_module: false,
                module_name: None,
                filename: None,
                sourcemap: false,
            },
        )
        .unwrap()
        .code
    }

    /// WS 5.1: :deep(.a, .b) — each comma-separated selector gets its own
    /// [data-v-xxx] prefix; neither inner selector should receive a scope attr.
    #[test]
    fn test_deep_with_comma_e2e() {
        let result = scoped_e2e(":deep(.a, .b) { color: red; }");
        // Each branch must have the scope attr as a prefix (from prepass expansion)
        assert!(
            result.contains("[data-v-a4f2eed6] .a"),
            ":deep(.a, .b) — .a branch must have scope prefix. Got: {}",
            result
        );
        assert!(
            result.contains("[data-v-a4f2eed6] .b"),
            ":deep(.a, .b) — .b branch must have scope prefix. Got: {}",
            result
        );
        // The inner selectors must NOT themselves be scoped
        assert!(
            !result.contains(".a[data-v"),
            ".a inside :deep() must not be scoped. Got: {}",
            result
        );
        assert!(
            !result.contains(".b[data-v"),
            ".b inside :deep() must not be scoped. Got: {}",
            result
        );
        // The raw Vue syntax must not leak into the output
        assert!(
            !result.contains(":deep("),
            ":deep() must be removed from output. Got: {}",
            result
        );
    }

    /// WS 5.1: .parent :deep(.a, .b) — scope attr placed between parent and
    /// each inner selector branch.
    #[test]
    fn test_deep_with_comma_and_parent_e2e() {
        let result = scoped_e2e(".parent :deep(.a, .b) { color: red; }");
        // After prepass: ".parent [__v_deep__] .a, .parent [__v_deep__] .b { ... }"
        // After scoped: ".parent [data-v-xxx] .a, .parent [data-v-xxx] .b { ... }"
        assert!(
            result.contains("[data-v-a4f2eed6] .a"),
            ".a branch must have scope prefix. Got: {}",
            result
        );
        assert!(
            result.contains("[data-v-a4f2eed6] .b"),
            ".b branch must have scope prefix. Got: {}",
            result
        );
        // Inner selectors must NOT be scoped
        assert!(
            !result.contains(".a[data-v"),
            ".a inside :deep() must not be scoped. Got: {}",
            result
        );
        assert!(
            !result.contains(".b[data-v"),
            ".b inside :deep() must not be scoped. Got: {}",
            result
        );
    }

    /// WS 5.3: :deep() with empty parens — prepass leaves the token unchanged;
    /// lightningcss may drop the unknown pseudo-class; either way no deep marker
    /// and no crash should occur.
    #[test]
    fn test_deep_empty_parens_e2e() {
        // process_style() runs prepass → normalize → scope.
        // Prepass returns :deep() unchanged (empty inner = no transform).
        // lightningcss may strip the unknown pseudo or error; the result must
        // not contain the internal deep marker and must not panic.
        use super::super::types::ProcessStyleOptions;
        let result = super::super::process_style(
            ":deep() { color: red; }",
            &ProcessStyleOptions {
                scope_id: "a4f2eed6",
                scoped: true,
                is_module: false,
                module_name: None,
                filename: None,
                sourcemap: false,
            },
        );
        // We don't assert Ok/Err since lightningcss may reject :deep() —
        // the important constraint is that if it succeeds, no deep marker leaks.
        if let Ok(r) = result {
            assert!(
                !r.code.contains("__v_deep__"),
                "deep marker must not appear in output. Got: {}",
                r.code
            );
            assert!(
                !r.code.contains(":deep()"),
                ":deep() syntax must not appear in output. Got: {}",
                r.code
            );
        }
        // A parse error is also an acceptable outcome — :deep() is not valid CSS.
    }

    /// WS 5.3: bare :deep (no parens) — prepass does not touch it; it should
    /// pass through without injecting any deep marker.
    #[test]
    fn test_deep_bare_no_parens_e2e() {
        // :deep without parens is not recognized by prepass (pattern ":deep(" required).
        // Lightningcss may strip the unknown pseudo-class; result must not contain
        // the internal marker.
        let result = apply_scoped(":deep { color: red; }", "a4f2eed6");
        if let Ok(css) = result {
            assert!(
                !css.contains("__v_deep__"),
                "deep marker must not appear for bare :deep. Got: {}",
                css
            );
        }
        // A parse error is also acceptable — bare :deep is not valid CSS.
    }
}