use std::collections::BTreeMap;
use quickjs::module::{LoadedModule, ModuleLoader};
struct MemoryLoader {
sources: BTreeMap<String, Vec<u8>>,
}
impl MemoryLoader {
fn resolve(specifier: &str, referrer: &str) -> String {
if referrer.is_empty() {
return specifier.to_string();
}
let dir = match referrer.rfind('/') {
Some(index) => &referrer[..index],
None => "",
};
let joined = format!("{dir}/{specifier}");
let mut parts: Vec<&str> = Vec::new();
for part in joined.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop();
}
other => parts.push(other),
}
}
format!("/{}", parts.join("/"))
}
}
impl ModuleLoader for MemoryLoader {
fn load(
&self,
specifier: &str,
_attributes: &[(String, String)],
referrer: &str,
) -> Result<LoadedModule, String> {
let name = Self::resolve(specifier, referrer);
let source = self
.sources
.get(&name)
.cloned()
.ok_or_else(|| format!("could not load module filename '{specifier}'"))?;
Ok(LoadedModule {
url: format!("file://{name}"),
name,
source,
})
}
}
fn run(files: &[(&str, &str)]) -> String {
let rt = quickjs::Runtime::new();
let mut ctx = quickjs::Context::new(&rt);
let sources = files
.iter()
.map(|(name, source)| (format!("/m/{name}"), source.as_bytes().to_vec()))
.collect();
ctx.set_module_loader(Box::new(MemoryLoader { sources }));
match ctx.eval_module("/m/main.js") {
Ok(_) => ctx.output().to_string(),
Err(error) => panic!(
"{files:?} failed: {error}\noutput so far:\n{}",
ctx.output()
),
}
}
fn fails(files: &[(&str, &str)]) -> String {
let rt = quickjs::Runtime::new();
let mut ctx = quickjs::Context::new(&rt);
let sources = files
.iter()
.map(|(name, source)| (format!("/m/{name}"), source.as_bytes().to_vec()))
.collect();
ctx.set_module_loader(Box::new(MemoryLoader { sources }));
match ctx.eval_module("/m/main.js") {
Ok(_) => panic!("{files:?} should have failed"),
Err(error) => error.to_string(),
}
}
#[test]
fn an_imported_binding_is_the_exporters_cell_not_a_copy() {
assert_eq!(
run(&[
(
"main.js",
r#"
import def, * as ns from "./lib.js";
print("default:" + def);
print("keys:" + Object.keys(ns).join(","));
print("before:" + ns.counter);
ns.bump();
print("after:" + ns.counter);
"#
),
(
"lib.js",
r#"
export let counter = 0;
export function bump() { counter++ }
export default "D";
"#
),
]),
"default:D\nkeys:bump,counter,default\nbefore:0\nafter:1\n"
);
}
#[test]
fn a_cycle_hoists_before_any_body_runs() {
assert_eq!(
run(&[
(
"main.js",
r#"
import { a } from "./a.js";
print("main:" + a(1));
"#
),
(
"a.js",
r#"
import { b } from "./b.js";
export function a(x) { return x + 1 }
print("a sees b: " + typeof b);
"#
),
(
"b.js",
r#"
import { a } from "./a.js";
export function b(x) { return 2 * a(x) }
print("b sees a: " + typeof a);
print("b calls a: " + a(1));
"#
),
]),
"b sees a: function\nb calls a: 2\na sees b: function\nmain:2\n"
);
}
#[test]
fn a_namespace_is_sorted_frozen_and_tagged() {
assert_eq!(
run(&[
(
"main.js",
r#"
import * as ns from "./lib.js";
print(Object.keys(ns).join(","));
print(Object.prototype.toString.call(ns));
print(Object.isExtensible(ns));
try { ns.extra = 1 } catch (e) { print("assign threw") }
print("extra" in ns);
"#
),
(
"lib.js",
r#"
export const zebra = 1;
export const alpha = 2;
export function middle() {}
"#
),
]),
"alpha,middle,zebra\n[object Module]\nfalse\nassign threw\nfalse\n"
);
}
#[test]
fn re_exports_forward_names_and_their_own_default() {
assert_eq!(
run(&[
(
"main.js",
r#"
import * as barrel from "./barrel.js";
print("barrel keys:" + Object.keys(barrel).join(","));
print("a:" + barrel.a);
print("aliased:" + barrel.renamed);
print("ns:" + Object.keys(barrel.ns).join(","));
"#
),
(
"barrel.js",
r#"
export * from "./base.js";
export { b as renamed } from "./base.js";
export * as ns from "./base.js";
"#
),
(
"base.js",
r#"
export const a = "A";
export const b = "B";
export default "default-not-forwarded";
"#
),
]),
"barrel keys:a,b,ns,renamed\na:A\naliased:B\nns:a,b,default\n"
);
}
#[test]
fn json_and_text_modules_are_two_modules_from_one_file() {
assert_eq!(
run(&[
(
"main.js",
r#"
import data from "./data.json";
import text from "./data.json" with { type: "text" };
print(JSON.stringify(data));
print(typeof text);
print(JSON.stringify(text));
"#
),
("data.json", "{\"n\": [1, 2]}"),
]),
"{\"n\":[1,2]}\nstring\n\"{\\\"n\\\": [1, 2]}\"\n"
);
}
#[test]
fn a_dynamic_import_settles_after_the_current_script() {
assert_eq!(
run(&[
(
"main.js",
r#"
import("./lib.js").then(m => print("dynamic:" + m.value));
print("sync");
"#
),
("lib.js", "export const value = 42;\n"),
]),
"sync\ndynamic:42\n"
);
}
#[test]
fn a_missing_export_is_reported_at_link_time() {
let text = fails(&[
(
"main.js",
"import { nope } from \"./lib.js\";\nprint(nope);\n",
),
("lib.js", "export const yes = 1;\n"),
]);
assert!(
text.contains("Could not find export 'nope' in module"),
"unexpected error: {text}"
);
}
#[test]
fn a_module_has_no_arguments_and_no_global_leak() {
assert_eq!(
run(&[(
"main.js",
r#"
var leaked = 1;
function f(){ return leaked }
print(f());
print(typeof arguments);
print(typeof globalThis.leaked);
"#
),]),
"1\nundefined\nundefined\n"
);
}
#[test]
fn import_meta_names_the_module_and_marks_the_entry() {
assert_eq!(
run(&[
("main.js", "print(import.meta.url); import \"./lib.js\";\n"),
(
"lib.js",
"print(import.meta.url); print(import.meta.main);\n"
),
]),
"file:///m/lib.js\nfalse\nfile:///m/main.js\n"
);
}
#[test]
fn top_level_await_makes_evaluation_asynchronous() {
assert_eq!(
run(&[(
"main.js",
r#"
const v = await Promise.resolve(7);
print("awaited:" + v);
export const out = v;
"#
),]),
"awaited:7\n"
);
}
#[test]
fn a_dependency_with_top_level_await_is_waited_for() {
assert_eq!(
run(&[
(
"main.js",
"import { ready } from \"./dep.js\";\nprint(\"main sees: \" + ready);\n"
),
(
"dep.js",
"const p = Promise.resolve(\"ready\");\nawait p;\n\
print(\"dep done\");\nexport const ready = \"ready\";\n"
),
]),
"dep done\nmain sees: ready\n"
);
}
#[test]
fn a_rejection_at_the_top_level_stops_the_module() {
let text = fails(&[(
"main.js",
"await Promise.reject(new Error(\"top-level\"));\nprint(\"never\");\n",
)]);
assert!(text.contains("top-level"), "unexpected error: {text}");
}
#[test]
fn a_caught_top_level_rejection_continues() {
assert_eq!(
run(&[(
"main.js",
r#"
try { await Promise.reject(new Error("caught-here")) } catch (e) {
print("caught:" + e.message);
}
print("after");
"#
)]),
"caught:caught-here\nafter\n"
);
}
#[test]
fn a_module_top_level_using_is_disposed_at_the_end() {
assert_eq!(
run(&[(
"main.js",
"using a = { [Symbol.dispose]() { print('dispose a') } };\n\
using b = { [Symbol.dispose]() { print('dispose b') } };\n\
print('body');\n"
)]),
"body\ndispose b\ndispose a\n"
);
}
#[test]
fn a_module_top_level_using_is_disposed_when_the_body_throws() {
let text = fails(&[(
"main.js",
"using a = { [Symbol.dispose]() { print('dispose a') } };\n\
throw new Error('x');\n",
)]);
assert!(text.contains("Error: x"), "unexpected error: {text}");
}
#[test]
fn a_using_binding_cannot_be_exported() {
assert_eq!(
fails(&[(
"main.js",
"using a = { [Symbol.dispose]() {} };\nexport { a };\n"
)]),
"SyntaxError: exported variable 'a' does not exist\n"
);
}
#[test]
fn a_module_body_frame_is_anonymous() {
let text = fails(&[(
"main.js",
"function inner() { throw new Error('x') }\ninner();\n",
)]);
assert!(
text.contains("at <anonymous> (/m/main.js:2:6)"),
"expected an anonymous module frame, got: {text}"
);
}