oj_css 0.2.35

CSS pipeline: Lightning CSS transforms, CSS Modules scoping
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
//! `url()` / `@import` rewriting: lightningcss placeholders for a compile,
//! Vite's text rewrite for inlined imports.

use std::collections::HashMap;
use std::path::Path;
use std::sync::LazyLock;

use lightningcss::dependencies::Dependency;
use regex::Regex;

use crate::path::{is_external, join_relative, normalize, posix_join, relative_path, split_query};
use crate::resolve::CssResolve;

/// Rewrite the relative urls of a stylesheet in `from_dir` so they are
/// correct from `to_dir`, where it is being inlined. Text-based like Vite's
/// `rebaseUrls`: `url()`, `@import "x.css"` and `image-set()` strings.
pub(crate) fn rebase_to_dir(
    css: &str,
    from_dir: &Path,
    to_dir: &Path,
    resolve: &CssResolve<'_>,
) -> String {
    if from_dir == to_dir {
        return css.to_string();
    }
    let base = relative_path(to_dir, from_dir);
    let rebase = |url: &str| -> Option<String> {
        // Aliased specs keep their spelling for the entry's own resolution.
        if rebase_relative(url, "/x").is_none() || resolve.alias_spec(url).is_some() {
            return None;
        }
        let (path, suffix) = split_query(url);
        Some(format!("{}{suffix}", join_relative(&base, path)))
    };
    let mut out = css.to_string();
    if out.contains("@import") {
        out = rewrite_import_css(&out, &rebase);
    }
    if out.contains("url(") {
        out = rewrite_css_urls(&out, &rebase);
    }
    if out.contains("image-set(") {
        out = rewrite_image_set_strings(&out, &rebase);
    }
    out
}

type Rebase<'a> = dyn Fn(&str) -> Option<String> + 'a;

/// Vite's `cssUrlRE` minus its lookbehinds, which are checked by hand.
static URL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"url\((\s*('[^']+'|"[^"]+")\s*|(?:\\.|[^'")\\])+)\)"#).unwrap());
/// Vite's `importCssRE`.
static IMPORT_CSS_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)"#).unwrap()
});
/// Vite's `cssImageSetRE`. JS `\w` is ASCII; a Unicode `\w{1,256}` is too
/// big to compile.
static IMAGE_SET_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"image-set\(((?:[A-Za-z0-9_-]{1,256}\([^)]*\)|[^)])*)\)"#).unwrap()
});

/// `css` with each match of `re` replaced by `f(match, match start)` (None
/// keeps it). Plain matches, no capture groups: those need the slower engine.
fn replace_matches(
    css: &str,
    re: &Regex,
    mut f: impl FnMut(&str, usize) -> Option<String>,
) -> String {
    let mut out = String::with_capacity(css.len());
    let mut copied = 0;
    for m in re.find_iter(css) {
        if let Some(replacement) = f(m.as_str(), m.start()) {
            out.push_str(&css[copied..m.start()]);
            out.push_str(&replacement);
            copied = m.end();
        }
    }
    out.push_str(&css[copied..]);
    out
}

fn rewrite_css_urls(css: &str, rebase: &Rebase<'_>) -> String {
    replace_matches(css, &URL_RE, |m, start| {
        let before = &css[..start];
        // `(?<=^|[^\w\-\u0080-\uffff])`: not the tail of a longer name.
        let ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-' || !c.is_ascii();
        if before.chars().next_back().is_some_and(ident) {
            return None;
        }
        // `(?<!@import\s+)`: an import's url is the import rewrite's business.
        let trimmed = before.trim_end();
        if trimmed.len() < before.len() && trimmed.ends_with("@import") {
            return None;
        }
        let inner = &m["url(".len()..m.len() - 1];
        url_replace(inner.trim(), rebase).map(|(wrap, url)| format!("url({wrap}{url}{wrap})"))
    })
}

fn rewrite_import_css(css: &str, rebase: &Rebase<'_>) -> String {
    replace_matches(css, &IMPORT_CSS_RE, |m, _| {
        let spec = m["@import".len()..].trim_start();
        let (prefix, spec) = match spec.strip_prefix("url(") {
            Some(rest) => ("url(", rest),
            None => ("", spec),
        };
        let (wrap, unquoted) = unquote(spec);
        if skip_url(unquoted) {
            return None;
        }
        let url = rebase(unquoted)?;
        Some(format!("@import {prefix}{wrap}{url}{wrap}"))
    })
}

/// The bare `"x" 1x` candidates of `image-set()`; its `url()` ones were
/// already rewritten.
fn rewrite_image_set_strings(css: &str, rebase: &Rebase<'_>) -> String {
    replace_matches(css, &IMAGE_SET_RE, |m, _| {
        let body = &m["image-set(".len()..m.len() - 1];
        let mut out = String::with_capacity(body.len());
        let mut depth = 0usize;
        let mut chars = body.char_indices();
        let mut changed = false;
        while let Some((i, c)) = chars.next() {
            match c {
                '(' => depth += 1,
                ')' => depth = depth.saturating_sub(1),
                '"' | '\'' if depth == 0 => {
                    if let Some(close) = body[i + 1..].find(c) {
                        let raw = &body[i..i + close + 2];
                        if let Some((wrap, url)) = url_replace(raw, rebase) {
                            let wrap = if wrap.is_empty() { "\"" } else { wrap };
                            out.push_str(&format!("{wrap}{url}{wrap}"));
                            changed = true;
                        } else {
                            out.push_str(raw);
                        }
                        for _ in 0..raw.chars().count() - 1 {
                            chars.next();
                        }
                        continue;
                    }
                }
                _ => {}
            }
            out.push(c);
        }
        changed.then(|| format!("image-set({out})"))
    })
}

/// Vite's `rewriteCssImageSet` (its url-rewrite PostCSS plugin): each
/// candidate of `image-set()` through `rebase`, a bare string one wrapped in
/// `url()`, gradients and other images left alone, the list re-joined.
pub(crate) fn rewrite_css_image_set(css: &str, rebase: &Rebase<'_>) -> String {
    static NOT_PROCESSED_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?:gradient|element|cross-fade|image)\(").unwrap());
    replace_matches(css, &IMAGE_SET_RE, |m, _| {
        let body = &m["image-set(".len()..m.len() - 1];
        let candidates: Vec<String> = parse_srcset(body)
            .into_iter()
            .map(|(url, descriptor)| {
                let url = if URL_RE.is_match(&url) {
                    rewrite_css_urls(&url, rebase)
                } else if !NOT_PROCESSED_RE.is_match(&url) {
                    match url_replace(&url, rebase) {
                        Some((wrap, new)) => format!("url({wrap}{new}{wrap})"),
                        None => url,
                    }
                } else {
                    url
                };
                if descriptor.is_empty() {
                    url
                } else {
                    format!("{url} {descriptor}")
                }
            })
            .collect();
        Some(format!("image-set({})", candidates.join(", ")))
    })
}

/// Vite's `parseSrcset`: `(url, descriptor)` per image candidate.
fn parse_srcset(srcset: &str) -> Vec<(String, String)> {
    static ESCAPED_SPACES: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?: |\\t|\\n|\\f|\\r)+").unwrap());
    static NEWLINE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\r?\n").unwrap());
    static COMMA_SPACE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r",\s+").unwrap());
    static SPACES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
    // Vite's `imageCandidateRegex`, whose `(?<=,)` start is where the previous
    // match (ending at its comma) left off.
    static CANDIDATE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?:^|\s)?(?P<url>[A-Za-z0-9_-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?P<descriptor>[A-Za-z0-9_][^,]+))?(?:,|$)"#,
        )
        .unwrap()
    });
    let s = ESCAPED_SPACES.replace_all(srcset.trim(), " ");
    let s = NEWLINE.replacen(&s, 1, "");
    let s = COMMA_SPACE.replacen(&s, 1, ", ");
    let s = SPACES.replace_all(&s, " ");
    CANDIDATE
        .captures_iter(&s)
        .map(|c| {
            let field = |name| c.name(name).map_or("", |m| m.as_str().trim()).to_string();
            (field("url"), field("descriptor"))
        })
        .filter(|(url, _)| !url.is_empty())
        .collect()
}

/// A `style` attribute's declarations with their urls rewritten like Vite's
/// url-rewrite PostCSS plugin does in dev: `url()`s, then `image-set()`
/// candidates, rebased as in a sheet served at `url`. Text only, as under
/// Vite's default PostCSS transformer, so the declarations stay as written.
pub fn rewrite_style_attribute_dev(url: &str, code: &str, resolve: &CssResolve<'_>) -> String {
    let Some(base) = css_base_dir(url) else {
        return code.to_string();
    };
    let rebase = |spec: &str| Some(dev_url_of(spec, &base, resolve));
    let mut out = code.to_string();
    if URL_RE.is_match(&out) {
        out = rewrite_css_urls(&out, &rebase);
    }
    if IMAGE_SET_RE.is_match(&out) {
        out = rewrite_css_image_set(&out, &rebase);
    }
    out
}

/// Vite's `doUrlReplace`: the new url and the quote to wrap it in, or None to
/// keep the original.
fn url_replace(raw: &str, rebase: &Rebase<'_>) -> Option<(&'static str, String)> {
    let (wrap, unquoted) = unquote(raw);
    if skip_url(unquoted) {
        return None;
    }
    let mut url = rebase(&unescape(unquoted))?;
    let mut wrap = wrap;
    if wrap.is_empty() && (needs_uri_encoding(&url) || url.contains(')')) {
        wrap = "\"";
    }
    if wrap == "'" && url.contains('\'') {
        wrap = "\"";
    }
    if wrap == "\"" && url.contains('"') {
        url = escape_double_quotes(&url);
    }
    Some((wrap, url))
}

fn unquote(raw: &str) -> (&'static str, &str) {
    match raw.as_bytes() {
        [b'"', .., b'"'] if raw.len() >= 2 => ("\"", &raw[1..raw.len() - 1]),
        [b'\'', .., b'\''] if raw.len() >= 2 => ("'", &raw[1..raw.len() - 1]),
        _ => ("", raw),
    }
}

/// Vite's `skipUrlReplacer`: external, data, `#fragment` and `fn(...)` urls.
fn skip_url(url: &str) -> bool {
    let function_call = url.find('(').is_some_and(|i| {
        let name = &url[..i];
        name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
            && name
                .chars()
                .all(|c| c.is_alphanumeric() || matches!(c, '_' | '.' | '-'))
    });
    is_external(url)
        || url.trim_start().starts_with("data:")
        || url.starts_with('#')
        || function_call
}

/// `\(\W)` -> `$1`.
fn unescape(url: &str) -> String {
    let mut out = String::with_capacity(url.len());
    let mut chars = url.chars().peekable();
    while let Some(c) = chars.next() {
        match chars.peek() {
            Some(&n) if c == '\\' && !(n.is_alphanumeric() || n == '_') => {
                out.push(n);
                chars.next();
            }
            _ => out.push(c),
        }
    }
    out
}

/// Whether `encodeURI` would change `url`.
fn needs_uri_encoding(url: &str) -> bool {
    !url.chars()
        .all(|c| c.is_ascii_alphanumeric() || ";,/?:@&=+$-_.!~*'()#".contains(c))
}

/// `"` not already escaped, escaped.
fn escape_double_quotes(url: &str) -> String {
    let mut out = String::with_capacity(url.len() + 2);
    let mut prev = '\0';
    for c in url.chars() {
        if c == '"' && prev != '\\' {
            out.push('\\');
        }
        out.push(c);
        prev = c;
    }
    out
}

/// Swap every printed placeholder for `rewrite(original url)`.
pub(crate) fn rewrite_dependencies(
    code: String,
    deps: Vec<Dependency>,
    mut rewrite: impl FnMut(String) -> String,
) -> String {
    let pairs: Vec<(String, String)> = deps
        .into_iter()
        .map(|dep| {
            let (placeholder, url) = match dep {
                Dependency::Url(u) => (u.placeholder, u.url),
                Dependency::Import(i) => (i.placeholder, i.url),
            };
            (placeholder, rewrite(url))
        })
        .collect();
    substitute_placeholders(code, &pairs)
}

/// The url directory a server url lives in (`/src/app.css` -> `/src`).
pub(crate) fn css_base_dir(url: &str) -> Option<String> {
    let path = split_query(url).0;
    if !path.starts_with('/') {
        return None;
    }
    let i = path.rfind('/')?;
    Some(if i == 0 { "/".into() } else { path[..i].into() })
}

/// The server url a spec in a stylesheet served from `base_dir` stands for:
/// an alias becomes the file's url, a relative path joins `base_dir`, the
/// rest (root-absolute, external, data:) is kept. Like Vite's dev url
/// resolver, a relative path is rewritten only when it names a file: one that
/// resolves nowhere (a missing file, a sheet whose url has no directory on
/// disk, such as a page's with no file) stays as written.
pub(crate) fn dev_url_of(spec: &str, base_dir: &str, resolve: &CssResolve<'_>) -> String {
    let (path, suffix) = split_query(spec);
    if let Some(file) = resolve.alias_path(path) {
        return format!("{}{suffix}", resolve.dev_url(&file));
    }
    match rebase_relative(spec, base_dir) {
        Some(url) if relative_resolves(path, base_dir, resolve) => url,
        _ => spec.to_string(),
    }
}

/// Whether relative `path` names a file from the directory `base_dir` is
/// served from. Without a root there is no disk to ask, and it is assumed to.
fn relative_resolves(path: &str, base_dir: &str, resolve: &CssResolve<'_>) -> bool {
    let Some(root) = resolve.root else {
        return true;
    };
    let dir = match base_dir.strip_prefix("/@fs") {
        Some(abs) if abs.starts_with('/') => Path::new(abs).to_path_buf(),
        _ => root.join(base_dir.trim_start_matches('/')),
    };
    // Vite resolves `decodeURI(url)` minus its `#fragment`.
    let path = path.split('#').next().unwrap_or(path);
    normalize(&dir.join(percent_decode(path))).is_file()
}

/// `decodeURI` for a path: `%XX` escapes decoded, a malformed one kept.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
                out.push(h << 4 | l);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8(out).unwrap_or_else(|_| s.to_string())
}

/// A relative spec joined onto `base_dir`; None for anything not relative.
fn rebase_relative(spec: &str, base_dir: &str) -> Option<String> {
    if spec.is_empty() || spec.starts_with(['/', '#']) || is_external(spec) {
        return None;
    }
    let (path, suffix) = split_query(spec);
    Some(format!("{}{suffix}", posix_join(base_dir, path)))
}

/// Replace dependency placeholders in one left-to-right pass. The printer
/// always emits a placeholder quoted (`url("PH")`, `@import "PH"`, `"PH" 1x`
/// in `image-set()`), so only text between a `"` and the next is looked up.
/// The first replacement for a repeated placeholder wins; replacements are
/// not re-scanned.
pub(crate) fn substitute_placeholders(code: String, pairs: &[(String, String)]) -> String {
    if pairs.is_empty() {
        return code;
    }
    let mut map: HashMap<&str, &str> = HashMap::with_capacity(pairs.len());
    for (p, r) in pairs {
        if !p.is_empty() {
            map.entry(p.as_str()).or_insert(r.as_str());
        }
    }
    let extra: usize = pairs
        .iter()
        .map(|(p, r)| r.len().saturating_sub(p.len()))
        .sum();
    let mut out = String::with_capacity(code.len() + extra);
    let mut copied = 0; // start of the text not yet appended to `out`
    let mut scan = 0; // where the next `"` search begins
    while let Some(q) = code[scan..].find('"') {
        let start = scan + q + 1;
        let Some(n) = code[start..].find('"') else {
            break;
        };
        let end = start + n;
        if let Some(r) = map.get(&code[start..end]) {
            out.push_str(&code[copied..start]);
            out.push_str(r);
            copied = end;
            scan = end + 1;
        } else {
            // The closing quote may open the next token.
            scan = start;
        }
    }
    out.push_str(&code[copied..]);
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::*;
    use lightningcss::dependencies::DependencyOptions;
    use lightningcss::printer::PrinterOptions;
    use lightningcss::stylesheet::{ParserOptions, StyleSheet};

    /// An app root holding `src/a.png`, `src/b.png`, `a.png` and
    /// `__preview/a.png`, with `@` aliased to its `src`.
    fn url_app(name: &str) -> (std::path::PathBuf, [(String, String); 1]) {
        let root = std::env::temp_dir().join(format!("oj-css-urls-{name}-{}", std::process::id()));
        for f in ["src/a.png", "src/b.png", "a.png", "__preview/a.png"] {
            let p = root.join(f);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(p, b"x").unwrap();
        }
        let alias = [("@".to_string(), root.join("src").display().to_string())];
        (root, alias)
    }

    /// Each pair is a `style` attribute of a page at `/index.html` and what
    /// Vite 8.2.1's dev transform writes for it, quotes unescaped.
    #[test]
    fn style_attribute_urls_rewrite_like_vites() {
        let (root, alias) = url_app("attr");
        let resolve = CssResolve {
            root: Some(&root),
            alias: &alias,
            ..CssResolve::default()
        };
        let cases = [
            (
                "background: url(./src/a.png)",
                "background: url(/src/a.png)",
            ),
            (
                r#"background: url('./src/a.png'), url("@/b.png")"#,
                r#"background: url('/src/a.png'), url("/src/b.png")"#,
            ),
            (
                r#"background-image: image-set("./src/a.png" 1x, './src/b.png' 2x)"#,
                r#"background-image: image-set(url("/src/a.png") 1x, url('/src/b.png') 2x)"#,
            ),
            (
                r#"background-image: image-set(url(./src/a.png) 1x, "@/b.png" type("image/png"))"#,
                r#"background-image: image-set(url(/src/a.png) 1x, url("/src/b.png") type("image/png"))"#,
            ),
            (
                r#"background-image: -webkit-image-set("./src/a.png" 1x); color: red"#,
                r#"background-image: -webkit-image-set(url("/src/a.png") 1x); color: red"#,
            ),
            (
                r#"background-image: image-set(linear-gradient(red, blue) 1x, "data:image/png;base64,AA" 2x, "https://x.dev/a.png" 3x)"#,
                r#"background-image: image-set(linear-gradient(red, blue) 1x, "data:image/png;base64,AA" 2x, "https://x.dev/a.png" 3x)"#,
            ),
            (
                r#"background: url(./src/b.png) no-repeat, image-set( "./src/a.png"   1x ,"./src/b.png" 2x )"#,
                r#"background: url(/src/b.png) no-repeat, image-set(url("/src/a.png") 1x, url("/src/b.png") 2x)"#,
            ),
            (
                r#"background: url(./missing.png), url(./src/a.png), url(./a.png), url("./src/a.png?v=1#x")"#,
                r#"background: url(./missing.png), url(/src/a.png), url(/a.png), url("/src/a.png?v=1#x")"#,
            ),
        ];
        for (attr, vite) in cases {
            let url = "/index.html?html-proxy&inline-css&style-attr&index=0.css";
            assert_eq!(
                rewrite_style_attribute_dev(url, attr, &resolve),
                vite,
                "{attr}"
            );
        }
        // A page with no file: nothing relative resolves, even `./a.png`
        // beside its path; an alias still does.
        let url = "/@id/__x00__/__preview/Card?html-proxy&inline-css&style-attr&index=0.css";
        assert_eq!(
            rewrite_style_attribute_dev(
                url,
                "background: url(./missing.png), url(./src/a.png), url(./a.png), url(@/a.png)",
                &resolve
            ),
            "background: url(./missing.png), url(./src/a.png), url(./a.png), url(/src/a.png)"
        );
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn a_sheets_image_set_strings_print_as_urls_like_vites() {
        let (root, _) = url_app("sheet");
        let resolve = CssResolve {
            root: Some(&root),
            ..CssResolve::default()
        };
        let src = r#".s { background-image: image-set("./a.png" 1x, url(./b.png) 2x) }"#;
        let css = compile_css_dev("/src/x.css", src, false, &resolve)
            .unwrap()
            .css;
        assert!(
            css.contains(r#"image-set(url("/src/a.png") 1x, url("/src/b.png") 2x)"#),
            "{css}"
        );
        std::fs::remove_dir_all(root).ok();
    }

    /// Vite's dev url resolver rewrites a relative url only when it resolves
    /// to a file; a missing one, or any in a sheet whose url has no directory
    /// on disk, stays as written.
    #[test]
    fn a_sheets_relative_urls_resolve_only_to_files() {
        let (root, _) = url_app("miss");
        let resolve = CssResolve {
            root: Some(&root),
            ..CssResolve::default()
        };
        let src = ".a { background: url(./a.png) } .m { background: url(./missing.png) }";
        let css = compile_css_dev("/src/x.css", src, false, &resolve)
            .unwrap()
            .css;
        assert!(css.contains(r#"url("/src/a.png")"#), "{css}");
        assert!(css.contains(r#"url("./missing.png")"#), "{css}");
        let css = compile_css_dev("/@id/__x00__virtual.css", src, false, &resolve)
            .unwrap()
            .css;
        assert!(css.contains(r#"url("./a.png")"#), "{css}");
        std::fs::remove_dir_all(root).ok();
    }

    /// The sequential `str::replace` loop `substitute_placeholders` replaced.
    fn sequential_replace(code: &str, pairs: &[(String, String)]) -> String {
        pairs
            .iter()
            .fold(code.to_string(), |c, (p, r)| c.replace(p, r))
    }

    fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
        list.iter()
            .map(|(p, r)| (p.to_string(), r.to_string()))
            .collect()
    }

    /// Every `"` followed by exactly six placeholder-alphabet bytes and a closing
    /// `"`: the shape of an unsubstituted lightningcss dependency placeholder
    /// (and of a six-character user string, which callers exclude by value).
    fn quoted_six_char_tokens(css: &str) -> Vec<&str> {
        let b = css.as_bytes();
        (0..b.len())
            .filter(|&i| {
                b[i] == b'"'
                    && i + 7 < b.len()
                    && b[i + 7] == b'"'
                    && b[i + 1..i + 7]
                        .iter()
                        .all(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'-')
            })
            .map(|i| &css[i + 1..i + 7])
            .collect()
    }

    #[test]
    fn substitute_placeholders_handles_edge_shapes() {
        // Empty pairs: the input comes back as-is, without a copy.
        let input = ".a{content:\"abcdef\"}".to_string();
        let (ptr, cap) = (input.as_ptr(), input.capacity());
        let same = substitute_placeholders(input, &[]);
        assert_eq!((same.as_ptr(), same.capacity()), (ptr, cap));
        assert_eq!(same, ".a{content:\"abcdef\"}");

        let cases = vec![
            ("", pairs(&[("abcdef", "/a.png")]), ""),
            (
                ".a{color:red}",
                pairs(&[("abcdef", "/a.png")]),
                ".a{color:red}",
            ),
            // Placeholder at byte 0 and as the final quoted token.
            (
                "\"abcdef\" .a{x:1}\"abcdef\"",
                pairs(&[("abcdef", "/a.png")]),
                "\"/a.png\" .a{x:1}\"/a.png\"",
            ),
            // Duplicate placeholder with two replacements: first wins, both occurrences replaced.
            (
                ".a{background:url(\"abcdef\")}.b{background:url(\"abcdef\")}",
                pairs(&[("abcdef", "/first.png"), ("abcdef", "/second.png")]),
                ".a{background:url(\"/first.png\")}.b{background:url(\"/first.png\")}",
            ),
            // Zero-occurrence placeholder and a same-length user string.
            (
                ".a{content:\"qqqqqq\";background:url(\"abcdef\")}",
                pairs(&[("zzzzzz", "/z.png"), ("abcdef", "/a.png")]),
                ".a{content:\"qqqqqq\";background:url(\"/a.png\")}",
            ),
            // Escaped quote inside a user string before a placeholder.
            (
                ".a{content:\"a\\\"b\";background:url(\"Ab-_09\")}",
                pairs(&[("Ab-_09", "/x/y.svg")]),
                ".a{content:\"a\\\"b\";background:url(\"/x/y.svg\")}",
            ),
            // Adjacent quoted tokens.
            (
                "\"P1P1P1\"\"P2P2P2\"",
                pairs(&[("P1P1P1", "/1"), ("P2P2P2", "/2")]),
                "\"/1\"\"/2\"",
            ),
            // Multibyte neighbours and a multibyte replacement.
            (
                ".a::before{content:\"héllo\";background:url(\"Ab-_09\")}",
                pairs(&[("Ab-_09", "/ünï/y.svg")]),
                ".a::before{content:\"héllo\";background:url(\"/ünï/y.svg\")}",
            ),
            // Empty replacement.
            (
                ".a{x:url(\"abcdef\")}",
                pairs(&[("abcdef", "")]),
                ".a{x:url(\"\")}",
            ),
        ];
        for (code, pairs, want) in cases {
            let got = substitute_placeholders(code.to_string(), &pairs);
            assert_eq!(got, want, "input {code:?}");
            assert_eq!(
                got,
                sequential_replace(code, &pairs),
                "diverges from the sequential loop on {code:?}"
            );
        }

        // An unterminated `"PH` at the end of the input is left as written.
        let code = ".a{background:url(\"abcdef\")}\"abcdef";
        let got = substitute_placeholders(code.to_string(), &pairs(&[("abcdef", "/a.png")]));
        assert_eq!(got, ".a{background:url(\"/a.png\")}\"abcdef");
    }

    #[test]
    fn substitute_placeholders_matches_sequential_replace_on_printed_css() {
        let src = "@import \"./x.css\";\n\
                   @font-face { font-family: F; src: url(\"./f.woff2\") format(\"woff2\"); }\n\
                   .a { background: url(./a.png); }\n\
                   .b { background: url(\"./b.png\"); }\n\
                   .c { background: url(./a.png); }\n\
                   .d { background: image-set(\"./a.png\" 1x, \"./b.png\" 2x); }\n\
                   .e { background: -webkit-image-set(url(\"./c.png\") 1x, url(\"./d.png\") 2x); }\n\
                   .f::before { content: \"abcdef\"; }\n\
                   .g::before { content: \"a\\\"b\"; }\n\
                   .h { background: url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg'/%3e\"); }\n";
        let stylesheet = StyleSheet::parse(
            src,
            ParserOptions {
                filename: "/src/x.css".into(),
                ..ParserOptions::default()
            },
        )
        .unwrap();
        let result = stylesheet
            .to_css(PrinterOptions {
                analyze_dependencies: Some(DependencyOptions::default()),
                ..PrinterOptions::default()
            })
            .unwrap();
        let deps = result.dependencies.unwrap();
        let pairs: Vec<(String, String)> = deps
            .into_iter()
            .map(|dep| match dep {
                Dependency::Url(u) => (u.placeholder, format!("/src/{}", u.url)),
                Dependency::Import(i) => (i.placeholder, format!("/src/{}", i.url)),
            })
            .collect();
        assert!(
            pairs.len() >= 9,
            "one Dependency per printed url/import: {pairs:?}"
        );
        assert!(pairs.iter().all(|(p, _)| p.len() == 6), "{pairs:?}");
        // One quoted placeholder per Dependency, plus the user string.
        assert_eq!(
            quoted_six_char_tokens(&result.code).len(),
            pairs.len() + 1,
            "{}",
            result.code
        );

        let got = substitute_placeholders(result.code.clone(), &pairs);
        assert_eq!(got, sequential_replace(&result.code, &pairs));
        // Only the same-width user string survives as a six-char quoted token.
        assert_eq!(quoted_six_char_tokens(&got), vec!["abcdef"], "{got}");
        assert!(
            got.contains("/src/./a.png")
                && got.contains("/src/./x.css")
                && got.contains("/src/./f.woff2"),
            "{got}"
        );
        assert!(
            got.contains("/src/data:image/svg+xml"),
            "the test maps every dependency, data: included: {got}"
        );
    }

    #[test]
    fn dev_compile_rewrites_a_url_used_twice_and_an_import() {
        // Distinct declarations keep the two rules from being merged by minify.
        let src = "@import \"./b.css\";\n\
                   .a { background: url(./a.png); color: red; }\n\
                   .b { background: url(\"./a.png\"); color: blue; }\n";
        let out = compile_css_dev("/src/x.css", src, false, &CssResolve::default())
            .unwrap()
            .css;
        assert_eq!(
            out.matches("url(\"/src/a.png\")").count(),
            2,
            "both occurrences rewritten: {out}"
        );
        assert!(out.contains("@import \"/src/b.css\""), "{out}");
        assert!(
            quoted_six_char_tokens(&out).is_empty(),
            "a placeholder survived substitution: {out}"
        );
    }

    #[test]
    fn rebase_to_dir_rewrites_like_vite_rebase_urls() {
        let resolve = CssResolveConfig {
            alias: vec![("@".into(), "/abs/src".into())],
            ..Default::default()
        };
        let rebase = |css: &str| {
            rebase_to_dir(
                css,
                Path::new("/p/src/base"),
                Path::new("/p/src"),
                &resolve.as_ref(),
            )
        };
        assert_eq!(
            rebase(".a{background:url(./x.png)}"),
            ".a{background:url(./base/x.png)}"
        );
        assert_eq!(
            rebase(".a{background:url( 'x.png?v=1#h' )}"),
            ".a{background:url('./base/x.png?v=1#h')}"
        );
        assert_eq!(
            rebase(r#".a{background:url("../up.png")}"#),
            r#".a{background:url("./up.png")}"#
        );
        // A space in the new url needs quotes.
        assert_eq!(
            rebase(r".a{background:url(my\ file.png)}"),
            r#".a{background:url("./base/my file.png")}"#
        );
        // Not a `url(` token, external, data, fragments, functions, aliases, root-absolute.
        for kept in [
            ".a{b:myurl(x.png)}",
            ".a{b:url(https://cdn.test/x.png)}",
            ".a{b:url(//cdn.test/x.png)}",
            ".a{b:url(data:image/png;base64,AAAA)}",
            ".a{b:url(#grad)}",
            ".a{b:url(var(--x))}",
            ".a{b:url(@/x.png)}",
            ".a{b:url(/x.png)}",
        ] {
            assert_eq!(rebase(kept), kept);
        }
        // `@import` urls go through the import rewrite only (`.css` specs).
        assert_eq!(
            rebase("@import url(./a.css) print;"),
            "@import url(./base/a.css) print;"
        );
        assert_eq!(rebase("@import \"./a.css\";"), "@import \"./base/a.css\";");
        assert_eq!(
            rebase("@import url(https://x.test/a.css);"),
            "@import url(https://x.test/a.css);"
        );
        // image-set: bare strings and url() candidates, each rewritten once.
        assert_eq!(
            rebase(r#".a{b:image-set("x.png" 1x, url(y.png) 2x, "z.png" type("image/png"))}"#),
            r#".a{b:image-set("./base/x.png" 1x, url(./base/y.png) 2x, "./base/z.png" type("image/png"))}"#
        );
        assert_eq!(
            rebase(".a{b:url(x.png)}").len(),
            ".a{b:url(./base/x.png)}".len()
        );
        // Same directory: untouched.
        let same = rebase_to_dir(
            ".a{b:url(x.png)}",
            Path::new("/p"),
            Path::new("/p"),
            &resolve.as_ref(),
        );
        assert_eq!(same, ".a{b:url(x.png)}");
    }
}