rhaiper 0.2.0

Minifier for Rhai scripts, with Source Map v3 output
Documentation
//! Source Map v3 generation and position resolution.

use rhaiper_map::vlq;

use crate::emit::Mapping;
use crate::stream::LineIndex;

#[derive(Debug, Clone)]
pub struct MapOptions {
    /// Name recorded for the generated file.
    pub file: Option<String>,
    /// Name recorded for the original source.
    pub source_name: String,
    /// Whether to embed the original source in the map. Makes the map standalone at the cost of
    /// roughly the size of the input.
    pub include_sources_content: bool,
}

impl Default for MapOptions {
    fn default() -> Self {
        Self {
            file: None,
            source_name: "input.rhai".into(),
            include_sources_content: true,
        }
    }
}

/// Encodes the `mappings` field.
///
/// Every field is a delta. Only the generated column resets per line; source index, source line and
/// source column accumulate across the whole map.
fn encode_mappings(src: &str, minified: &str, mappings: &[Mapping]) -> String {
    let src_lines = LineIndex::new(src);
    let gen_lines = LineIndex::new(minified);

    let mut out = String::new();
    let (mut prev_gen_col, mut prev_src_line, mut prev_src_col) = (0i64, 0i64, 0i64);
    let mut line_no = 0u32;
    let mut first_on_line = true;

    for m in mappings {
        while line_no < m.gen_line {
            out.push(';');
            line_no += 1;
            prev_gen_col = 0;
            first_on_line = true;
        }
        if !first_on_line {
            out.push(',');
        }
        first_on_line = false;

        let gen_col = i64::from(gen_lines.utf16_col(minified, m.gen_line, m.gen_col));
        let src_col = i64::from(src_lines.utf16_col(src, m.src_line, m.src_col));
        let src_line = i64::from(m.src_line);

        vlq::encode(gen_col - prev_gen_col, &mut out);
        vlq::encode(0, &mut out); // single source
        vlq::encode(src_line - prev_src_line, &mut out);
        vlq::encode(src_col - prev_src_col, &mut out);

        prev_gen_col = gen_col;
        prev_src_line = src_line;
        prev_src_col = src_col;
    }
    out
}

/// Serializes a Source Map v3 document.
pub fn to_json(src: &str, minified: &str, mappings: &[Mapping], opts: &MapOptions) -> String {
    let mappings = encode_mappings(src, minified, mappings);
    let mut doc = serde_json::Map::new();
    doc.insert("version".into(), 3.into());
    if let Some(file) = &opts.file {
        doc.insert("file".into(), file.clone().into());
    }
    doc.insert(
        "sources".into(),
        serde_json::Value::Array(vec![opts.source_name.clone().into()]),
    );
    if opts.include_sources_content {
        doc.insert(
            "sourcesContent".into(),
            serde_json::Value::Array(vec![src.into()]),
        );
    }
    doc.insert("names".into(), serde_json::Value::Array(Vec::new()));
    doc.insert("mappings".into(), mappings.into());
    serde_json::Value::Object(doc).to_string()
}

/// The parts of a Source Map v3 document needed to resolve a position.
#[derive(Debug, Clone)]
pub struct SourceMap {
    pub sources: Vec<String>,
    pub sources_content: Vec<Option<String>>,
    pub mappings: String,
}

/// A resolved original position, in the units rhai reports: 1-based line and character column.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Original {
    pub source: String,
    pub line: u32,
    pub column: u32,
}

impl SourceMap {
    pub fn from_json(json: &str) -> Result<Self, String> {
        let doc: serde_json::Value =
            serde_json::from_str(json).map_err(|e| format!("malformed source map: {e}"))?;

        let strings = |key: &str| -> Vec<Option<String>> {
            doc.get(key)
                .and_then(serde_json::Value::as_array)
                .map(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
                .unwrap_or_default()
        };

        let sources = strings("sources").into_iter().flatten().collect();
        let mappings = doc
            .get("mappings")
            .and_then(serde_json::Value::as_str)
            .ok_or("source map has no `mappings` field")?
            .to_owned();

        Ok(Self {
            sources,
            sources_content: strings("sourcesContent"),
            mappings,
        })
    }

    /// Maps a position in the minified script back to the original.
    ///
    /// `line` and `column` are as rhai reports them: 1-based, with the column counted in
    /// characters. `minified` is needed to convert that column into the UTF-16 units the map stores;
    /// for an all-ASCII script the two coincide.
    pub fn resolve(&self, minified: &str, line: u32, column: u32) -> Option<Original> {
        let gen_line = line.checked_sub(1)?;
        let gen_char_col = column.saturating_sub(1);
        let gen_col = LineIndex::new(minified).utf16_col(minified, gen_line, gen_char_col);

        let found = rhaiper_map::resolve(&self.mappings, gen_line, gen_col)?;
        let source = self.sources.get(found.source as usize)?.clone();

        // Report the column in characters, to match how rhai counts.
        let column = match self
            .sources_content
            .get(found.source as usize)
            .and_then(Option::as_ref)
        {
            Some(text) => LineIndex::new(text).char_col(text, found.line, found.col) + 1,
            None => found.col + 1,
        };

        Some(Original {
            source,
            line: found.line + 1,
            column,
        })
    }
}