mod common;
use common::{fixture, mds_bin};
use std::path::Path;
fn decode_vlq_one(iter: &mut impl Iterator<Item = u8>) -> Option<i64> {
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut result: u64 = 0;
let mut shift: u32 = 0;
let mut continuation = true;
while continuation {
let ch = iter.next()?;
let digit = B64.iter().position(|&b| b == ch)? as u64;
continuation = (digit & 0x20) != 0;
result |= (digit & 0x1f) << shift;
shift += 5;
if shift > 30 {
return None; }
}
let value = (result >> 1) as i64;
if (result & 1) != 0 {
Some(-value)
} else {
Some(value)
}
}
fn decode_first_segment(mappings: &str) -> Option<(i64, i64, i64, i64)> {
let first_seg = mappings
.split(';')
.filter_map(|group| group.split(',').next())
.find(|seg| !seg.is_empty())?;
let mut iter = first_seg.bytes();
let gen_col = decode_vlq_one(&mut iter)?;
let src_idx = decode_vlq_one(&mut iter)?;
let orig_line = decode_vlq_one(&mut iter)?;
let orig_col = decode_vlq_one(&mut iter)?;
Some((gen_col, src_idx, orig_line, orig_col))
}
fn base64_decode(input: &str) -> Vec<u8> {
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::with_capacity(input.len() / 4 * 3);
let bytes: Vec<u8> = input
.bytes()
.filter(|&b| b != b'=')
.map(|b| B64.iter().position(|&x| x == b).unwrap() as u8)
.collect();
for chunk in bytes.chunks(4) {
let n = (chunk[0] as u32) << 18
| (chunk.get(1).copied().unwrap_or(0) as u32) << 12
| (chunk.get(2).copied().unwrap_or(0) as u32) << 6
| (chunk.get(3).copied().unwrap_or(0) as u32);
out.push(((n >> 16) & 0xff) as u8);
if chunk.len() > 2 {
out.push(((n >> 8) & 0xff) as u8);
}
if chunk.len() > 3 {
out.push((n & 0xff) as u8);
}
}
out
}
fn build_file(path: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("build")
.arg(path)
.args(extra_args)
.stderr(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.output()
.expect("mds binary should run")
}
fn read_map_json(map_path: &Path) -> serde_json::Value {
let text = std::fs::read_to_string(map_path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", map_path.display()));
serde_json::from_str(&text)
.unwrap_or_else(|e| panic!("map file is not valid JSON at {}: {e}", map_path.display()))
}
fn assert_source_is_contained(s: &str, root: &Path, base: &Path, forbidden: &[&str]) {
if s.starts_with('<') && s.ends_with('>') {
return;
}
let unified = s.replace('\\', "/");
assert!(
!unified.starts_with("//?/"),
"source must not contain Windows verbatim prefix: {s:?}"
);
assert!(
!unified.contains(":\\"),
"source must not contain backslash-qualified Windows drive: {s:?}"
);
assert!(
!unified.contains(":/"),
"source must not contain forward-slash-qualified Windows drive: {s:?}"
);
let drive_lead = unified.len() >= 2
&& (unified.as_bytes()[0] as char).is_ascii_alphabetic()
&& unified.as_bytes()[1] == b':';
assert!(
!drive_lead,
"source must not start with a bare drive designator: {s:?}"
);
assert!(
!unified.starts_with('/'),
"source must not be an absolute path: {s:?}"
);
let contained = [root, base].iter().any(|anchor| {
let joined = anchor.join(&unified);
let mut comps: Vec<_> = Vec::new();
for c in joined.components() {
match c {
std::path::Component::ParentDir => {
comps.pop();
}
std::path::Component::CurDir => {}
other => comps.push(other),
}
}
let norm: std::path::PathBuf = comps.iter().collect();
norm.starts_with(root)
});
assert!(
contained,
"source path {s:?} is not contained in root {root:?} \
(tried root-join and base-join with {base:?})"
);
for comp in unified.split('/') {
for &f in forbidden {
assert_ne!(
comp, f,
"source path {s:?} contains forbidden component {f:?}"
);
}
}
}
#[test]
fn sm1_source_map_creates_sidecar() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(result.status.success(), "build should succeed");
assert!(out.exists(), "output .md should exist");
let map_path = dir.path().join("out.md.map");
assert!(
map_path.exists(),
"sidecar map out.md.map should exist next to out.md"
);
}
#[test]
fn sm2_sidecar_is_valid_v3_json() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(result.status.success(), "build should succeed");
let map_path = dir.path().join("out.md.map");
let v = read_map_json(&map_path);
assert_eq!(
v["version"].as_u64(),
Some(3),
"version must be 3, got: {:?}",
v["version"]
);
assert!(v["sources"].is_array(), "sources must be an array");
assert!(v["mappings"].is_string(), "mappings must be a string");
let mappings = v["mappings"].as_str().unwrap();
assert!(!mappings.is_empty(), "mappings must be non-empty");
}
#[test]
fn sm3_sources_are_relative_not_absolute() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(result.status.success(), "build should succeed");
let map_path = dir.path().join("out.md.map");
let v = read_map_json(&map_path);
let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let workspace = crate_dir
.parent()
.and_then(|p| p.parent())
.expect("workspace root must be two levels above crate dir");
let dir_name = dir
.path()
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
for src in v["sources"].as_array().unwrap() {
let s = src.as_str().unwrap();
assert_source_is_contained(s, workspace, workspace, &[dir_name]);
}
}
#[test]
fn sm4_file_field_is_output_basename() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(result.status.success(), "build should succeed");
let map_path = dir.path().join("out.md.map");
let v = read_map_json(&map_path);
assert_eq!(
v["file"].as_str(),
Some("out.md"),
"file must be the output basename 'out.md', got: {:?}",
v["file"]
);
}
#[test]
fn sm5_no_source_map_suppresses_generation() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
let map_path = dir.path().join("out.md.map");
assert!(
map_path.exists(),
"pre-condition: map should exist after first build"
);
let result = build_file(&fixture("sm_basic.mds"), &["-o", out.to_str().unwrap()]);
assert!(
result.status.success(),
"rebuild without --source-map should succeed"
);
assert!(
!map_path.exists(),
"stale map should be removed when --source-map is omitted"
);
}
#[test]
fn sm6_inline_embeds_carrier_in_output() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "--inline", "-o", out.to_str().unwrap()],
);
assert!(
result.status.success(),
"build with --inline should succeed"
);
let content = std::fs::read_to_string(&out).unwrap();
assert!(
content.contains("<!--# sourceMappingURL=data:application/json;base64,"),
"inline output must contain the sourceMappingURL carrier, got:\n{content}"
);
let map_path = dir.path().join("out.md.map");
assert!(
!map_path.exists(),
"--inline must not create a sidecar .map file"
);
}
#[test]
fn sm7_inline_carrier_is_decodable_v3() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
build_file(
&fixture("sm_basic.mds"),
&["--source-map", "--inline", "-o", out.to_str().unwrap()],
);
let content = std::fs::read_to_string(&out).unwrap();
let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
let suffix = " -->";
let start = content
.find(prefix)
.expect("carrier prefix not found in inline output");
let rest = &content[start + prefix.len()..];
let end = rest.find(suffix).expect("carrier suffix ' -->' not found");
let b64 = &rest[..end];
assert!(!b64.is_empty(), "base64 payload must be non-empty");
let decoded = base64_decode(b64);
let json: serde_json::Value =
serde_json::from_slice(&decoded).expect("decoded carrier must be valid JSON");
assert_eq!(
json["version"].as_u64(),
Some(3),
"decoded carrier version must be 3"
);
assert!(json["sources"].is_array(), "sources must be array");
assert!(json["mappings"].is_string(), "mappings must be string");
}
#[test]
fn sm8_embed_sources_includes_sources_content() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&[
"--source-map",
"--embed-sources",
"-o",
out.to_str().unwrap(),
],
);
assert!(
result.status.success(),
"build with --embed-sources should succeed"
);
let map_path = dir.path().join("out.md.map");
let v = read_map_json(&map_path);
let sources_content = v["sourcesContent"]
.as_array()
.expect("sourcesContent must be present when --embed-sources is set");
assert!(
!sources_content.is_empty(),
"sourcesContent must be non-empty"
);
for entry in sources_content {
assert!(
entry.is_null() || entry.is_string(),
"each sourcesContent entry must be null or string, got: {entry:?}"
);
}
}
#[test]
fn sm9_no_embed_sources_omits_sources_content() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
let map_path = dir.path().join("out.md.map");
let v = read_map_json(&map_path);
assert!(
v["sourcesContent"].is_null(),
"sourcesContent must be absent (null in JSON) when --embed-sources is omitted, got: {:?}",
v["sourcesContent"]
);
}
#[test]
fn sm10_messages_mode_degrades_to_no_map() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.json");
let result = build_file(
&fixture("sm_message.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(
result.status.success(),
"messages-mode build with --source-map must succeed (graceful degradation)"
);
let map_path = dir.path().join("out.json.map");
assert!(
!map_path.exists(),
"no .map should be emitted for a messages-mode template"
);
let stderr = String::from_utf8(result.stderr).unwrap();
let has_warn =
stderr.contains("messages") || stderr.contains("source_map") || stderr.contains("None");
assert!(
has_warn,
"stderr must contain a degradation warning for messages-mode, got: {stderr:?}"
);
}
#[test]
fn sm11_stale_map_removed_on_no_map_rebuild() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let r1 = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(
r1.status.success(),
"initial source-map build should succeed"
);
let map_path = dir.path().join("out.md.map");
assert!(map_path.exists(), "sidecar must exist after step 1");
let r2 = build_file(&fixture("sm_basic.mds"), &["-o", out.to_str().unwrap()]);
assert!(
r2.status.success(),
"rebuild without --source-map should succeed"
);
assert!(
!map_path.exists(),
"stale map must be removed when rebuilding without --source-map (AC-FUNC-10)"
);
}
#[test]
fn sm12_sidecar_overwritten_on_rebuild() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let r1 = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(r1.status.success(), "first source-map build should succeed");
let map_path = dir.path().join("out.md.map");
let map1 = std::fs::read_to_string(&map_path).unwrap();
let r2 = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(
r2.status.success(),
"second source-map build should succeed"
);
let map2 = std::fs::read_to_string(&map_path).unwrap();
assert_eq!(
map1, map2,
"map should be deterministic across identical builds"
);
}
#[test]
fn sm13_inline_build_removes_stale_sidecar() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let r1 = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(r1.status.success(), "initial sidecar build should succeed");
let map_path = dir.path().join("out.md.map");
assert!(map_path.exists(), "sidecar must exist after step 1");
let r2 = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "--inline", "-o", out.to_str().unwrap()],
);
assert!(r2.status.success(), "inline rebuild should succeed");
assert!(
!map_path.exists(),
"stale sidecar must be removed when switching to --inline (AC-FUNC-10)"
);
let content = std::fs::read_to_string(&out).unwrap();
assert!(
content.contains("<!--# sourceMappingURL=data:"),
"output must contain inline carrier after --inline rebuild"
);
}
#[test]
fn sm14_stdin_source_map_inline_produces_carrier() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("stdin_out.md");
let mut child = mds_bin()
.args([
"build",
"-",
"--source-map",
"--inline",
"-o",
out.to_str().unwrap(),
])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("mds binary should spawn");
use std::io::Write as _;
child
.stdin
.take()
.unwrap()
.write_all(b"---\nname: World\n---\nHello {{name}}!\n")
.unwrap();
let result = child.wait_with_output().unwrap();
assert!(
result.status.success(),
"stdin --source-map --inline should succeed"
);
let content = std::fs::read_to_string(&out).unwrap();
assert!(
content.contains("<!--# sourceMappingURL=data:application/json;base64,"),
"stdin inline output must contain carrier"
);
let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
let suffix = " -->";
let start = content.find(prefix).unwrap();
let rest = &content[start + prefix.len()..];
let end = rest.find(suffix).unwrap();
let b64 = &rest[..end];
let decoded = base64_decode(b64);
let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
let sources = json["sources"].as_array().expect("sources must be array");
assert!(
sources.iter().any(|s| s.as_str() == Some("<stdin>")),
"stdin builds must label source as '<stdin>', got: {sources:?}"
);
}
#[test]
fn sm15_directory_mode_source_map() {
let dir = tempfile::tempdir().unwrap();
let src_content = std::fs::read_to_string(fixture("sm_basic.mds")).unwrap();
std::fs::write(dir.path().join("basic.mds"), &src_content).unwrap();
let out_dir = dir.path().join("out");
let result = mds_bin()
.args([
"build",
dir.path().to_str().unwrap(),
"--source-map",
"--out-dir",
out_dir.to_str().unwrap(),
])
.stderr(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
result.status.success(),
"directory mode --source-map build should succeed, stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let out_md = out_dir.join("basic.md");
let out_map = out_dir.join("basic.md.map");
assert!(out_md.exists(), "compiled .md should exist in out_dir");
assert!(
out_map.exists(),
"sidecar .md.map should exist in out_dir alongside basic.md"
);
let v = read_map_json(&out_map);
assert_eq!(v["version"].as_u64(), Some(3), "map version must be 3");
}
#[test]
fn sm_det_sources_never_absolute_across_build_dirs() {
let dir_a = tempfile::tempdir().unwrap();
let dir_b = tempfile::tempdir().unwrap();
let out_a = dir_a.path().join("out_a.md");
let out_b = dir_b.path().join("out_b.md");
build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out_a.to_str().unwrap()],
);
build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out_b.to_str().unwrap()],
);
let map_a = read_map_json(&dir_a.path().join("out_a.md.map"));
let map_b = read_map_json(&dir_b.path().join("out_b.md.map"));
let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let workspace = crate_dir
.parent()
.and_then(|p| p.parent())
.expect("workspace root must be two levels above crate dir");
for (_label, v, dir_path) in [
("dir_a", &map_a, dir_a.path()),
("dir_b", &map_b, dir_b.path()),
] {
let dir_name = dir_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
for src in v["sources"].as_array().unwrap() {
let s = src.as_str().unwrap();
assert_source_is_contained(s, workspace, workspace, &[dir_name]);
}
}
assert_eq!(
map_a["mappings"], map_b["mappings"],
"mappings must be deterministic regardless of output directory"
);
}
#[test]
fn sm_gold_mappings_first_segment_is_aaaa() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("gold.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(result.status.success(), "golden build should succeed");
let map_path = dir.path().join("gold.md.map");
let v = read_map_json(&map_path);
let mappings = v["mappings"].as_str().unwrap();
const GOLDEN_FIRST_SEG: &str = "AAGA";
let first_nonempty_seg = mappings
.split(';')
.filter_map(|g| g.split(',').next())
.find(|s| !s.is_empty())
.unwrap_or("");
if std::env::var("UPDATE_GOLDEN").is_ok() {
eprintln!("UPDATE_GOLDEN: first nonempty segment = {first_nonempty_seg:?}");
eprintln!("UPDATE_GOLDEN: full mappings = {mappings:?}");
}
assert_eq!(
first_nonempty_seg, GOLDEN_FIRST_SEG,
"first non-empty segment must be {GOLDEN_FIRST_SEG:?} \
(gen_col=0,src=0,orig_line=3,orig_col=0 for sm_basic.mds), got: {first_nonempty_seg:?}"
);
}
#[test]
fn sm_vlq_decoder_known_values() {
let mut iter_a = b"A".iter().copied();
assert_eq!(decode_vlq_one(&mut iter_a), Some(0), "A → 0");
let mut iter_c = b"C".iter().copied();
assert_eq!(decode_vlq_one(&mut iter_c), Some(1), "C → 1");
let mut iter_d = b"D".iter().copied();
assert_eq!(decode_vlq_one(&mut iter_d), Some(-1), "D → -1");
let mut iter_e = b"E".iter().copied();
assert_eq!(decode_vlq_one(&mut iter_e), Some(2), "E → 2");
let seg = decode_first_segment("AAAA").expect("AAAA must decode");
assert_eq!(seg, (0, 0, 0, 0), "AAAA must decode to all-zero offsets");
let seg2 = decode_first_segment("CCCC").expect("CCCC must decode");
assert_eq!(seg2, (1, 1, 1, 1), "CCCC must decode to all-one offsets");
}
fn mappings_reference_multiple_sources(mappings: &str) -> bool {
let mut src_idx: i64 = 0;
for group in mappings.split(';') {
for seg in group.split(',') {
if seg.is_empty() {
continue;
}
let mut iter = seg.bytes();
if decode_vlq_one(&mut iter).is_none() {
continue;
}
if let Some(delta) = decode_vlq_one(&mut iter) {
src_idx = src_idx.saturating_add(delta);
if src_idx > 0 {
return true;
}
}
}
}
false
}
#[test]
fn sm17_include_multi_file_attribution() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_include_parent.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(
result.status.success(),
"build of @include fixture should succeed, stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let map_path = dir.path().join("out.md.map");
assert!(map_path.exists(), "sidecar .md.map must exist");
let v = read_map_json(&map_path);
let sources = v["sources"].as_array().expect("sources must be an array");
assert!(
sources.len() >= 2,
"sources[] must have ≥ 2 entries for a template that @imports another, got: {:?}",
sources
);
let has_parent = sources
.iter()
.any(|s| s.as_str().is_some_and(|p| p.contains("sm_include_parent")));
assert!(
has_parent,
"sources[] must include the parent file (sm_include_parent), got: {:?}",
sources
);
let has_partial = sources
.iter()
.any(|s| s.as_str().is_some_and(|p| p.contains("_sm_partial")));
assert!(
has_partial,
"sources[] must include the imported file (_sm_partial), got: {:?}",
sources
);
let mappings = v["mappings"].as_str().unwrap();
assert!(
mappings_reference_multiple_sources(mappings),
"mappings must contain a segment referencing the imported source (src_idx > 0); \
got sources: {:?}, mappings: {:?}",
sources,
mappings
);
}
#[test]
fn sm_vlq_actual_map_first_segment_decodes() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let result = build_file(
&fixture("sm_basic.mds"),
&["--source-map", "-o", out.to_str().unwrap()],
);
assert!(result.status.success(), "build should succeed");
let map_path = dir.path().join("out.md.map");
let v = read_map_json(&map_path);
let mappings = v["mappings"].as_str().unwrap();
let (gen_col, src_idx, orig_line, orig_col) =
decode_first_segment(mappings).expect("first segment must decode");
assert_eq!(src_idx, 0, "first segment must reference source index 0");
assert!(gen_col >= 0, "generated column must be >= 0");
assert!(orig_line >= 0, "original line must be >= 0");
assert!(orig_col >= 0, "original column must be >= 0");
}
#[test]
fn sm16_stale_map_not_smv3_preserved_with_warning() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let map_path = dir.path().join("out.md.map");
std::fs::write(&map_path, r#"{"version":2,"file":"WRONG.md"}"#).unwrap();
let result = build_file(&fixture("sm_basic.mds"), &["-o", out.to_str().unwrap()]);
assert!(result.status.success(), "build should succeed");
assert!(
map_path.exists(),
"hand-authored non-SMv3 map must be preserved (not deleted)"
);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
stderr.contains("warning:") && stderr.contains("out.md.map"),
"expected a warning about leaving the non-SMv3 map in place, got stderr: {stderr:?}"
);
std::fs::write(&map_path, r#"{"version":2,"file":"WRONG.md"}"#).unwrap();
let quiet_result = build_file(
&fixture("sm_basic.mds"),
&["-o", out.to_str().unwrap(), "--quiet"],
);
assert!(quiet_result.status.success(), "quiet build should succeed");
assert!(
map_path.exists(),
"hand-authored non-SMv3 map must be preserved even with --quiet"
);
let quiet_stderr = String::from_utf8_lossy(&quiet_result.stderr);
assert!(
!quiet_stderr.contains("warning:"),
"--quiet must suppress the warning; got stderr: {quiet_stderr:?}"
);
}
#[test]
fn sm14b_stdin_source_map_sidecar_relabels_source_to_stdin() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("stdin_out.md");
let map_path = dir.path().join("stdin_out.md.map");
let mut child = mds_bin()
.args(["build", "-", "--source-map", "-o", out.to_str().unwrap()])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("mds binary should spawn");
use std::io::Write as _;
child
.stdin
.take()
.unwrap()
.write_all(b"---\nname: World\n---\nHello {{name}}!\n")
.unwrap();
let result = child.wait_with_output().unwrap();
assert!(
result.status.success(),
"stdin --source-map sidecar should succeed"
);
let map_json = read_map_json(&map_path);
let sources = map_json["sources"]
.as_array()
.expect("sources must be array");
assert!(
sources.iter().any(|s| s.as_str() == Some("<stdin>")),
"stdin sidecar must label source as \"<stdin>\"; got: {sources:?}"
);
assert!(
!sources.iter().any(|s| s.as_str() == Some("input.mds")),
"\"input.mds\" must not leak into stdin sidecar sources[]; got: {sources:?}"
);
assert!(
!sources.iter().any(|s| s.as_str() == Some("<source>")),
"\"<source>\" must not appear in stdin sidecar sources[]; got: {sources:?}"
);
}
#[test]
fn sm16a_file_inline_stdout_no_absolute_paths() {
let result = mds_bin()
.args([
"build",
fixture("sm_basic.mds").to_str().unwrap(),
"--source-map",
"--inline",
"-o",
"-",
])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
result.status.success(),
"file --inline -o - must succeed; stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stdout = String::from_utf8_lossy(&result.stdout);
let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
let suffix = " -->";
let start = stdout
.find(prefix)
.expect("stdout must contain inline source-map carrier");
let rest = &stdout[start + prefix.len()..];
let end = rest
.find(suffix)
.expect("carrier must be closed with \" -->\"");
let b64 = &rest[..end];
let decoded = base64_decode(b64);
let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let workspace = crate_dir
.parent()
.and_then(|p| p.parent())
.expect("workspace root must be two levels above crate dir");
let cwd = std::env::current_dir().unwrap_or_else(|_| workspace.to_path_buf());
let home = std::env::var("HOME").unwrap_or_default();
let home_name = std::path::Path::new(&home)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
let sources = json["sources"].as_array().expect("sources must be array");
for src in sources {
let s = src.as_str().expect("source must be string");
assert_source_is_contained(s, workspace, &cwd, &[home_name]);
}
assert!(
json.get("file").map(|v| v.is_null()).unwrap_or(true),
"`file` field must be absent or null for stdout inline map; got: {:?}",
json.get("file")
);
}
#[test]
fn sm16b_stdin_inline_stdout_now_allowed() {
let mut child = mds_bin()
.args(["build", "-", "--source-map", "--inline", "-o", "-"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("mds binary should spawn");
use std::io::Write as _;
child
.stdin
.take()
.unwrap()
.write_all(b"Hello World!\n")
.unwrap();
let result = child.wait_with_output().unwrap();
assert!(
result.status.success(),
"stdin --inline -o - must succeed after removing the false rejection; \
stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stdout = String::from_utf8_lossy(&result.stdout);
assert!(
stdout.contains("<!--# sourceMappingURL=data:application/json;base64,"),
"stdin --inline -o - must embed a source-map carrier in stdout; stdout: {stdout:?}"
);
let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
let suffix = " -->";
let start = stdout.find(prefix).unwrap();
let rest = &stdout[start + prefix.len()..];
let end = rest.find(suffix).unwrap();
let decoded = base64_decode(&rest[..end]);
let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let workspace = crate_dir
.parent()
.and_then(|p| p.parent())
.expect("workspace root must be two levels above crate dir");
let cwd = std::env::current_dir().unwrap_or_else(|_| workspace.to_path_buf());
let home = std::env::var("HOME").unwrap_or_default();
let home_name = std::path::Path::new(&home)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
let sources = json["sources"].as_array().expect("sources must be array");
assert!(
sources.iter().any(|s| s.as_str() == Some("<stdin>")),
"stdin --inline stdout must label source as \"<stdin>\"; got: {sources:?}"
);
for src in sources {
let s = src.as_str().expect("source must be string");
assert_source_is_contained(s, workspace, &cwd, &[home_name]);
}
}
#[test]
fn sm_sec3_dotdot_escape_falls_back_to_basename() {
let src_dir = tempfile::tempdir().unwrap();
let out_dir = tempfile::tempdir().unwrap();
let src_dir_name = src_dir
.path()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
let src_path = src_dir.path().join("input.mds");
std::fs::write(&src_path, "Hello SEC-3!\n").unwrap();
let deep_out_dir = out_dir.path().join("a/b/c/d/e/f/g/h/i/j");
std::fs::create_dir_all(&deep_out_dir).unwrap();
let out_path = deep_out_dir.join("out.md");
let result = mds_bin()
.arg("build")
.arg(&src_path)
.arg("--source-map")
.arg("-o")
.arg(&out_path)
.output()
.expect("mds build (sidecar) should run");
assert!(
result.status.success(),
"sidecar build should succeed; stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let map_path = deep_out_dir.join("out.md.map");
let v = read_map_json(&map_path);
let sidecar_sources = v["sources"].as_array().expect("sources must be array");
for src in sidecar_sources {
let s = src.as_str().expect("source must be string");
assert!(
!s.starts_with("../"),
"sidecar sources[] must not contain a `..`-escaping path \
(SEC-3 guard must fire); got: {s:?}"
);
assert_ne!(s, "..", "sidecar sources[] must not be bare `..`");
assert!(
!s.starts_with('/'),
"sidecar sources[] must not be absolute; got: {s:?}"
);
assert!(
!s.contains(src_dir_name.as_str()),
"sidecar sources[] must not contain the source tempdir name \
(path reconstruction leak); dir={src_dir_name:?} entry={s:?}"
);
}
let inline_result = mds_bin()
.current_dir(&deep_out_dir)
.arg("build")
.arg(&src_path)
.args(["--source-map", "--inline", "-o", "-"])
.output()
.expect("mds build --inline should run");
assert!(
inline_result.status.success(),
"inline build should succeed; stderr: {}",
String::from_utf8_lossy(&inline_result.stderr)
);
let stdout = String::from_utf8_lossy(&inline_result.stdout);
let prefix = "<!--# sourceMappingURL=data:application/json;base64,";
let suffix = " -->";
let start = stdout
.find(prefix)
.expect("stdout must contain inline source-map carrier");
let rest = &stdout[start + prefix.len()..];
let end = rest
.find(suffix)
.expect("carrier must be closed with \" -->\"");
let decoded = base64_decode(&rest[..end]);
let inline_json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
let inline_sources = inline_json["sources"]
.as_array()
.expect("inline sources must be array");
for src in inline_sources {
let s = src.as_str().expect("source must be string");
assert!(
!s.starts_with("../"),
"inline sources[] must not contain a `..`-escaping path \
(SEC-3 guard must fire); got: {s:?}"
);
assert_ne!(s, "..", "inline sources[] must not be bare `..`");
assert!(
!s.starts_with('/'),
"inline sources[] must not be absolute; got: {s:?}"
);
assert!(
!s.contains(src_dir_name.as_str()),
"inline sources[] must not contain the source tempdir name \
(path reconstruction leak); dir={src_dir_name:?} entry={s:?}"
);
}
}
#[test]
fn sm18_explicit_sidecar_flag_without_output_hard_errors() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "# Hello\n").unwrap();
let result = mds_bin()
.args(["build", "--source-map", "-o", "-"])
.arg(&src)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
!result.status.success(),
"explicit --source-map -o - must fail (sidecar cannot write to stdout); stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
stderr.contains("sidecar") || stderr.contains("output file") || stderr.contains("-o"),
"error must mention sidecar / output-file / -o; got: {stderr:?}"
);
assert!(
stderr.contains("--inline") || stderr.contains("--no-source-map"),
"error must mention --inline or --no-source-map as alternatives; got: {stderr:?}"
);
}
#[test]
fn sm19_config_source_map_sidecar_without_output_degrades_with_warning() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "# Hello\n").unwrap();
std::fs::write(
dir.path().join("mds.json"),
r#"{"build": {"source_map": true}}"#,
)
.unwrap();
let result = mds_bin()
.args(["build", "-o", "-"]) .arg(&src)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
result.status.success(),
"config-sourced source_map with -o - must exit 0 (degrade gracefully); \
stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stdout = String::from_utf8_lossy(&result.stdout);
assert!(
!stdout.is_empty(),
"compiled content must be written to stdout; stdout was empty"
);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
stderr.contains("source_map") || stderr.contains("mds.json"),
"warning must mention source_map or mds.json; got: {stderr:?}"
);
assert!(
stderr.contains("warning") || stderr.contains("no effect"),
"output must look like a warning, not an error; got: {stderr:?}"
);
}
#[test]
fn sm19q_config_source_map_without_output_quiet_no_warning() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "# Hello\n").unwrap();
std::fs::write(
dir.path().join("mds.json"),
r#"{"build": {"source_map": true}}"#,
)
.unwrap();
let result = mds_bin()
.args(["build", "--quiet", "-o", "-"]) .arg(&src)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
result.status.success(),
"--quiet config-sourced source_map with -o - must exit 0; stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
stderr.is_empty(),
"--quiet must suppress the degradation warning; got: {stderr:?}"
);
}
#[test]
fn sm20_embed_sources_without_source_map_warns() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
let out = dir.path().join("out.md");
std::fs::write(&src, "# Hello\n").unwrap();
std::fs::write(
dir.path().join("mds.json"),
r#"{"build": {"embed_sources": true}}"#,
)
.unwrap();
let result = mds_bin()
.args(["build", "-o"])
.arg(&out)
.arg(&src)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
result.status.success(),
"config embed_sources without source_map must still succeed (warning only); \
stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
stderr.contains("embed_sources") && stderr.contains("no effect"),
"stderr must warn that embed_sources has no effect without source maps; got: {stderr:?}"
);
}
#[test]
fn sm20b_embed_sources_with_source_map_no_warning() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
let out = dir.path().join("out.md");
std::fs::write(&src, "# Hello\n").unwrap();
std::fs::write(
dir.path().join("mds.json"),
r#"{"build": {"embed_sources": true, "source_map": true}}"#,
)
.unwrap();
let result = mds_bin()
.args(["build", "-o"])
.arg(&out)
.arg(&src)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.expect("mds binary should run");
assert!(
result.status.success(),
"config embed_sources+source_map must succeed; stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
!stderr.contains("no effect"),
"embed_sources+source_map must NOT warn about no effect; got: {stderr:?}"
);
}
#[cfg(unix)]
#[test]
fn build_source_map_sidecar_symlink_target_rejected() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("in.mds");
std::fs::write(&src, "Hello sidecar!\n").unwrap();
let out = dir.path().join("out.md");
let real = dir.path().join("real.map");
std::fs::write(&real, "OLD").unwrap();
std::os::unix::fs::symlink(&real, dir.path().join("out.md.map")).unwrap();
let result = mds_bin()
.arg("build")
.arg(&src)
.arg("--source-map")
.arg("-o")
.arg(&out)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&result.stderr).into_owned();
assert_ne!(
result.status.code(),
Some(0),
"a symlinked sidecar path must fail the build; stderr: {stderr}"
);
assert!(
stderr.contains("symlink"),
"the refusal must say why; got: {stderr:?}"
);
assert!(
out.exists(),
"the compiled artifact itself is written before the sidecar and must survive"
);
assert_eq!(
std::fs::read_to_string(&real).unwrap(),
"OLD",
"the symlink target must not be written through"
);
}
#[cfg(unix)]
#[test]
fn build_stdin_source_map_sidecar_symlink_target_rejected() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let real = dir.path().join("real.map");
std::fs::write(&real, "OLD").unwrap();
std::os::unix::fs::symlink(&real, dir.path().join("out.md.map")).unwrap();
let mut child = mds_bin()
.args(["build", "-", "--source-map", "-o", out.to_str().unwrap()])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("mds binary should spawn");
use std::io::Write as _;
child
.stdin
.take()
.unwrap()
.write_all(b"---\nname: World\n---\nHello {{name}}!\n")
.unwrap();
let result = child.wait_with_output().unwrap();
let stderr = String::from_utf8_lossy(&result.stderr).into_owned();
assert_ne!(
result.status.code(),
Some(0),
"a symlinked sidecar path must fail the stdin build; stderr: {stderr}"
);
assert!(
stderr.contains("symlink"),
"the refusal must say why; got: {stderr:?}"
);
assert!(
out.exists(),
"the compiled artifact itself is written before the sidecar and must survive"
);
assert_eq!(
std::fs::read_to_string(&real).unwrap(),
"OLD",
"the symlink target must not be written through"
);
}