use js_sys::Function;
use wasm_bindgen::prelude::*;
use crate::{Error, FunctionBundle, Result, python::PythonEngine};
use crate::python::wasm_function_bundle::register_all_functions_with_pyodide;
pub fn register_bundle(engine: &mut PythonEngine, bundle: &FunctionBundle) -> Result<()> {
match bundle {
FunctionBundle::Python(_) => {
println!("Registering Python function bundle with Pyodide...");
web_sys::console::log_1(&format!("Registering Python function bundle...").into());
if let FunctionBundle::Python(py_bundle) = bundle {
if let Err(e) = py_bundle.register() {
eprintln!("Failed to register functions in global scope: {:?}", e);
}
}
match register_all_functions_with_pyodide(bundle) {
Ok(_) => {
println!("Successfully registered Python function bundle with Pyodide");
engine._initialized = true;
}
Err(e) => {
eprintln!(
"Failed to register Python function bundle with Pyodide, will try again: {:?}",
e
);
}
}
}
_ => {
}
}
Ok(())
}
pub fn eval(engine: &mut PythonEngine, code: &str) -> Result<String> {
use js_sys::JsString;
use wasm_bindgen::prelude::*;
use web_sys::window;
let window = window().ok_or_else(|| Error::Python("No window object available".into()))?;
let pyodide_obj = js_sys::Reflect::get(&window.into(), &"pyodide".into()).map_err(|_| {
console_error_panic_hook::set_once();
eprintln!("Pyodide not found in global scope");
Error::Python(
"Pyodide not available. Make sure Pyodide is loaded before running Python code."
.to_string(),
)
})?;
if pyodide_obj.is_undefined() {
return Err(Error::Python(
"Pyodide is undefined. The Pyodide library may not be fully loaded yet.".to_string(),
));
}
if !engine._initialized {
}
let run_python_fn = js_sys::Reflect::get(&pyodide_obj, &"runPython".into()).map_err(|e| {
eprintln!("Failed to get runPython function: {:?}", e);
Error::Python("Failed to get runPython function from Pyodide object".to_string())
})?;
if run_python_fn.is_undefined() {
return Err(Error::Python(
"runPython function is undefined. Pyodide may not be fully initialized.".to_string(),
));
}
let run_python_fn = run_python_fn
.dyn_into::<Function>()
.map_err(|_| Error::Python("runPython is not a function".into()))?;
let result = run_python_fn
.call1(&pyodide_obj, &JsString::from(code).into())
.map_err(|e| {
eprintln!("JS error calling runPython: {:?}", e);
let error_str = format!("{:?}", e);
Error::Python(format!(
"JavaScript error when executing Python code: {}",
error_str
))
})?;
let result_str = if result.is_string() {
result
.as_string()
.unwrap_or_else(|| "<no result>".to_string())
} else if result.is_object() {
let obj = result.dyn_ref::<js_sys::Object>().unwrap();
let to_string_result = js_sys::Reflect::get(obj, &"toString".into()).ok();
if let Some(to_string_fn) = to_string_result {
if let Some(to_string_fn) = to_string_fn.dyn_ref::<Function>() {
match to_string_fn.call0(obj) {
Ok(str_result) => {
let str_val = str_result
.as_string()
.unwrap_or_else(|| "<toString failed>".to_string());
str_val
}
Err(_) => "<object>".to_string(),
}
} else {
format!("{:?}", result)
}
} else {
format!("{:?}", result)
}
} else {
use js_sys::JSON;
match JSON::stringify(&result) {
Ok(json_str) => json_str
.as_string()
.unwrap_or_else(|| format!("{:?}", result)),
Err(_) => format!("{:?}", result), }
};
Ok(result_str)
}