use std::io::Read;
use std::path::{Path, PathBuf};
use super::config::ProjectConfig;
#[cfg(doc)]
use super::out_paths::resolve_output_path_for_kind;
use super::stdio::write_output;
use crate::output::WriteTarget;
use crate::write::{write_compiled, Inputs, NotRemoved, Removal};
use mds::{effective_parent, MdsError, SourceMap, STRING_SOURCE_MAP_LABEL};
use miette::Result;
pub(crate) fn map_path_for(output_path: &Path) -> PathBuf {
let mut s = output_path.as_os_str().to_owned();
s.push(".map");
PathBuf::from(s)
}
pub(crate) fn base64_encode(input: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char);
out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char);
if chunk.len() > 1 {
out.push(ALPHABET[((n >> 6) & 0x3f) as usize] as char);
} else {
out.push('=');
}
if chunk.len() > 2 {
out.push(ALPHABET[(n & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
out
}
pub(crate) fn carrier_line(map_json: &str) -> String {
let b64 = base64_encode(map_json.as_bytes());
format!("<!--# sourceMappingURL=data:application/json;base64,{b64} -->")
}
fn strip_existing_carrier(content: &str) -> &str {
let trimmed = content.trim_end_matches('\n');
if let Some(pos) = trimmed.rfind('\n') {
let last_line = &trimmed[pos + 1..];
if last_line.starts_with("<!--# sourceMappingURL=data:") {
return &content[..pos + 1];
}
} else if trimmed.starts_with("<!--# sourceMappingURL=data:") {
return "";
}
content
}
pub(crate) fn embed_carrier(content: String, map_json: &str) -> String {
let base = strip_existing_carrier(&content);
let sep = if base.ends_with('\n') { "" } else { "\n" };
format!("{base}{sep}{}\n", carrier_line(map_json))
}
#[must_use]
pub(super) fn embed_map_in_content(content: String, map: Option<&SourceMap>) -> String {
match map {
Some(sm) => embed_carrier(content, &sm.to_json()),
None => content,
}
}
pub(super) fn write_sidecar_map(
out: &WriteTarget,
sm: &SourceMap,
inputs: &Inputs,
quiet: bool,
) -> Result<(), MdsError> {
let map = out.sibling(map_path_for);
write_compiled(&map, &sm.to_json(), inputs)?;
if !quiet {
crate::output::ewriteln!(
"Source map written to {}",
crate::output::safe_path(&map.shown)
);
}
Ok(())
}
pub(super) fn write_stdout_ladder(
map_present: bool,
flag_source_map: bool,
cfg: Option<&ProjectConfig>,
content: String,
inputs: &Inputs,
quiet: bool,
) -> Result<()> {
if map_present {
if flag_source_map {
return Err(miette::miette!(
"--source-map (sidecar) requires an output file; use -o <file> or \
--out-dir, --inline to embed the map for stdout, or --no-source-map \
to skip it"
));
}
if !quiet {
let cfg_path = cfg
.map(ProjectConfig::shown_file)
.unwrap_or_else(|| PathBuf::from("mds.json"));
crate::output::ewriteln!(
"warning: source_map in {} has no effect when writing to \
stdout (sidecar requires -o <file> or --out-dir); use --inline to \
embed the map, or --no-source-map to silence this warning",
crate::output::safe_path(&cfg_path)
);
}
}
write_output(None, &content, inputs, quiet, true)
}
pub(super) fn compute_source_map_base(
input: &Path,
output: &Option<String>,
out_dir: &Option<PathBuf>,
config: &Option<ProjectConfig>,
) -> Result<PathBuf, MdsError> {
use crate::output::current_dir;
let abs = |p: PathBuf| -> Result<PathBuf, MdsError> {
if p.is_absolute() {
Ok(p)
} else {
Ok(current_dir()?.join(p))
}
};
match output.as_deref() {
Some("-") => {
current_dir()
}
Some(o) => {
abs(effective_parent(Path::new(o)).to_path_buf())
}
None => {
if let Some(dir) = out_dir {
abs(dir.clone())
} else if input == Path::new("-") {
current_dir()
} else if let Some(ProjectConfig { config, dir, .. }) = config {
if let Some(ref output_dir) = config.build.output_dir {
abs(dir.join(output_dir))
} else {
abs(effective_parent(input).to_path_buf())
}
} else {
abs(effective_parent(input).to_path_buf())
}
}
}
}
pub(crate) fn apply_source_map_file_label(
sm: &mut mds::SourceMap,
output_path: Option<&Path>,
stdin_label: bool,
) {
if let Some(out) = output_path {
sm.file = out.file_name().map(|n| n.to_string_lossy().into_owned());
}
if stdin_label {
for src in &mut sm.sources {
if src == STRING_SOURCE_MAP_LABEL {
*src = crate::output::STDIN_DISPLAY_LABEL.to_string();
}
}
}
}
pub(crate) fn verify_then_delete_map(
map: &WriteTarget,
expected_basename: &str,
quiet: bool,
) -> Result<(), MdsError> {
let proof = |file: &mut std::fs::File| has_sidecar_head(file, expected_basename);
match crate::write::remove_proven(map, proof) {
Ok(Removal::Removed) => {
if !quiet {
crate::output::ewriteln!(
"Removed stale map {}",
crate::output::safe_path(&map.shown)
);
}
Ok(())
}
Ok(Removal::Missing) => Ok(()),
Ok(Removal::Kept) => keep_stale_map(map, "not proven to be written by mds", quiet),
Err(not_a_file @ NotRemoved::NotAFile) => keep_stale_map(map, not_a_file.cause(), quiet),
Err(not_removed) => Err(crate::output::stale_removal_error(
"stale map",
&map.shown,
¬_removed,
)),
}
}
fn keep_stale_map(map: &WriteTarget, why: &str, quiet: bool) -> Result<(), MdsError> {
if !quiet {
crate::output::ewriteln!(
"warning: kept stale map {}: {}",
crate::output::safe_path(&map.shown),
crate::output::safe_inline(why)
);
}
Ok(())
}
fn has_sidecar_head(reader: &mut impl Read, expected_basename: &str) -> std::io::Result<bool> {
let Ok(name) = serde_json::to_string(expected_basename) else {
return Ok(false);
};
let head = format!("{{\"version\":3,\"file\":{name},");
let len = head.len() as u64;
Ok(mds::read_at_most(reader, len, len)? == head.as_bytes())
}
pub(super) fn file_name_of(output: &WriteTarget) -> String {
output
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::super::stdio::tests::Stream;
use super::*;
#[test]
fn source_map_base_is_absolute_for_every_output_mode() {
let input = PathBuf::from("src/a.mds");
let cases: Vec<(&str, Option<String>, Option<PathBuf>)> = vec![
("-o - (stdout)", Some("-".to_string()), None),
(
"-o relative/out.md",
Some("relative/out.md".to_string()),
None,
),
("-o bare.md", Some("bare.md".to_string()), None),
("-o /abs/out.md", Some("/abs/out.md".to_string()), None),
("--out-dir relative", None, Some(PathBuf::from("dist"))),
("--out-dir /abs", None, Some(PathBuf::from("/abs/dist"))),
("default (beside source)", None, None),
];
for (label, output, out_dir) in cases {
let got = compute_source_map_base(&input, &output, &out_dir, &None)
.unwrap_or_else(|e| panic!("{label}: the working directory exists: {e}"));
assert!(
got.is_absolute(),
"{label}: source_map_base must be absolute so core's root-containment \
check succeeds; got {got:?}"
);
}
}
#[test]
fn source_map_base_for_bare_filename_output_is_cwd() {
let got = compute_source_map_base(
Path::new("src/a.mds"),
&Some("out.md".to_string()),
&None,
&None,
)
.expect("bare -o must still produce a base");
let cwd = std::env::current_dir().unwrap();
assert_eq!(
got, cwd,
"`-o out.md` writes into the CWD, so the map base is the CWD"
);
}
#[test]
fn source_map_base_tracks_the_output_file_directory() {
let got = compute_source_map_base(
Path::new("src/a.mds"),
&Some("dist/nested/a.md".to_string()),
&None,
&None,
)
.expect("base must be Some");
assert_eq!(got, std::env::current_dir().unwrap().join("dist/nested"));
}
#[test]
fn embed_carrier_is_idempotent() {
let json = r#"{"version":3,"sources":["a.mds"],"mappings":"AAAA"}"#;
let once = embed_carrier("Hello world\n".to_string(), json);
let twice = embed_carrier(once.clone(), json);
assert_eq!(
once, twice,
"embedding the carrier twice must be idempotent"
);
assert_eq!(
twice.matches("sourceMappingURL=data:").count(),
1,
"the carrier must appear exactly once, got:\n{twice}"
);
}
#[test]
fn carrier_line_cannot_break_out_of_html_comment() {
let hostile_json = r#"{"sourcesContent":["--> break out <script>"]}"#;
let line = carrier_line(hostile_json);
let payload = line
.strip_prefix("<!--# sourceMappingURL=data:application/json;base64,")
.and_then(|s| s.strip_suffix(" -->"))
.expect("carrier must have the expected envelope");
assert!(!payload.contains('<'), "payload must not contain '<'");
assert!(!payload.contains('>'), "payload must not contain '>'");
assert!(!payload.contains('-'), "payload must not contain '-'");
}
#[test]
fn stale_map_check_reads_only_the_sidecar_head() {
let sidecar = |name: &str| {
let mut sm = mds::compile_str_with_deps_opts(
"Hi\n",
None,
None,
mds::CompileOptions::default().with_source_map(true),
)
.unwrap()
.source_map
.expect("a map was built");
apply_source_map_file_label(&mut sm, Some(Path::new(name)), false);
sm.to_json()
};
let verdict =
|bytes: &str, name: &str| has_sidecar_head(&mut bytes.as_bytes(), name).unwrap();
let mut mismatches = Vec::new();
for name in ["out.md", "a \"quoted\" name.md", "caf\u{e9}.md"] {
if !verdict(&sidecar(name), name) {
mismatches.push(format!("{name}: its own sidecar is not recognised"));
}
}
let rows = [
("another output's sidecar", sidecar("other.md")),
(
"hand-formatted, same fields",
"{ \"version\": 3, \"file\": \"out.md\", \"sources\": [], \"names\": [], \"mappings\": \"\" }".to_owned(),
),
("ends after file", "{\"version\":3,\"file\":\"out.md\"}".to_owned()),
("version 2", "{\"version\":2,\"file\":\"out.md\",\"sources\":[]}".to_owned()),
];
for (label, bytes) in rows {
if verdict(&bytes, "out.md") {
mismatches.push(format!("{label}: recognised as out.md's sidecar"));
}
}
let head = "{\"version\":3,\"file\":\"out.md\",".len() as u64;
let mut large = Stream::sized(64 * 1024 * 1024);
if has_sidecar_head(&mut large, "out.md").unwrap() || large.served > head {
mismatches.push(format!(
"64 MiB of x: read {} bytes; the head is {head}",
large.served
));
}
assert!(mismatches.is_empty(), "{mismatches:#?}");
}
#[cfg(unix)]
#[test]
fn a_stale_map_that_cannot_be_removed_is_an_io_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let map = dir.path().join("out.md.map");
let sidecar = "{\"version\":3,\"file\":\"out.md\",\"sources\":[],\"mappings\":\"\"}";
std::fs::write(&map, sidecar).unwrap();
assert!(
verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true).is_ok()
);
assert!(!map.exists(), "control: the stale sidecar must be removed");
std::fs::write(&map, sidecar).unwrap();
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap();
let probe = std::fs::write(dir.path().join("probe"), b"");
let result = verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true);
let _ = std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755));
if probe.is_ok() {
crate::output::ewriteln!(
"skipped: a file can be created at mode 0o555 (running as root?)"
);
return;
}
match result {
Err(MdsError::Io { message }) => assert!(
message.starts_with("could not remove stale map "),
"unexpected message: {message}"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
assert!(
map.exists(),
"the sidecar that could not be removed is still there"
);
}
#[cfg(unix)]
#[test]
fn a_stale_map_that_cannot_be_read_is_an_io_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let map = dir.path().join("out.md.map");
std::fs::write(&map, "{\"hand\":\"written\"}").unwrap();
assert!(
verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true).is_ok()
);
assert!(map.exists(), "control: a hand-written map is left in place");
let sidecar = "{\"version\":3,\"file\":\"out.md\",\"sources\":[],\"mappings\":\"\"}";
std::fs::write(&map, sidecar).unwrap();
std::fs::set_permissions(&map, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::File::open(&map).is_ok() {
crate::output::ewriteln!(
"skipped: a file can be read at mode 0o000 (running as root?)"
);
return;
}
let result = verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true);
match result {
Err(MdsError::Io { message }) => assert!(
message.starts_with("cannot read stale map ") && message.contains("out.md.map"),
"unexpected message: {message}"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
assert!(map.exists(), "a map that cannot be read is left in place");
}
#[cfg(unix)]
#[test]
fn a_stale_map_is_never_removed_through_a_symlink_below_its_anchor() {
let sidecar = "{\"version\":3,\"file\":\"x.md\",\"sources\":[],\"mappings\":\"\"}";
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
std::fs::create_dir_all(anchor.join("real")).unwrap();
std::fs::create_dir(dir.path().join("victim")).unwrap();
std::os::unix::fs::symlink("../victim", anchor.join("sub")).unwrap();
let victim = dir.path().join("victim/x.md.map");
std::fs::write(&victim, sidecar).unwrap();
let map = WriteTarget::below(&anchor, Path::new("out"), Path::new("sub/x.md.map"));
let result = verify_then_delete_map(&map, "x.md", true);
assert_eq!(
std::fs::read_to_string(&victim).ok().as_deref(),
Some(sidecar),
"nothing is removed through the symlink"
);
match result {
Err(MdsError::Io { message }) => assert_eq!(
message,
"could not remove stale map out/sub/x.md.map: \
refusing to follow a symlink at out/sub"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
let real = anchor.join("real/x.md.map");
std::fs::write(&real, sidecar).unwrap();
let map = WriteTarget::below(&anchor, Path::new("out"), Path::new("real/x.md.map"));
assert!(verify_then_delete_map(&map, "x.md", true).is_ok());
assert!(!real.exists(), "control: the stale sidecar is removed");
}
}