web_modules 0.6.0

Pure-Rust, buildless toolchain for ES modules and Web Components
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
//! SCSS → CSS compilation via [`grass`] (pure Rust, no Node/dart-sass).
//!
//! [`compile_directory`] mirrors the [`super::typescript`] convention: walk a
//! source tree, skip `_`-prefixed partials, and emit a sibling `.css` for each
//! `.scss`. `load_paths` lets `@use`/`@import` reach vendored stylesheets (e.g. a
//! vendored Bootstrap under `web_modules/bootstrap/scss`).
//!
//! `@use`/`@import` resolution is sandboxed by [`SandboxFs`]: `grass` resolves an
//! import against the importing file's own directory first, then the load paths,
//! following `..` and symlinks like any lookup, so without a containment check a
//! source stylesheet could `@import "../../../../secret.scss"` and inline a file
//! from outside the tree into the compiled CSS (which the dev server would then
//! serve). The sandbox confines every probe and read to the source roots and their
//! load paths — the SCSS counterpart of the serving layer's `contained_file`.
//!
//! A refusal deliberately reads as a missing file to `grass` (fail-closed), but not
//! to the caller: the compile error names every real path a probe was refused on,
//! so a forgotten load path explains itself instead of surfacing as a bare
//! "Can't find stylesheet to import".

use std::fs::{create_dir_all, write};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use grass::{Fs, Options, OutputStyle};
use walkdir::WalkDir;

use crate::{Error, Result};

/// A [`grass::Fs`] that confines every `@use`/`@import` probe and read to an allowlist of
/// canonicalized directories, so SCSS resolution cannot climb out of the source roots and their
/// load paths. The containment mirrors the serving layer's `contained_file`: canonicalize the
/// probed path and require it to stay under one of the allowed `roots`.
///
/// A refusal is invisible to `grass` itself: imports resolve through [`is_file`](Fs::is_file)
/// probes, so a refused candidate reads exactly like a missing file and the refusal message in
/// [`read`](Fs::read) is unreachable for imports. To keep that diagnosable the sandbox records
/// every probe that hit something real outside the roots, and the compile error carries the
/// list — see [`refusal_note`](SandboxFs::refusal_note).
#[derive(Debug)]
struct SandboxFs {
    roots: Vec<PathBuf>,
    /// Probes that resolved to a real file or directory outside every root, in probe order —
    /// the difference between "the import is a typo" and "a load path is missing", kept as
    /// data instead of silence.
    refused: Mutex<Vec<PathBuf>>,
}

impl SandboxFs {
    /// Confine access to `roots`. Each is canonicalized once here; a root that does not exist is
    /// dropped, since it can never contain a file and so never widens the allowlist.
    fn new(roots: &[&Path]) -> Self {
        Self {
            roots: roots.iter().filter_map(|p| p.canonicalize().ok()).collect(),
            refused: Mutex::new(Vec::new()),
        }
    }

    /// The real location of `path` if it resolves inside an allowed root, else `None`. A path that
    /// does not resolve — a probe for a candidate that isn't on disk — is not contained, matching
    /// how a missing file reads on the default [`grass::StdFs`]. A path that resolves but sits
    /// outside every root is recorded for [`refusal_note`](SandboxFs::refusal_note).
    fn contained(&self, path: &Path) -> Option<PathBuf> {
        let real = path.canonicalize().ok()?;
        if self.roots.iter().any(|root| real.starts_with(root)) {
            return Some(real);
        }
        let mut refused = self.refused.lock().expect("sandbox refusal log poisoned");
        if !refused.contains(&real) {
            refused.push(real);
        }
        None
    }

    /// One `note:` block naming what the sandbox refused since the last
    /// [`reset_refusals`](SandboxFs::reset_refusals), or `None` when nothing was.
    fn refusal_note(&self) -> Option<String> {
        let refused = self.refused.lock().expect("sandbox refusal log poisoned");
        if refused.is_empty() {
            return None;
        }
        let list = refused
            .iter()
            .map(|p| format!("  {}", p.display()))
            .collect::<Vec<_>>()
            .join("\n");
        Some(format!(
            "note: the sandbox refused {} path(s) that exist outside the source roots and load \
             paths; if an import should reach them, add their tree as a load path:\n{list}",
            refused.len()
        ))
    }

    /// Forget recorded refusals — [`compile_directory`] resets between entry files so a note
    /// names only the failing file's probes.
    fn reset_refusals(&self) {
        self.refused
            .lock()
            .expect("sandbox refusal log poisoned")
            .clear();
    }
}

/// Map a `grass` failure to [`Error::Scss`], appending the sandbox's refusal note when there is
/// one — without it, a refused import is indistinguishable from a missing file.
fn scss_error(sandbox: &SandboxFs, error: Box<grass::Error>) -> Error {
    match sandbox.refusal_note() {
        Some(note) => Error::Scss(format!("{error}\n{note}")),
        None => Error::Scss(error.to_string()),
    }
}

impl Fs for SandboxFs {
    fn is_file(&self, path: &Path) -> bool {
        self.contained(path).is_some_and(|real| real.is_file())
    }

    fn is_dir(&self, path: &Path) -> bool {
        self.contained(path).is_some_and(|real| real.is_dir())
    }

    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
        match self.contained(path) {
            Some(real) => std::fs::read(real),
            None => Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("SCSS import {path:?} escapes the source roots"),
            )),
        }
    }

    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        std::fs::canonicalize(path)
    }
}

/// The directory `grass` resolves a file's relative imports against — its parent, or the current
/// directory for a bare filename. Kept in the sandbox allowlist so the entry file (which
/// [`grass::from_path`] reads through the [`Fs`]) and its sibling imports stay reachable.
fn entry_dir(path: &Path) -> PathBuf {
    match path.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
        _ => PathBuf::from("."),
    }
}

fn options<'a>(fs: &'a dyn Fs, load_paths: &[&Path]) -> Options<'a> {
    let mut opts = Options::default().style(OutputStyle::Compressed).fs(fs);
    for path in load_paths {
        opts = opts.load_path(path);
    }
    opts
}

/// Compile a single SCSS string to compressed CSS. Imports resolve within `load_paths` only (a
/// string has no source directory of its own).
pub fn compile_str(input: &str, load_paths: &[&Path]) -> Result<String> {
    let sandbox = SandboxFs::new(load_paths);
    grass::from_string(input.to_string(), &options(&sandbox, load_paths))
        .map_err(|e| scss_error(&sandbox, e))
}

/// Compile a single `.scss` file to CSS. Imports resolve within `load_paths` and the file's own
/// directory, and cannot escape them.
pub fn compile_file(path: &Path, load_paths: &[&Path]) -> Result<String> {
    let entry = entry_dir(path);
    let mut roots = load_paths.to_vec();
    roots.push(entry.as_path());
    let sandbox = SandboxFs::new(&roots);
    grass::from_path(path, &options(&sandbox, load_paths)).map_err(|e| scss_error(&sandbox, e))
}

/// Compile every `.scss` under `src_dir` (skipping `_` partials) into a mirrored
/// `.css` under `out_dir`. Symlinks are skipped entirely — file or directory; the
/// pipeline's preflight, not this standalone helper, honors
/// [`SymlinkMode`](crate::SymlinkMode). Returns the number of files written.
pub fn compile_directory(src_dir: &Path, out_dir: &Path, load_paths: &[&Path]) -> Result<usize> {
    // Every entry file lives under `src_dir`, so one sandbox covering the load paths plus
    // `src_dir` keeps each file and its in-tree imports reachable while refusing escapes.
    let mut roots = load_paths.to_vec();
    roots.push(src_dir);
    let sandbox = SandboxFs::new(&roots);
    let opts = options(&sandbox, load_paths);
    let mut count = 0;
    for entry in WalkDir::new(src_dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| !e.path_is_symlink())
        .filter(|e| {
            e.path()
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| ext.eq_ignore_ascii_case("scss"))
        })
    {
        let path = entry.path();
        if path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with('_'))
        {
            continue;
        }
        let rel = path
            .strip_prefix(src_dir)
            .map_err(|e| Error::Scss(e.to_string()))?;
        let out = out_dir.join(rel).with_extension("css");
        if let Some(parent) = out.parent() {
            create_dir_all(parent)?;
        }
        // Per-file refusal scope: a note on the eventual error names only the failing
        // file's probes, not leftovers from files that compiled.
        sandbox.reset_refusals();
        let css = grass::from_path(path, &opts).map_err(|e| scss_error(&sandbox, e))?;
        write(&out, css)?;
        count += 1;
    }
    Ok(count)
}

/// The SCSS stage as a pipeline step: claims `.scss` (minus `_` partials) for a
/// mirrored `.css`.
pub(crate) struct ScssStep {
    load_paths: Vec<PathBuf>,
}

impl ScssStep {
    pub(crate) fn new(load_paths: Vec<PathBuf>) -> Self {
        Self { load_paths }
    }
}

impl crate::build::steps::Preflight for ScssStep {
    fn name(&self) -> &'static str {
        "SCSS compile"
    }

    fn rank(&self) -> crate::build::steps::Rank {
        crate::build::steps::Rank::Transform
    }

    fn claim(&self, rel: &Path) -> Option<crate::build::steps::Claim> {
        let name = rel.file_name()?.to_str()?;
        let ext = rel.extension()?.to_str()?;
        if !ext.eq_ignore_ascii_case("scss") || name.starts_with('_') {
            return None;
        }
        Some(crate::build::steps::Claim {
            out_rel: rel.with_extension("css"),
            tiebreak: 0,
        })
    }
}

impl crate::build::steps::Step for ScssStep {
    fn emit(
        &self,
        _cx: &crate::build::steps::EmitCx<'_>,
        src: &Path,
        _rel: &Path,
        dest: &Path,
    ) -> Result<crate::build::steps::Emitted> {
        let paths: Vec<&Path> = self.load_paths.iter().map(PathBuf::as_path).collect();
        let css = compile_file(src, &paths)?;
        write(dest, css)?;
        Ok(crate::build::steps::Emitted::default())
    }
}

/// Feature-specific `--scss-*` flags, paired with the `--scss` / `--no-scss` toggle in
/// [`ScssArgs`].
#[cfg(feature = "cli")]
#[derive(clap::Args, Clone, Debug, Default)]
pub struct ScssConfig {
    /// Extra SCSS `@use`/`@import` load path(s), on top of the source roots (repeatable).
    #[arg(long = "scss-load-path", value_name = "DIR")]
    pub load_paths: Vec<std::path::PathBuf>,
}

#[cfg(feature = "cli")]
crate::cli_config::feature_args!(ScssArgs, scss, "scss", no_scss, "no-scss", ScssConfig);

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

    #[test]
    fn compiles_and_compresses() {
        let css = compile_str("$c: red; a { color: $c; b { color: $c; } }", &[]).unwrap();
        assert!(css.contains("color:red"));
        assert!(!css.contains('\n'), "compressed output is single-line");
    }

    #[test]
    fn directory_skips_partials() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        let out = dir.path().join("out");
        create_dir_all(&src).unwrap();
        write(src.join("_vars.scss"), "$c: blue;").unwrap();
        write(src.join("app.scss"), "@use 'vars'; a { color: vars.$c; }").unwrap();
        let n = compile_directory(&src, &out, &[]).unwrap();
        assert_eq!(n, 1);
        assert!(out.join("app.css").exists());
        assert!(!out.join("_vars.css").exists());
    }

    #[cfg(unix)]
    #[test]
    fn directory_skips_symlinks_entirely() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        let out = dir.path().join("out");
        create_dir_all(&src).unwrap();
        write(src.join("app.scss"), "a { color: red; }").unwrap();
        write(dir.path().join("outside.scss"), "b { color: blue; }").unwrap();
        std::os::unix::fs::symlink(dir.path().join("outside.scss"), src.join("linked.scss"))
            .unwrap();

        let n = compile_directory(&src, &out, &[]).unwrap();
        assert_eq!(n, 1, "the link contributes nothing");
        assert!(out.join("app.css").exists());
        assert!(!out.join("linked.css").exists());
    }

    #[test]
    fn import_within_the_tree_still_resolves() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        create_dir_all(&src).unwrap();
        write(src.join("_vars.scss"), "$c: blue;").unwrap();
        write(src.join("app.scss"), "@use 'vars'; a { color: vars.$c; }").unwrap();
        let css = compile_file(&src.join("app.scss"), &[]).unwrap();
        assert!(css.contains("color:blue"));
    }

    #[test]
    fn import_through_a_load_path_still_resolves() {
        // A vendored stylesheet reached via an explicit load path stays allowed.
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        let vendor = tmp.path().join("vendor");
        create_dir_all(&src).unwrap();
        create_dir_all(&vendor).unwrap();
        write(vendor.join("_theme.scss"), "$c: green;").unwrap();
        write(src.join("app.scss"), "@use 'theme'; a { color: theme.$c; }").unwrap();
        let css = compile_file(&src.join("app.scss"), &[vendor.as_path()]).unwrap();
        assert!(css.contains("color:green"));
    }

    #[test]
    fn import_climbing_out_of_the_tree_is_refused() {
        // A valid partial sits just outside the source tree, so only containment — not a parse
        // error — can be what stops it from being inlined into the compiled CSS.
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        create_dir_all(&src).unwrap();
        write(tmp.path().join("_secret.scss"), "$leak: red;").unwrap();
        write(src.join("app.scss"), "@import '../secret';").unwrap();
        // `grass` reports the escaping import as an unfindable stylesheet rather than reading
        // it; the error's refusal note is what tells the two failure modes apart, naming the
        // existing file and pointing at the fix.
        let err = compile_file(&src.join("app.scss"), &[]).unwrap_err();
        let message = err.to_string();
        assert!(message.contains("_secret.scss"), "{message}");
        assert!(message.contains("load path"), "{message}");
    }

    #[test]
    fn a_truly_missing_import_carries_no_refusal_note() {
        // The note is evidence, not boilerplate: an import that exists nowhere stays a plain
        // "can't find stylesheet" with nothing to blame on the sandbox.
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        create_dir_all(&src).unwrap();
        write(src.join("app.scss"), "@import '../nonexistent';").unwrap();
        let err = compile_file(&src.join("app.scss"), &[]).unwrap_err();
        let message = err.to_string();
        assert!(!message.contains("note:"), "{message}");
    }

    #[test]
    fn directory_error_carries_the_refusal_note() {
        // The same diagnosis through the tree API — the consumer that hit this in the wild.
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        let out = tmp.path().join("out");
        create_dir_all(&src).unwrap();
        write(tmp.path().join("_outside.scss"), "$c: red;").unwrap();
        write(src.join("app.scss"), "@import '../outside';").unwrap();
        let err = compile_directory(&src, &out, &[]).unwrap_err();
        assert!(err.to_string().contains("_outside.scss"), "{err}");
    }

    #[cfg(unix)]
    #[test]
    fn import_through_a_symlink_escaping_the_tree_is_refused() {
        use std::os::unix::fs::symlink;
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        let outside = tmp.path().join("outside");
        create_dir_all(&src).unwrap();
        create_dir_all(&outside).unwrap();
        write(outside.join("_theme.scss"), "$c: red;").unwrap();
        // A partial that appears to live in the tree is really a symlink pointing out of it.
        symlink(outside.join("_theme.scss"), src.join("_theme.scss")).unwrap();
        write(src.join("app.scss"), "@use 'theme';").unwrap();
        let err = compile_file(&src.join("app.scss"), &[]).unwrap_err();
        // The note names the link's real target — where the file actually lives.
        let message = err.to_string();
        assert!(message.contains("outside"), "{message}");
        assert!(
            message.contains("_theme.scss"),
            "expected the refused target in {message}"
        );
    }
}