use rquickjs::{
CatchResultExt, Context, Module, Runtime,
module::{WriteOptions, WriteOptionsEndianness},
};
use crate::error::JsError;
pub const BYTECODE_VERSION: &str = "rquickjs-0.14.0/quickjs-ng-0.16.2/le64";
pub const BUNDLE_NAME: &str = nsh_core::js::ENTRY_CHUNK;
pub fn compile_bytecode(source: &str, strip: bool) -> Result<Vec<u8>, JsError> {
compile_bytecode_with(source, strip, &[])
}
pub fn compile_bytecode_with(
source: &str,
strip: bool,
ui_sets: &[nsh_core::ui::Registry],
) -> Result<Vec<u8>, JsError> {
compile(
BUNDLE_NAME,
source,
crate::modules::ModuleTable::new(ui_sets),
strip,
)
}
pub fn compile_chunk_bytecode(
entry: &str,
chunks: &[(&str, &str)],
strip: bool,
ui_sets: &[nsh_core::ui::Registry],
) -> Result<Vec<Vec<u8>>, JsError> {
chunks
.iter()
.map(|&(id, source)| {
let table = crate::modules::ModuleTable::new(ui_sets);
{
let mut code = table.chunks.borrow_mut();
let others = chunks.iter().filter(|(other, _)| *other != id);
for (other, source) in std::iter::once(&(BUNDLE_NAME, entry)).chain(others) {
let source = crate::modules::ChunkCode::Source((*source).to_owned());
code.code.insert((*other).to_owned(), source);
}
}
compile(id, source, table, strip)
.map_err(|e| JsError::new(format!("chunk {id}: {}", e.message)))
})
.collect()
}
fn compile(
name: &str,
source: &str,
modules: crate::modules::ModuleTable,
strip: bool,
) -> Result<Vec<u8>, JsError> {
let rt = Runtime::new()?;
let ctx = Context::full(&rt)?;
ctx.with(|ctx| {
crate::modules::set_loader(
unsafe { rquickjs::qjs::JS_GetRuntime(ctx.as_raw().as_ptr()) },
&modules,
);
let module = Module::declare(ctx.clone(), name, source)
.catch(&ctx)
.map_err(JsError::caught)?;
let options = WriteOptions {
endianness: WriteOptionsEndianness::Little,
strip_source: strip,
strip_debug: strip,
..WriteOptions::default()
};
module
.write(options)
.map_err(|e| JsError::from_engine(&ctx, e))
})
}
#[cfg(test)]
mod tests {
use std::ffi::CStr;
use super::*;
#[test]
fn bytecode_version_matches_linked_engine() {
let engine = unsafe { CStr::from_ptr(rquickjs::qjs::JS_GetVersion()) }
.to_str()
.unwrap();
assert!(
BYTECODE_VERSION.contains(&format!("quickjs-ng-{engine}/")),
"linked QuickJS-NG {engine}, BYTECODE_VERSION says {BYTECODE_VERSION}"
);
}
}