Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

Merge #87: UTF-8 BOM in Python and Node files

EL4CTEOed97d8735343
diff --cc src/node.rs
index a2a3ee2,2a6cd64..bf756a0
--- a/src/node.rs
+++ b/src/node.rs
@@@ -710,231 -648,6 +710,304 @@@ fn without_shim(text: &str, port: &Port
mod tests {
use super::*;
++ #[test]
++ fn utf8_bom_node_file_scans_enables_and_restores_byte_for_byte() {
++ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
++ eprintln!("no node on PATH, skipping");
++ return;
++ }
++ let cases = [
++ (
++ "func",
++ b"\xef\xbb\xbfexport function crunch(n) {\r\n let t = 0;\r\n for (let i = 0; i < n; i++) t += (i * i) % 97;\r\n return t;\r\n}\r\n"
++ .as_slice(),
++ ),
++ (
++ "const",
++ b"\xef\xbb\xbfexport const crunch = (n) => {\r\n let t = 0;\r\n for (let i = 0; i < n; i++) t += (i * i) % 97;\r\n return t;\r\n};\r\n"
++ .as_slice(),
++ ),
++ ];
++ let tmp = std::env::temp_dir();
++ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
++ let base = tmp.join(format!("fa-node-bom-{}", std::process::id()));
++ let _ = fs::remove_dir_all(&base);
++ // Bare `const` after line-1 BOM matches, while non-line-1 U+FEFF is not skipped.
++ assert_eq!(declaration("\u{feff}const crunch = (n) => n;\n", "const", "crunch"), Some("\u{feff}".len()));
++ assert_eq!(declaration("const a = 1;\n\u{feff}const crunch = (n) => n;\n", "const", "crunch"), None);
++ // package.json with UTF-8 BOM is still recognized as ESM.
++ let pkg_dir = base.join("bom-pkg");
++ fs::create_dir_all(&pkg_dir).unwrap();
++ fs::write(pkg_dir.join("package.json"), b"\xef\xbb\xbf{\"type\": \"module\"}\r\n").unwrap();
++ assert!(is_esm(&pkg_dir, &pkg_dir.join("work.js")));
++ for (name, work_bytes) in cases {
++ let dir = base.join(name);
++ fs::create_dir_all(&dir).unwrap();
++ fs::write(dir.join("work.mjs"), work_bytes).unwrap();
++ fs::write(
++ dir.join("app.mjs"),
++ b"\xef\xbb\xbfimport { crunch } from './work.mjs';\r\nlet s = 0;\r\nfor (let r = 0; r < 200; r++) s += crunch(100000);\r\nconsole.log(s);\r\n",
++ )
++ .unwrap();
++ let scanned = crate::pipeline::scan(&dir, vec!["node".into(), "app.mjs".into()], None).unwrap();
++ let h =
++ scanned.hotspots.iter().find(|h| h.name == "crunch").unwrap_or_else(|| {
++ panic!("{name}: BOM node file should appear in scan, got {:?}", scanned.hotspots)
++ });
++ assert!(h.portable(), "{name}: crunch should be portable, got {:?}", h.blockers);
++ crate::pipeline::port(&dir, Some("work.crunch"), 10).unwrap();
++ let ctx = Ctx::open(&dir).unwrap();
++ let port = &ctx.state.ports["work.crunch"];
++ assert!(!port.sources.is_empty(), "{name}: verbatim source should be captured for BOM file");
++ assert!(!ctx.stale(port), "{name}: fresh BOM port must not be reported stale");
++ crate::pipeline::enable(&dir, Some("work.crunch"), true).unwrap();
++ let enabled_bytes = fs::read(dir.join("work.mjs")).unwrap();
++ assert!(enabled_bytes.starts_with(b"\xef\xbb\xbf"), "{name}: enable must preserve UTF-8 BOM");
++ if name == "const" {
++ let text = String::from_utf8_lossy(&enabled_bytes);
++ assert!(
++ text.starts_with("\u{feff}export let crunch"),
++ "{name}: const must switch to let after BOM: {text}"
++ );
++ }
++ assert!(!Ctx::open(&dir).unwrap().stale(port), "{name}: enabled BOM port must not be reported stale");
++ crate::pipeline::disable(&dir, Some("work.crunch")).unwrap();
++ let restored_bytes = fs::read(dir.join("work.mjs")).unwrap();
++ assert_eq!(restored_bytes, work_bytes, "{name}: disable must restore BOM file byte for byte");
++ let edited = String::from_utf8_lossy(work_bytes).replace("let t = 0;", "let t = 1;");
++ fs::write(dir.join("work.mjs"), edited.as_bytes()).unwrap();
++ let stale_after_edit = Ctx::open(&dir).unwrap().stale(port);
++ let _ = fs::remove_dir_all(&dir);
++ assert!(stale_after_edit, "{name}: editing first-line BOM function must trigger stale detection");
++ }
++ let _ = fs::remove_dir_all(&base);
++ }
++
+ #[test]
+ fn scan_handles_regex_literals_and_division_ambiguity() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let tmp = std::env::temp_dir();
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-node-regex-lexer-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ // Put regexes with quotes, character-class slashes, and return-regex above a single hot
+ // function so V8 sampling reliably captures it even on fast CI runners.
+ fs::write(
+ dir.join("work.mjs"),
+ "export function stripQuotes(s) {\n\
+ \x20 return s.replace(/['\"]/g, \"\").replace(/[/']/g, \"-\");\n\
+ }\n\n\
+ export function hasQuote(s) {\n\
+ \x20 return /'/.test(s);\n\
+ }\n\n\
+ export function afterRegex(n) {\n\
+ \x20 let t = 0;\n\
+ \x20 for (let i = 0; i < n; i++) t += (i * i) % 97;\n\
+ \x20 return t;\n\
+ }\n",
+ )
+ .unwrap();
+ fs::write(
+ dir.join("app.mjs"),
+ "import { stripQuotes, hasQuote, afterRegex } from './work.mjs';\n\
+ let s = stripQuotes(\"a/b'c\") + hasQuote(\"'\");\n\
+ let total = 0;\n\
+ for (let r = 0; r < 200; r++) total += afterRegex(100000);\n\
+ console.log(s, total);\n",
+ )
+ .unwrap();
+ let scanned = crate::pipeline::scan(&dir, vec!["node".into(), "app.mjs".into()], None);
+ let _ = fs::remove_dir_all(&dir);
+ let scanned = scanned.unwrap();
+ let h = scanned.hotspots.iter().find(|h| h.name == "afterRegex").unwrap_or_else(|| {
+ panic!("missing hotspot afterRegex; got {:?}", scanned.hotspots.iter().map(|h| &h.name).collect::<Vec<_>>())
+ });
+ assert!(h.portable(), "afterRegex should be portable, got blockers {:?}", h.blockers);
+ }
+
+ #[test]
+ fn code_only_handles_regex_and_division_deterministically() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let tmp = std::env::temp_dir();
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-node-codeonly-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ // Export codeOnly/describe from a temporary copy of runner.mjs to assert exact blanking on tricky tokens
+ // (and verify linear time on adversarial unterminated-slash lines).
+ let stripped = RUNNER.split("const [mode, jobPath]").next().unwrap();
+ fs::write(dir.join("lib.mjs"), format!("{stripped}\nexport {{ codeOnly, describe }};\n")).unwrap();
+ fs::write(
+ dir.join("check.mjs"),
+ r#"import assert from "node:assert/strict";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { codeOnly, describe } from "./lib.mjs";
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+
+// Division preserved intact (two slashes on the same line pin every guard against regex misreads)
+for (const line of [
+ "const r = a / b / c;",
+ "const r = (a + b) / 2 / arr[0];",
+ "const r = arr[0] / 2 / 3;",
+ "const r = obj.return / 2 / 3;",
+ "const r = i++ / 2 / 3;",
+ "const r = i-- / 2 / 3;",
+ "const r = 10 / 2 / 3;",
+ "const r = 1.5 / 2 / 3;",
+ 'const r = "10" / 2 / 3;',
+ "const r = of / 2 / 3;",
+ "const r = { a: 1 } / 2 / 3;",
+ "return { a: 1 } / 2 / 3;",
+ "const r = { a: () => { return 1; } } / 2 / 3;",
+ "const r = π / 2 / 3;",
+ "const r = 数量 / 2 / 3;",
+ "const r = a! / console.log(1) / 2;",
+ "const r = a!! / 2 / 3;",
+]) {
+ assert.equal(codeOnly(line), line.replace('"10"', '" "'), `division misread: ${line}`);
+}
+assert.equal(codeOnly("const r = /a/ / 2 / 3;"), "const r = / / / 2 / 3;");
+
+// Division followed by a quoted line comment (must not pair `/` with `//`)
+for (const prefix of [
+ "const x = y / 2",
+ "const x = obj.return / 2",
+ "const x = i++ / 2",
+ "const x = of / 2",
+ "const x = { a: 1 } / 2",
+ "const x = π / 2",
+ "const x = m.get('a')! / 2",
+]) {
+ const src = `${prefix}; // don't "break"\nconst z = 1;`;
+ const res = codeOnly(src);
+ assert.equal(res.length, src.length, `length drift for ${prefix}`);
+ assert.ok(res.startsWith(`${prefix.replace("'a'", "' '")}; `), `prefix damaged: ${res}`);
+ assert.ok(res.endsWith("\nconst z = 1;"), `next line swallowed for ${prefix}: ${res}`);
+}
+
+// Regex literals: start-of-file, quotes, char-class slashes, escapes, flags, keywords, blocks, prefix `!`
+assert.equal(codeOnly("/'/.test(s);"), "/ /.test(s);");
+assert.equal(codeOnly("/>/.test(s);"), "/ /.test(s);");
+assert.equal(codeOnly("a < /'/.source.length;"), "a < / /.source.length;");
+assert.equal(codeOnly("s.replace(/['\"]/g, \"\")"), "s.replace(/ /g, \"\")");
+assert.equal(codeOnly("s.replace(/[/]/g, \"-\")"), "s.replace(/ /g, \" \")");
+assert.equal(codeOnly("return /https?:\\/\\//.test(s);"), "return / /.test(s);");
+assert.equal(codeOnly("const t = `a / b / 'c'`;\nconst ok = 1;"), "const t = ` `;\nconst ok = 1;");
+
+for (const [src, expected] of [
+ ["return /'/.test(s);", "return / /.test(s);"],
+ ["case /'/: break;", "case / /: break;"],
+ ["throw /'/;", "throw / /;"],
+ ["typeof /'/", "typeof / /"],
+ ["void /'/", "void / /"],
+ ["delete /'/", "delete / /"],
+ ["new /'/", "new / /"],
+ ["yield /'/", "yield / /"],
+ ["await /'/", "await / /"],
+ ["if (a) b(); else /'/.test(s);", "if (a) b(); else / /.test(s);"],
+ ["do /'/.test(s); while (0);", "do / /.test(s); while (0);"],
+ ["x in /'/", "x in / /"],
+ ["function foo() {} /'/.test(s);", "function foo() {} / /.test(s);"],
+ ["if (ok) { a(); } /'/.test(s);", "if (ok) { a(); } / /.test(s);"],
+ ["const f = () => { return 1; } /'/.test(s);", "const f = () => { return 1; } / /.test(s);"],
+ ["class C {} /'/.test(s);", "class C {} / /.test(s);"],
+ ["class C extends ns.Base {} /'/.test(s);", "class C extends ns.Base {} / /.test(s);"],
+ ["if (!/'/.test(s)) {}", "if (!/ /.test(s)) {}"],
+ ["foo()\n!/'/.test(s);", "foo()\n!/ /.test(s);"],
+ ["foo() /*\n*/ !/'/.test(s);", "foo() \n !/ /.test(s);"],
+ ["a != /'/.source;", "a != / /.source;"],
+ ["a !== /'/.source;", "a !== / /.source;"],
+]) {
+ assert.equal(codeOnly(src), expected, `regex misread: ${src}`);
+}
+
+// Unterminated `/` on a line never crosses LF, CRLF, or trailing backslash before newline
+assert.equal(codeOnly("x = /a\nconst b = 1 / 2;"), "x = /a\nconst b = 1 / 2;");
+assert.equal(codeOnly("x = /a\r\nconst b = 1 / 2;"), "x = /a\r\nconst b = 1 / 2;");
+assert.equal(codeOnly("x = /a\\\nconst b = /'/;"), "x = /a\\\nconst b = / /;");
+
+// Escaped quotes inside regex and comments don't leak into later functions
+const modFile = path.join(root, "sample.mjs");
+const sample = [
+ "export function f1(s) { return s.replace(/['\"]/g, ''); }",
+ "export function f2(s) { return s.replace(/[/]/g, '-'); }",
+ "export function f3(s) { return /'/.test(s); }",
+ "export function f4(a, b, c) { return a / b / c; }",
+ "export function f5(y) { const x = y / 2; // don't break\n return x; }",
+ "export function f6(s) { const t = `a / b`; return t + s; }",
+].join("\n") + "\n";
+fs.writeFileSync(modFile, sample);
+for (const [line0, name] of [[0, "f1"], [1, "f2"], [2, "f3"], [3, "f4"], [4, "f5"], [6, "f6"]]) {
+ const info = describe(modFile, line0, name, null, root);
+ assert.ok(info, `describe missed ${name}`);
+ assert.deepEqual(info.blockers, [], `${name} had unexpected blockers: ${info.blockers}`);
+}
+
+// JSX closing tags (`</tag>`, `</>`) and self-closing tags (`/>`) must not be misread as regex
+const jsxFile = path.join(root, "sample.jsx");
+const jsxSample = [
+ 'export function ViewA() { return <span>Home</span><a href="/about">About</a>; }',
+ "export function afterA(x) { return x + 1; }",
+ "export function ViewB() { return <span>a</span><span>{console.log(1)}</span>; }",
+ "export function ViewC(a) { return <div><span>a</span>{a && <span>b</span>}</div>; }",
+ "export function ViewD() { return <Icon size={16} /><button onClick={() => console.log(1)}>ok</button>; }",
+ "export function ViewFrag() { return <><span>a</span></>; }",
+ "export function afterFrag(x) { return x + 2; }",
+].join("\n") + "\n";
+fs.writeFileSync(jsxFile, jsxSample);
+for (const [line0, name] of [[1, "afterA"], [3, "ViewC"], [6, "afterFrag"]]) {
+ const info = describe(jsxFile, line0, name, null, root);
+ assert.ok(info, `describe missed JSX ${name}`);
+ assert.deepEqual(info.blockers, [], `JSX ${name} had unexpected blockers: ${info.blockers}`);
+}
+for (const [line0, name] of [[2, "ViewB"], [4, "ViewD"]]) {
+ const info = describe(jsxFile, line0, name, null, root);
+ assert.ok(info, `describe missed JSX ${name}`);
+ assert.ok(info.blockers.some((b) => b.includes("console")), `JSX ${name} lost console blocker: ${info.blockers}`);
+}
+
+// TypeScript postfix non-null assertion `!` before `/` must not swallow following functions or console I/O
+const tsxFile = path.join(root, "sample.tsx");
+const tsxSample = [
+ "export function tsDiv(m) { const x = m.get('a')! / 2; // don't break",
+ " return x; }",
+ "export function afterTs(x) { return x + 1; }",
+ "export function tsConsole(a) { return a! / console.log(1) / 2; }",
+].join("\n") + "\n";
+fs.writeFileSync(tsxFile, tsxSample);
+const afterTs = describe(tsxFile, 2, "afterTs", null, root);
+assert.ok(afterTs, "describe missed afterTs");
+assert.deepEqual(afterTs.blockers, [], `afterTs had unexpected blockers: ${afterTs.blockers}`);
+const tsConsole = describe(tsxFile, 3, "tsConsole", null, root);
+assert.ok(tsConsole, "describe missed tsConsole");
+assert.ok(tsConsole.blockers.some((b) => b.includes("console")), `tsConsole lost console blocker: ${tsConsole.blockers}`);
+
+// Adversarial inputs with unterminated slashes (odd repeat count prevents even-pairing false passes)
+for (const worst of [
+ "x = /a\n".repeat(5001) + "const ok = 1;",
+ "x = /[".repeat(10000) + "\nconst ok = 1;",
+]) {
+ const res = codeOnly(worst);
+ assert.equal(res, worst);
+}
+"#,
+ )
+ .unwrap();
+ let out = Command::new("node").arg("check.mjs").current_dir(&dir).output().unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", combined(&out));
+ }
+
#[test]
fn bun_and_deno_get_their_own_command_lines() {
let args = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
diff --cc src/node/runner.mjs
index e814692,800f064..fb14fba
--- a/src/node/runner.mjs
+++ b/src/node/runner.mjs
@@@ -675,9 -112,8 +675,9 @@@ const parsed = new Map()
function describe(file, line0, name, entry, root) {
if (!parsed.has(file)) {
try {
- const src = readFileSync(file, "utf8");
+ const src = readFileSync(file, "utf8").replace(/^\uFEFF/, "");
- parsed.set(file, { src, code: codeOnly(src), top: topLevelFunctions(src) });
+ const code = codeOnly(src, { jsx: /\.[jt]sx$/i.test(file) });
+ parsed.set(file, { src, code, top: topLevelFunctions(src), imports: importsOf(src, code) });
} catch {
parsed.set(file, null);
}