1use anyhow::{Context, Result, bail};
17use sha2::{Digest, Sha256};
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20
21const NORMALIZER_VERSION: &str = "normalize-v1";
23const SHIM_SRC: &str = include_str!("host/shim-dual-sqlite.mjs");
27const STALE_TMP_SECS: u64 = 3600;
29
30#[derive(Debug)]
33pub enum Outcome {
34 Warm(PathBuf),
36 Built {
38 path: PathBuf,
39 ms: u128,
40 beside: bool,
41 rss_before_kb: i64,
42 rss_after_kb: i64,
43 },
44 Skipped(PathBuf),
46 Fallback { path: PathBuf, err: String },
49 Passthrough(PathBuf),
51}
52
53impl Outcome {
54 pub fn label(&self) -> &'static str {
56 match self {
57 Outcome::Warm(_) => "warm",
58 Outcome::Built { .. } => "built",
59 Outcome::Skipped(_) => "disabled",
60 Outcome::Fallback { .. } => "error",
61 Outcome::Passthrough(_) => "passthrough",
62 }
63 }
64}
65
66pub fn needs_ancestry(code: &str) -> bool {
80 let consts = const_map(code);
81 for spec in specifiers(code, &consts) {
82 match spec {
83 None => return true,
86 Some(s) if !clean_spec(&s) => return true,
87 Some(_) => {}
88 }
89 }
90 false
91}
92
93fn specifiers(code: &str, consts: &HashMap<String, String>) -> Vec<Option<String>> {
98 let mut out = Vec::new();
99 let b = code.as_bytes();
100 let n = b.len();
101 let idc = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'$';
102 let boundary = |start: usize, len: usize| -> bool {
103 (start == 0 || !idc(b[start - 1])) && b.get(start + len).map(|&c| !idc(c)).unwrap_or(true)
104 };
105 let is_quote = |c: u8| c == b'"' || c == b'\'' || c == b'`';
106
107 for (kw, len) in [("import", 6usize), ("require", 7usize), ("from", 4usize)] {
108 let mut i = 0;
109 while let Some(rel) = code[i..].find(kw) {
110 let start = i + rel;
111 i = start + len;
112 if !boundary(start, len) {
113 continue;
114 }
115 let mut j = start + len;
116 while j < n && b[j].is_ascii_whitespace() {
117 j += 1;
118 }
119 if j >= n {
120 continue;
121 }
122 if b[j] == b'(' {
123 if kw != "from" {
127 j += 1;
128 while j < n && b[j].is_ascii_whitespace() {
129 j += 1;
130 }
131 out.push(parse_arg(code, j, consts));
132 }
133 } else if is_quote(b[j]) {
134 let after_dot = start > 0 && b[start - 1] == b'.';
141 if ((kw == "from" && !after_dot) || kw == "import")
142 && let Some(sp) = parse_arg(code, j, consts)
143 {
144 out.push(Some(sp));
145 }
146 }
148 }
149 }
150 out
151}
152
153fn parse_arg(code: &str, j: usize, consts: &HashMap<String, String>) -> Option<String> {
155 let b = code.as_bytes();
156 match b.get(j)? {
157 q @ (b'"' | b'\'') => read_quoted(code, j + 1, *q).map(|(s, _)| s),
158 b'`' => {
159 let (s, end) = read_quoted(code, j + 1, b'`')?;
160 if s.contains("${") {
161 None } else {
163 let _ = end;
164 Some(s)
165 }
166 }
167 c if c.is_ascii_alphabetic() || *c == b'_' || *c == b'$' => {
168 let mut k = j;
170 while k < b.len() && (b[k].is_ascii_alphanumeric() || b[k] == b'_' || b[k] == b'$') {
171 k += 1;
172 }
173 consts.get(&code[j..k]).cloned()
174 }
175 _ => None, }
177}
178
179fn read_quoted(code: &str, start: usize, quote: u8) -> Option<(String, usize)> {
182 let b = code.as_bytes();
183 let mut k = start;
184 let mut val = String::new();
185 while k < b.len() {
186 match b[k] {
187 c if c == quote => return Some((val, k + 1)),
188 b'\\' => {
189 k += 1;
190 if k < b.len() {
191 val.push(b[k] as char);
192 k += 1;
193 }
194 }
195 c => {
196 val.push(c as char);
197 k += 1;
198 }
199 }
200 }
201 None }
203
204fn const_map(code: &str) -> HashMap<String, String> {
207 let mut m = HashMap::new();
208 let b = code.as_bytes();
209 let n = b.len();
210 let idc = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'$';
211 for kw in ["const", "let", "var"] {
212 let len = kw.len();
213 let mut i = 0;
214 while let Some(rel) = code[i..].find(kw) {
215 let at = i + rel;
216 i = at + len;
217 let before_ok = at == 0 || !idc(b[at - 1]);
218 let after_ok = b.get(at + len).map(|&c| !idc(c)).unwrap_or(true);
219 if !before_ok || !after_ok {
220 continue;
221 }
222 let mut k = at + len;
223 while k < n && b[k].is_ascii_whitespace() {
224 k += 1;
225 }
226 let name_start = k;
227 while k < n && idc(b[k]) {
228 k += 1;
229 }
230 if k == name_start {
231 continue;
232 }
233 let name = code[name_start..k].to_string();
234 let mut ws = k;
235 while ws < n && b[ws].is_ascii_whitespace() {
236 ws += 1;
237 }
238 if ws >= n || b[ws] != b'=' {
239 continue;
240 }
241 ws += 1;
242 while ws < n && b[ws].is_ascii_whitespace() {
243 ws += 1;
244 }
245 if ws >= n {
246 continue;
247 }
248 let q = b[ws];
249 if (q == b'"' || q == b'\'')
250 && let Some((v, _)) = read_quoted(code, ws + 1, q)
251 {
252 m.entry(name).or_insert(v);
253 } else if q == b'`'
254 && let Some((v, _)) = read_quoted(code, ws + 1, b'`')
255 && !v.contains("${")
256 {
257 m.entry(name).or_insert(v);
258 }
259 }
260 }
261 m
262}
263
264fn clean_spec(s: &str) -> bool {
266 if s.is_empty() {
267 return true;
268 }
269 if s.starts_with("./") || s.starts_with("../") || s.starts_with('/') {
270 return true;
271 }
272 if s.starts_with("file:") || s.starts_with("data:") {
273 return true;
274 }
275 if s.starts_with("node:") || s.starts_with("bun:") {
276 return true;
277 }
278 let first = s.split('/').next().unwrap_or("");
279 is_node_builtin(first)
280}
281
282fn is_node_builtin(first: &str) -> bool {
285 matches!(
286 first,
287 "assert"
288 | "async_hooks"
289 | "buffer"
290 | "child_process"
291 | "cluster"
292 | "console"
293 | "constants"
294 | "crypto"
295 | "dgram"
296 | "diagnostics_channel"
297 | "dns"
298 | "events"
299 | "fs"
300 | "http"
301 | "http2"
302 | "https"
303 | "inspector"
304 | "module"
305 | "net"
306 | "os"
307 | "path"
308 | "perf_hooks"
309 | "process"
310 | "punycode"
311 | "querystring"
312 | "readline"
313 | "stream"
314 | "string_decoder"
315 | "sys"
316 | "timers"
317 | "tls"
318 | "tty"
319 | "url"
320 | "util"
321 | "v8"
322 | "vm"
323 | "wasi"
324 | "worker_threads"
325 | "zlib"
326 )
327}
328
329fn bundle(entry: &Path) -> Result<String> {
336 use rolldown::plugin::{
337 HookLoadArgs, HookLoadOutput, HookResolveIdArgs, HookResolveIdOutput, HookUsage, Plugin,
338 PluginContext, SharedLoadPluginContext,
339 };
340 use rolldown::{
341 Bundler, BundlerOptions, InputItem, LogLevel, OutputFormat, Platform, TreeshakeOptions,
342 };
343 use std::borrow::Cow;
344 use std::future::Future;
345
346 const SHIM_ID: &str = "ocserve:bun-sqlite-shim";
347
348 #[derive(Debug)]
349 struct AliasBunSqlite {
350 shim_src: &'static str,
351 }
352
353 impl Plugin for AliasBunSqlite {
354 fn name(&self) -> Cow<'static, str> {
355 Cow::Borrowed("ocserve-bun-sqlite-alias")
356 }
357
358 fn resolve_id(
359 &self,
360 _ctx: &PluginContext,
361 args: &HookResolveIdArgs<'_>,
362 ) -> impl Future<Output = rolldown::plugin::HookResolveIdReturn> + Send {
363 let hit = args.specifier == "bun:sqlite";
364 let from_shim = args.importer == Some(SHIM_ID);
368 async move {
369 if hit && from_shim {
370 Ok(Some(HookResolveIdOutput {
371 id: "bun:sqlite".into(),
372 external: Some(rolldown_common::ResolvedExternal::Bool(true)),
373 ..Default::default()
374 }))
375 } else if hit {
376 Ok(Some(HookResolveIdOutput::from_id(SHIM_ID)))
377 } else {
378 Ok(None)
379 }
380 }
381 }
382
383 fn load(
384 &self,
385 _ctx: SharedLoadPluginContext,
386 args: &HookLoadArgs<'_>,
387 ) -> impl Future<Output = rolldown::plugin::HookLoadReturn> + Send {
388 let hit = args.id == SHIM_ID;
389 let code = self.shim_src;
390 async move {
391 if hit {
392 Ok(Some(HookLoadOutput {
393 code: code.into(),
394 map: None,
395 side_effects: None,
396 module_type: Some(rolldown_common::ModuleType::Js),
397 }))
398 } else {
399 Ok(None)
400 }
401 }
402 }
403
404 fn register_hook_usage(&self) -> HookUsage {
405 HookUsage::ResolveId | HookUsage::Load
406 }
407 }
408
409 let opts = BundlerOptions {
410 input: Some(vec![InputItem {
411 name: Some("plugin".to_string()),
412 import: entry.to_string_lossy().into_owned(),
413 }]),
414 cwd: entry.parent().map(Path::to_path_buf),
415 format: Some(OutputFormat::Esm),
416 platform: Some(Platform::Node),
417 treeshake: TreeshakeOptions::Boolean(false),
419 minify: Some(rolldown::RawMinifyOptions::Bool(false)),
430 log_level: Some(LogLevel::Warn),
431 ..Default::default()
432 };
433 let mut bundler = Bundler::with_plugins(
434 opts,
435 vec![rolldown::plugin::__inner::Pluginable::new_shared(
436 AliasBunSqlite { shim_src: SHIM_SRC },
437 )],
438 )
439 .map_err(|e| anyhow::anyhow!("bundler init: {e:?}"))?;
440
441 let rt = tokio::runtime::Builder::new_current_thread()
444 .enable_all()
445 .build()
446 .context("normalize runtime")?;
447 let out = rt
448 .block_on(bundler.generate())
449 .map_err(|e| anyhow::anyhow!("{e:?}"))?;
450 for w in &out.warnings {
451 tracing::warn!("normalize bundler warning: {w:?}");
452 }
453 let mut chunks = Vec::new();
454 for a in &out.assets {
455 if let rolldown_common::Output::Chunk(c) = a {
456 chunks.push(c);
457 }
458 }
459 if chunks.len() != 1 {
460 bail!(
461 "expected exactly 1 chunk, got {} ({:?})",
462 chunks.len(),
463 chunks
464 .iter()
465 .map(|c| c.filename.as_str())
466 .collect::<Vec<_>>()
467 );
468 }
469 Ok(chunks[0].code.clone())
470}
471
472fn content_hash(entry: &Path) -> Result<String> {
477 let mut h = Sha256::new();
478 let bytes = std::fs::read(entry).with_context(|| format!("read {}", entry.display()))?;
479 h.update(bytes);
480 h.update([0xff]);
481 h.update(SHIM_SRC.as_bytes());
482 h.update(NORMALIZER_VERSION.as_bytes());
483 Ok(hex::encode(h.finalize()))
485}
486
487fn path_key(entry: &Path) -> String {
489 let mut h = Sha256::new();
490 h.update(entry.to_string_lossy().as_bytes());
491 hex::encode(h.finalize())[..16].to_string()
492}
493
494fn warm(out: &Path, want: &str) -> bool {
495 let hash_path = hash_path_of(out);
496 let Ok(h) = std::fs::read_to_string(&hash_path) else {
497 return false;
498 };
499 h.trim() == want && std::fs::metadata(out).map(|m| m.len() > 0).unwrap_or(false)
500}
501
502fn hash_path_of(out: &Path) -> PathBuf {
503 let mut s = out.as_os_str().to_os_string();
504 s.push(".hash");
505 PathBuf::from(s)
506}
507
508fn atomic_write(dest: &Path, data: &str) -> Result<()> {
511 let dir = dest.parent().context("dest has no parent")?;
512 std::fs::create_dir_all(dir).with_context(|| format!("mkdir {}", dir.display()))?;
513 let name = dest
514 .file_name()
515 .context("dest has no name")?
516 .to_string_lossy()
517 .into_owned();
518 let tmp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
519 std::fs::write(&tmp, data).with_context(|| format!("write {}", tmp.display()))?;
520 std::fs::rename(&tmp, dest).with_context(|| format!("rename {}", dest.display()))?;
521 Ok(())
522}
523
524fn sweep_stale_tmp(dest: &Path) {
526 let (Some(dir), Some(name)) = (dest.parent(), dest.file_name()) else {
527 return;
528 };
529 let prefix = format!(".{}.", name.to_string_lossy());
530 let Ok(rd) = std::fs::read_dir(dir) else {
531 return;
532 };
533 for e in rd.flatten() {
534 let fname = e.file_name().to_string_lossy().into_owned();
535 if fname.starts_with(&prefix) && fname.ends_with(".tmp") {
536 let stale = e
537 .metadata()
538 .ok()
539 .and_then(|m| m.modified().ok())
540 .and_then(|t| t.elapsed().ok())
541 .map(|age| age.as_secs() > STALE_TMP_SECS)
542 .unwrap_or(false);
543 if stale {
544 let _ = std::fs::remove_file(e.path());
545 }
546 }
547 }
548}
549
550fn rss_kb() -> i64 {
551 std::fs::read_to_string("/proc/self/status")
552 .ok()
553 .and_then(|s| {
554 s.lines()
555 .find(|l| l.starts_with("VmRSS:"))
556 .and_then(|l| l.split_whitespace().nth(1))
557 .and_then(|v| v.parse().ok())
558 })
559 .unwrap_or(-1)
560}
561
562pub fn normalize_or_raw_sync(root: Option<&Path>, entry: &Path) -> (PathBuf, Outcome) {
570 let raw = entry.to_path_buf();
571 if entry
573 .file_name()
574 .map(|n| n.to_string_lossy().ends_with(".normalized.mjs"))
575 .unwrap_or(false)
576 {
577 return (raw.clone(), Outcome::Passthrough(raw));
578 }
579 let Some(root) = root else {
580 return (raw.clone(), Outcome::Skipped(raw));
582 };
583 if matches!(
585 std::env::var("OCSERVE_PLUGIN_NORMALIZE").as_deref(),
586 Ok("0")
587 ) {
588 return (raw.clone(), Outcome::Skipped(raw));
589 }
590
591 let work = match entry.canonicalize() {
592 Ok(w) => w,
593 Err(e) => {
594 return (
595 raw.clone(),
596 Outcome::Fallback {
597 path: raw,
598 err: format!("canonicalize {}: {e}", entry.display()),
599 },
600 );
601 }
602 };
603 let hash = match content_hash(&work) {
604 Ok(h) => h,
605 Err(e) => {
606 return (
607 raw.clone(),
608 Outcome::Fallback {
609 path: raw,
610 err: format!("{e:#}"),
611 },
612 );
613 }
614 };
615
616 let stem = work
617 .file_stem()
618 .map(|s| s.to_string_lossy().into_owned())
619 .unwrap_or_else(|| "index".into());
620 let out_name = format!("{stem}.normalized.mjs");
621 let beside = work.with_file_name(&out_name);
622 let data_dir = root.join(path_key(&work));
623 let data_out = data_dir.join(&out_name);
624 let hash_file = root.join(path_key(&work)).join(format!("{out_name}.hash"));
625
626 for c in [&beside, &data_out] {
629 if warm(c, &hash) {
630 return (c.clone(), Outcome::Warm(c.clone()));
631 }
632 }
633
634 let rss_before = rss_kb();
636 let t0 = std::time::Instant::now();
637 let code = match bundle(&work) {
638 Ok(c) => c,
639 Err(e) => {
640 return (
641 raw.clone(),
642 Outcome::Fallback {
643 path: raw,
644 err: format!("bundle: {e:#}"),
645 },
646 );
647 }
648 };
649
650 let needs = needs_ancestry(&code);
652 let (dest, other) = if needs {
653 (beside.clone(), Some(data_out.clone()))
654 } else {
655 (data_out.clone(), Some(beside.clone()))
656 };
657
658 if let Err(e) = atomic_write(&dest, &code) {
659 return (
660 raw.clone(),
661 Outcome::Fallback {
662 path: raw,
663 err: format!("write: {e:#}"),
664 },
665 );
666 }
667 if let Err(e) = atomic_write(&hash_path_of(&dest), &hash) {
669 tracing::warn!("normalize hash write failed (will rebuild next boot): {e:#}");
670 }
671 if let Some(o) = other
674 && o != dest
675 {
676 let _ = std::fs::remove_file(&o);
677 let _ = std::fs::remove_file(hash_path_of(&o));
678 }
679 sweep_stale_tmp(&dest);
680 let _ = hash_file; (
683 dest.clone(),
684 Outcome::Built {
685 path: dest,
686 ms: t0.elapsed().as_millis(),
687 beside: needs,
688 rss_before_kb: rss_before,
689 rss_after_kb: rss_kb(),
690 },
691 )
692}
693
694#[cfg(test)]
699mod tests {
700 use super::*;
701
702 static ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
704
705 fn real_entry(pkg: &str, rel: &str) -> Option<PathBuf> {
707 let home = std::env::var("HOME").ok()?;
708 let p = PathBuf::from(home).join(pkg).join(rel);
709 p.exists().then_some(p)
710 }
711
712 fn scratch() -> (PathBuf, PathBuf) {
713 let base = std::env::temp_dir().join(format!(
714 "ocserve-norm-test-{}-{:?}",
715 std::process::id(),
716 std::thread::current().id()
717 ));
718 let _ = std::fs::remove_dir_all(&base);
719 std::fs::create_dir_all(&base).unwrap();
720 let data = base.join("data");
721 std::fs::create_dir_all(&data).unwrap();
722 (base, data)
723 }
724
725 fn write_entry(base: &Path, name: &str, body: &str) -> PathBuf {
726 let p = base.join(name);
727 std::fs::write(&p, body).unwrap();
728 p
729 }
730
731 #[test]
734 fn scanner_real_magic_context_needs_ancestry() {
735 let Some(e) = real_entry(
736 ".cache/opencode/packages/@cortexkit/opencode-magic-context@latest/node_modules/@cortexkit/opencode-magic-context",
737 "dist/index.js",
738 ) else {
739 eprintln!("skip: magic-context not in opencode cache");
740 return;
741 };
742 let code = bundle(&e).expect("bundle magic-context");
743 assert!(
744 needs_ancestry(&code),
745 "computed @huggingface/transformers import MUST classify needs-ancestry \
746 (this is the ground truth that catches metadata-based scanners)"
747 );
748 }
749
750 #[test]
751 fn scanner_real_reliary8_is_clean() {
752 let home = std::env::var("HOME").unwrap();
753 let e = PathBuf::from(home).join("src/reliary8/opencode-plugin/dist/index.js");
754 if !e.exists() {
755 eprintln!("skip: reliary8 plugin absent");
756 return;
757 }
758 let code = bundle(&e).expect("bundle reliary8");
759 assert!(
760 !needs_ancestry(&code),
761 "reliary8 (builtins only) must be clean → data-dir emit, no repo writes"
762 );
763 }
764
765 #[test]
766 fn scanner_real_codex_auth_needs_ancestry() {
767 let Some(e) = real_entry(
773 ".cache/opencode/packages/@iam-brain/opencode-codex-auth@latest/node_modules/@iam-brain/opencode-codex-auth",
774 "dist/index.js",
775 ) else {
776 eprintln!("skip: codex-auth not in opencode cache");
777 return;
778 };
779 let code = bundle(&e).expect("bundle codex-auth");
780 assert!(
781 needs_ancestry(&code),
782 "codex-auth dynamically imports proper-lockfile at runtime"
783 );
784 }
785
786 #[test]
787 fn scanner_shim_identifier_stays_clean() {
788 let (base, _d) = scratch();
795 let e = write_entry(
796 &base,
797 "shimuser.js",
798 r#"import { Database } from "bun:sqlite";
799export default { Database };"#,
800 );
801 let code = bundle(&e).expect("bundle shim user");
802 assert!(
803 !needs_ancestry(&code),
804 "shim import(BUN_SPEC) must resolve via const_map to bun:sqlite (scheme-clean)"
805 );
806 let _ = std::fs::remove_dir_all(&base);
807 }
808
809 #[test]
810 fn scanner_synthetic_computed_import_needs_ancestry() {
811 let (base, _d) = scratch();
812 let e = write_entry(
813 &base,
814 "dyn.js",
815 r#"const pkg = "some-dep" + "-x";
816export default await import(pkg);"#,
817 );
818 let code = bundle(&e).expect("bundle synthetic dyn");
819 assert!(needs_ancestry(&code));
820 let _ = std::fs::remove_dir_all(&base);
821 }
822
823 #[test]
824 fn scanner_node_relative_const_are_clean() {
825 let (base, _d) = scratch();
826 std::fs::write(base.join("sib.js"), "export const x = 1;\n").unwrap();
827 let e = write_entry(
831 &base,
832 "ok.js",
833 r#"import fs from "node:fs";
834import path2 from "path";
835import { x } from "./sib.js";
836const P = "node:" + "crypto";
837const dyn = await import(P);
838export default { fs, path2, x, dyn };"#,
839 );
840 let code = bundle(&e).expect("bundle clean fixture");
841 assert!(
842 !needs_ancestry(&code),
843 "node:/relative/builtin + const-resolved node: spec are clean"
844 );
845 let _ = std::fs::remove_dir_all(&base);
846 }
847
848 #[test]
851 fn warm_hash_skips_rebuild() {
852 let _g = ENV_LOCK.lock();
853 unsafe {
855 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
856 };
857 let (base, data) = scratch();
858 let e = write_entry(&base, "p.js", "export default 1;\n");
859 let (p1, o1) = normalize_or_raw_sync(Some(&data), &e);
860 assert!(matches!(o1, Outcome::Built { .. }), "first: {o1:?}");
861 let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
862 assert!(matches!(o2, Outcome::Warm(_)), "second: {o2:?}");
863 assert_eq!(p1, p2);
864 let _ = std::fs::remove_dir_all(&base);
865 }
866
867 #[test]
868 fn stale_entry_rebuilds() {
869 let _g = ENV_LOCK.lock();
870 unsafe {
872 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
873 };
874 let (base, data) = scratch();
875 let e = write_entry(&base, "p.js", "export default 1;\n");
876 let (_, o1) = normalize_or_raw_sync(Some(&data), &e);
877 assert!(matches!(o1, Outcome::Built { .. }));
878 std::fs::write(&e, "export default 2; // changed\n").unwrap();
879 let (_, o2) = normalize_or_raw_sync(Some(&data), &e);
880 assert!(matches!(o2, Outcome::Built { .. }), "changed: {o2:?}");
881 let _ = std::fs::remove_dir_all(&base);
882 }
883
884 #[test]
885 fn normalize_error_falls_back_to_raw() {
886 let _g = ENV_LOCK.lock();
887 unsafe {
889 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
890 };
891 let (base, data) = scratch();
892 let e = write_entry(&base, "bad.js", "import { from 'broken");
893 let (p, o) = normalize_or_raw_sync(Some(&data), &e);
894 assert_eq!(p, e, "fallback path MUST be the raw entry");
895 assert!(matches!(o, Outcome::Fallback { .. }), "{o:?}");
896 let _ = std::fs::remove_dir_all(&base);
897 }
898
899 #[test]
900 fn kill_switch_disables_building() {
901 let _g = ENV_LOCK.lock();
902 let (base, data) = scratch();
903 let e = write_entry(&base, "p.js", "export default 1;\n");
904 unsafe { std::env::set_var("OCSERVE_PLUGIN_NORMALIZE", "0") };
906 let (p, o) = normalize_or_raw_sync(Some(&data), &e);
907 unsafe {
909 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
910 };
911 assert_eq!(p, e);
912 assert!(matches!(o, Outcome::Skipped(_)), "{o:?}");
913 let built = std::fs::read_dir(&data).map(|d| d.count()).unwrap_or(0);
915 assert_eq!(built, 0, "kill switch must not construct outputs");
916 let _ = std::fs::remove_dir_all(&base);
917 }
918
919 #[test]
920 fn wipe_then_normalize_rebuilds() {
921 let _g = ENV_LOCK.lock();
922 unsafe {
924 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
925 };
926 let (base, data) = scratch();
927 let e = write_entry(&base, "p.js", "export default 1;\n");
928 let (p1, o1) = normalize_or_raw_sync(Some(&data), &e);
929 assert!(matches!(o1, Outcome::Built { .. }));
930 std::fs::remove_file(&p1).unwrap();
931 std::fs::remove_file(hash_path_of(&p1)).unwrap();
932 let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
933 assert!(matches!(o2, Outcome::Built { .. }), "after wipe: {o2:?}");
934 assert!(p2.exists());
935 let _ = std::fs::remove_dir_all(&base);
936 }
937
938 #[test]
939 fn suffix_guard_passthrough() {
940 let _g = ENV_LOCK.lock();
941 unsafe {
943 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
944 };
945 let (base, data) = scratch();
946 let already = base.join("thing.normalized.mjs");
947 std::fs::write(&already, "// sentinel, must not be re-bundled\n").unwrap();
948 let (p, o) = normalize_or_raw_sync(Some(&data), &already);
949 assert_eq!(p, already);
950 assert!(matches!(o, Outcome::Passthrough(_)), "{o:?}");
951 let after = std::fs::read_to_string(&already).unwrap();
952 assert!(after.contains("sentinel"), "output must be untouched");
953 let _ = std::fs::remove_dir_all(&base);
954 }
955
956 #[test]
957 fn dest_routing_clean_goes_to_data_dir() {
958 let _g = ENV_LOCK.lock();
959 unsafe {
961 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
962 };
963 let (base, data) = scratch();
964 let e = write_entry(&base, "plain.js", "export default 42;\n");
965 let (p, o) = normalize_or_raw_sync(Some(&data), &e);
966 assert!(matches!(o, Outcome::Built { beside: false, .. }), "{o:?}");
967 assert!(
968 p.starts_with(&data),
969 "self-contained bundle must emit into ocserve's data dir, not beside entry: {}",
970 p.display()
971 );
972 assert!(!base.join("plain.normalized.mjs").exists());
974 let _ = std::fs::remove_dir_all(&base);
975 }
976
977 #[test]
978 fn dest_routing_needs_ancestry_goes_beside_entry() {
979 let _g = ENV_LOCK.lock();
980 unsafe {
982 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
983 };
984 let (base, data) = scratch();
985 let e = write_entry(
986 &base,
987 "dyn.js",
988 r#"const pkg = "some-dep" + "-x";
989export default await import(pkg);"#,
990 );
991 let (p, o) = normalize_or_raw_sync(Some(&data), &e);
992 assert!(matches!(o, Outcome::Built { beside: true, .. }), "{o:?}");
993 let expected = base.join("dyn.normalized.mjs").canonicalize().unwrap();
994 let actual = p.canonicalize().unwrap();
995 assert_eq!(actual, expected, "K4: beside the resolved entry");
996 let _ = std::fs::remove_dir_all(&base);
997 }
998
999 #[test]
1000 fn flip_destination_removes_stale_pair() {
1001 let _g = ENV_LOCK.lock();
1002 unsafe {
1004 std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
1005 };
1006 let (base, data) = scratch();
1007 let e = write_entry(&base, "flip.js", "export default 7;\n");
1008 let (p, _) = normalize_or_raw_sync(Some(&data), &e);
1009 assert!(p.starts_with(&data), "clean → data dir first");
1010 let stale = base.join("flip.normalized.mjs");
1012 std::fs::write(&stale, "// stale\n").unwrap();
1013 std::fs::write(&e, "export default 8;\n").unwrap();
1015 let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
1016 assert!(matches!(o2, Outcome::Built { beside: false, .. }), "{o2:?}");
1017 assert!(p2.starts_with(&data));
1018 assert!(
1019 !stale.exists(),
1020 "stale beside-entry pair must be cleaned (spike-leftover class)"
1021 );
1022 let _ = std::fs::remove_dir_all(&base);
1023 }
1024 #[test]
1038 fn normalizer_never_minifies() {
1039 let f = include_str!("normalize.rs");
1040 let opts = f
1041 .split("let opts = BundlerOptions {")
1042 .nth(1)
1043 .expect("bundler options block");
1044 let block = &opts[..opts.find("};").expect("options end")];
1045 assert!(
1046 block.contains("minify: Some(rolldown::RawMinifyOptions::Bool(false))"),
1047 "the normalizer must disable minification (oxc compressor loop panic)"
1048 );
1049 }
1050}