Skip to main content

strata_js/
engine.rs

1//! Pure-Rust JavaScript Execution Engine, AST Parser, and W3C DOM Bindings.
2
3pub mod ast;
4pub mod dom;
5pub mod eval;
6pub mod parser;
7pub mod scope;
8
9pub use ast::*;
10pub use dom::*;
11pub use parser::*;
12pub use scope::*;
13
14use crate::promise::{JsPromise, PromiseState, RejectFn, ResolveFn};
15use crate::{ClosureHandle, JsValue, SymbolId};
16use std::cell::RefCell;
17use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
18use std::rc::Rc;
19
20pub type WeakObjectMap = HashMap<u64, std::rc::Weak<RefCell<BTreeMap<String, JsValue>>>>;
21
22thread_local! {
23    pub(crate) static ENGINE_TIMER_CALLBACKS: RefCell<VecDeque<(JsValue, Vec<JsValue>)>> = const { RefCell::new(VecDeque::new()) };
24}
25
26pub struct JsEngine {
27    pub globals: BTreeMap<String, JsValue>,
28    pub root_scope: Rc<RefCell<Scope>>,
29    pub current_scope: Rc<RefCell<Scope>>,
30    pub document: Document,
31    pub console_logs: Vec<String>,
32    pub user_functions: HashMap<String, JsClosure>,
33    pub closures: HashMap<u64, JsClosure>,
34    pub next_closure_id: u64,
35    pub call_depth: usize,
36    pub live_nodes: RefCell<HashMap<u64, DomNode>>,
37    pub anon_counter: usize,
38    pub classes: HashMap<String, ClassDef>,
39    pub promises: HashMap<u64, JsPromise<JsValue>>,
40    pub promise_controllers: HashMap<u64, (ResolveFn<JsValue>, RejectFn)>,
41    pub next_promise_id: u64,
42    pub pending_throw: Option<JsValue>,
43    pub next_symbol_id: u64,
44    pub symbol_registry: HashMap<String, SymbolId>,
45    pub object_prototype: BTreeMap<String, JsValue>,
46    pub array_prototype: BTreeMap<String, JsValue>,
47    pub function_prototype: BTreeMap<String, JsValue>,
48    pub string_prototype: BTreeMap<String, JsValue>,
49    pub error_prototype: BTreeMap<String, JsValue>,
50    pub memory_limit_bytes: Option<usize>,
51    pub allocated_memory_bytes: usize,
52    pub freeze_prototypes: bool,
53    pub allow_prototype_mutation: bool,
54    pub eval_depth: usize,
55    pub is_strict: bool,
56    pub weak_maps: RefCell<HashMap<u64, HashMap<usize, JsValue>>>,
57    pub next_weak_id: u64,
58    pub weak_sets: RefCell<HashMap<u64, HashSet<usize>>>,
59    pub weak_refs: RefCell<WeakObjectMap>,
60    pub generators: RefCell<HashMap<u64, GeneratorInstance>>,
61    pub next_generator_id: u64,
62    pub pending_yield: Option<JsValue>,
63}
64
65#[derive(Clone)]
66pub struct GeneratorInstance {
67    pub closure: JsClosure,
68    pub scope: Rc<RefCell<Scope>>,
69    pub pc: usize,
70    pub done: bool,
71}
72
73/// Maximum AST expression evaluation recursion depth before returning RangeError (CWE-674).
74pub const MAX_EVAL_DEPTH: usize = 256;
75
76impl Default for JsEngine {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl JsEngine {
83    pub fn new() -> Self {
84        Self::with_document(Document::new())
85    }
86
87    pub fn with_document(doc: Document) -> Self {
88        let mut globals = BTreeMap::new();
89        globals.insert("window".to_string(), JsValue::empty_object());
90        globals.insert("document".to_string(), JsValue::empty_object());
91        globals.insert("console".to_string(), JsValue::empty_object());
92        let mut math_obj = BTreeMap::new();
93        math_obj.insert("PI".to_string(), JsValue::Number(std::f64::consts::PI));
94        math_obj.insert("E".to_string(), JsValue::Number(std::f64::consts::E));
95        globals.insert("Math".to_string(), JsValue::new_object(math_obj));
96        globals.insert("JSON".to_string(), JsValue::empty_object());
97
98        let mut promise_obj = BTreeMap::new();
99        promise_obj.insert("__is_class__".to_string(), JsValue::Bool(true));
100        promise_obj.insert(
101            "__class_name__".to_string(),
102            JsValue::String("Promise".to_string()),
103        );
104        globals.insert("Promise".to_string(), JsValue::new_object(promise_obj));
105
106        let mut regex_obj = BTreeMap::new();
107        regex_obj.insert("__fn__".to_string(), JsValue::String("RegExp".to_string()));
108        globals.insert("RegExp".to_string(), JsValue::new_object(regex_obj));
109
110        let mut fetch_obj = BTreeMap::new();
111        fetch_obj.insert("__fn__".to_string(), JsValue::String("fetch".to_string()));
112        globals.insert("fetch".to_string(), JsValue::new_object(fetch_obj));
113
114        let mut set_timeout_obj = BTreeMap::new();
115        set_timeout_obj.insert(
116            "__fn__".to_string(),
117            JsValue::String("setTimeout".to_string()),
118        );
119        let set_timeout_val = JsValue::new_object(set_timeout_obj);
120        globals.insert("setTimeout".to_string(), set_timeout_val.clone());
121
122        let mut clear_timeout_obj = BTreeMap::new();
123        clear_timeout_obj.insert(
124            "__fn__".to_string(),
125            JsValue::String("clearTimeout".to_string()),
126        );
127        let clear_timeout_val = JsValue::new_object(clear_timeout_obj);
128        globals.insert("clearTimeout".to_string(), clear_timeout_val.clone());
129
130        let mut set_interval_obj = BTreeMap::new();
131        set_interval_obj.insert(
132            "__fn__".to_string(),
133            JsValue::String("setInterval".to_string()),
134        );
135        let set_interval_val = JsValue::new_object(set_interval_obj);
136        globals.insert("setInterval".to_string(), set_interval_val.clone());
137
138        let mut clear_interval_obj = BTreeMap::new();
139        clear_interval_obj.insert(
140            "__fn__".to_string(),
141            JsValue::String("clearInterval".to_string()),
142        );
143        let clear_interval_val = JsValue::new_object(clear_interval_obj);
144        globals.insert("clearInterval".to_string(), clear_interval_val.clone());
145
146        if let Some(JsValue::Object(win_map)) = globals.get("window") {
147            let mut wb = win_map.borrow_mut();
148            wb.insert("setTimeout".to_string(), set_timeout_val);
149            wb.insert("clearTimeout".to_string(), clear_timeout_val);
150            wb.insert("setInterval".to_string(), set_interval_val);
151            wb.insert("clearInterval".to_string(), clear_interval_val);
152        }
153
154        // Built-in prototypes (W3C / ECMAScript specification)
155        let mut object_prototype = BTreeMap::new();
156        object_prototype.insert(
157            "hasOwnProperty".to_string(),
158            JsValue::Function(ClosureHandle::new(0, Some("hasOwnProperty".to_string()))),
159        );
160        object_prototype.insert(
161            "toString".to_string(),
162            JsValue::Function(ClosureHandle::new(0, Some("toString".to_string()))),
163        );
164        object_prototype.insert(
165            "valueOf".to_string(),
166            JsValue::Function(ClosureHandle::new(0, Some("valueOf".to_string()))),
167        );
168
169        let mut array_prototype = BTreeMap::new();
170        array_prototype.insert(
171            "__proto__".to_string(),
172            JsValue::new_object(object_prototype.clone()),
173        );
174
175        let mut function_prototype = BTreeMap::new();
176        function_prototype.insert(
177            "__proto__".to_string(),
178            JsValue::new_object(object_prototype.clone()),
179        );
180
181        let mut string_prototype = BTreeMap::new();
182        string_prototype.insert(
183            "__proto__".to_string(),
184            JsValue::new_object(object_prototype.clone()),
185        );
186
187        let mut error_prototype = BTreeMap::new();
188        error_prototype.insert("name".to_string(), JsValue::String("Error".to_string()));
189        error_prototype.insert("message".to_string(), JsValue::String(String::new()));
190        error_prototype.insert(
191            "__proto__".to_string(),
192            JsValue::new_object(object_prototype.clone()),
193        );
194
195        // Constructors with .prototype linkage
196        let mut obj_ctor = BTreeMap::new();
197        obj_ctor.insert(
198            "prototype".to_string(),
199            JsValue::new_object(object_prototype.clone()),
200        );
201        obj_ctor.insert("__fn__".to_string(), JsValue::String("Object".to_string()));
202        globals.insert("Object".to_string(), JsValue::new_object(obj_ctor));
203
204        let mut arr_ctor = BTreeMap::new();
205        arr_ctor.insert(
206            "prototype".to_string(),
207            JsValue::new_object(array_prototype.clone()),
208        );
209        arr_ctor.insert("__fn__".to_string(), JsValue::String("Array".to_string()));
210        globals.insert("Array".to_string(), JsValue::new_object(arr_ctor));
211
212        let mut fn_ctor = BTreeMap::new();
213        fn_ctor.insert(
214            "prototype".to_string(),
215            JsValue::new_object(function_prototype.clone()),
216        );
217        fn_ctor.insert(
218            "__fn__".to_string(),
219            JsValue::String("Function".to_string()),
220        );
221        globals.insert("Function".to_string(), JsValue::new_object(fn_ctor));
222
223        let mut str_ctor = BTreeMap::new();
224        str_ctor.insert(
225            "prototype".to_string(),
226            JsValue::new_object(string_prototype.clone()),
227        );
228        str_ctor.insert("__fn__".to_string(), JsValue::String("String".to_string()));
229        globals.insert("String".to_string(), JsValue::new_object(str_ctor));
230
231        let mut sym_ctor = BTreeMap::new();
232        sym_ctor.insert(
233            "iterator".to_string(),
234            JsValue::Symbol(SymbolId::iterator()),
235        );
236        sym_ctor.insert(
237            "toStringTag".to_string(),
238            JsValue::Symbol(SymbolId::to_string_tag()),
239        );
240        sym_ctor.insert(
241            "hasInstance".to_string(),
242            JsValue::Symbol(SymbolId::has_instance()),
243        );
244        sym_ctor.insert(
245            "toPrimitive".to_string(),
246            JsValue::Symbol(SymbolId::to_primitive()),
247        );
248        sym_ctor.insert("__fn__".to_string(), JsValue::String("Symbol".to_string()));
249        globals.insert("Symbol".to_string(), JsValue::new_object(sym_ctor));
250
251        // BigInt built-in
252        let mut bigint_obj = BTreeMap::new();
253        bigint_obj.insert("__fn__".to_string(), JsValue::String("BigInt".to_string()));
254        globals.insert("BigInt".to_string(), JsValue::new_object(bigint_obj));
255
256        // Proxy and Reflect built-ins
257        let mut proxy_obj = BTreeMap::new();
258        proxy_obj.insert("__fn__".to_string(), JsValue::String("Proxy".to_string()));
259        proxy_obj.insert("__is_class__".to_string(), JsValue::Bool(true));
260        proxy_obj.insert(
261            "__class_name__".to_string(),
262            JsValue::String("Proxy".to_string()),
263        );
264        globals.insert("Proxy".to_string(), JsValue::new_object(proxy_obj));
265
266        let mut reflect_obj = BTreeMap::new();
267        reflect_obj.insert("__is_reflect__".to_string(), JsValue::Bool(true));
268        globals.insert("Reflect".to_string(), JsValue::new_object(reflect_obj));
269
270        // Weak collections
271        for weak_type in &["WeakMap", "WeakSet", "WeakRef"] {
272            let mut weak_ctor = BTreeMap::new();
273            weak_ctor.insert("__fn__".to_string(), JsValue::String(weak_type.to_string()));
274            weak_ctor.insert("__is_class__".to_string(), JsValue::Bool(true));
275            weak_ctor.insert(
276                "__class_name__".to_string(),
277                JsValue::String(weak_type.to_string()),
278            );
279            globals.insert(weak_type.to_string(), JsValue::new_object(weak_ctor));
280        }
281
282        for err_type in &[
283            "Error",
284            "TypeError",
285            "ReferenceError",
286            "SyntaxError",
287            "RangeError",
288        ] {
289            let mut err_ctor = BTreeMap::new();
290            let mut proto = error_prototype.clone();
291            proto.insert("name".to_string(), JsValue::String(err_type.to_string()));
292            err_ctor.insert("prototype".to_string(), JsValue::new_object(proto));
293            err_ctor.insert("__fn__".to_string(), JsValue::String(err_type.to_string()));
294            globals.insert(err_type.to_string(), JsValue::new_object(err_ctor));
295        }
296
297        let root_scope = Scope::new_root();
298        for (k, v) in &globals {
299            root_scope.borrow_mut().declare(k, v.clone());
300        }
301
302        Self {
303            globals,
304            root_scope: root_scope.clone(),
305            current_scope: root_scope,
306            document: doc,
307            console_logs: Vec::new(),
308            user_functions: HashMap::new(),
309            closures: HashMap::new(),
310            next_closure_id: 1,
311            call_depth: 0,
312            live_nodes: RefCell::new(HashMap::new()),
313            anon_counter: 0,
314            classes: HashMap::new(),
315            promises: HashMap::new(),
316            promise_controllers: HashMap::new(),
317            next_promise_id: 1,
318            pending_throw: None,
319            next_symbol_id: 10, // 1..=4 reserved for well-known symbols
320            symbol_registry: HashMap::new(),
321            object_prototype,
322            array_prototype,
323            function_prototype,
324            string_prototype,
325            error_prototype,
326            memory_limit_bytes: None,
327            allocated_memory_bytes: 0,
328            freeze_prototypes: false,
329            allow_prototype_mutation: false,
330            eval_depth: 0,
331            is_strict: false,
332            weak_maps: RefCell::new(HashMap::new()),
333            next_weak_id: 1,
334            weak_sets: RefCell::new(HashMap::new()),
335            weak_refs: RefCell::new(HashMap::new()),
336            generators: RefCell::new(HashMap::new()),
337            next_generator_id: 1,
338            pending_yield: None,
339        }
340    }
341
342    /// Sets a strict memory allocation threshold in bytes (e.g. 64MB for sandbox).
343    pub fn with_memory_limit(mut self, limit_bytes: usize) -> Self {
344        self.memory_limit_bytes = Some(limit_bytes);
345        self
346    }
347
348    /// Enables or disables prototype freezing to prevent prototype pollution.
349    pub fn set_freeze_prototypes(&mut self, freeze: bool) {
350        self.freeze_prototypes = freeze;
351    }
352
353    /// Sets whether prototype mutation is allowed on root Object.prototype or via __proto__.
354    pub fn with_allow_prototype_mutation(mut self, allow: bool) -> Self {
355        self.allow_prototype_mutation = allow;
356        self
357    }
358
359    /// Toggles prototype mutation permissions on root prototypes and __proto__.
360    pub fn set_allow_prototype_mutation(&mut self, allow: bool) {
361        self.allow_prototype_mutation = allow;
362    }
363
364    /// Tracks heap memory allocations and enforces memory limit quotas.
365    pub fn allocate_bytes(&mut self, bytes: usize) -> Result<(), String> {
366        if let Some(limit) = self.memory_limit_bytes {
367            if self.allocated_memory_bytes.saturating_add(bytes) > limit {
368                return Err("RangeError: Script memory allocation quota exceeded".to_string());
369            }
370        }
371        self.allocated_memory_bytes = self.allocated_memory_bytes.saturating_add(bytes);
372        Ok(())
373    }
374
375    pub fn prune_dead_closures(&mut self) {
376        let mut visited_closure_ids = HashSet::new();
377        let mut visited_scopes = HashSet::new();
378
379        // 1. Mark from globals
380        for val in self.globals.values() {
381            self.mark_value_for_closures(val, &mut visited_closure_ids, &mut visited_scopes);
382        }
383
384        // 2. Mark from root_scope and current_scope
385        self.mark_scope_for_closures(
386            &self.root_scope,
387            &mut visited_closure_ids,
388            &mut visited_scopes,
389        );
390        self.mark_scope_for_closures(
391            &self.current_scope,
392            &mut visited_closure_ids,
393            &mut visited_scopes,
394        );
395
396        // 3. Mark from user_functions
397        for closure in self.user_functions.values() {
398            if closure.id != 0 {
399                visited_closure_ids.insert(closure.id);
400            }
401            self.mark_scope_for_closures(
402                &closure.env,
403                &mut visited_closure_ids,
404                &mut visited_scopes,
405            );
406        }
407
408        // 4. Mark from document nodes and live_nodes
409        self.mark_dom_node_closures(
410            &self.document.html,
411            &mut visited_closure_ids,
412            &mut visited_scopes,
413        );
414        self.mark_dom_node_closures(
415            &self.document.head,
416            &mut visited_closure_ids,
417            &mut visited_scopes,
418        );
419        self.mark_dom_node_closures(
420            &self.document.body,
421            &mut visited_closure_ids,
422            &mut visited_scopes,
423        );
424        for node in self.live_nodes.borrow().values() {
425            self.mark_dom_node_closures(node, &mut visited_closure_ids, &mut visited_scopes);
426        }
427
428        // 5. Mark from promises
429        for promise in self.promises.values() {
430            match promise.state() {
431                PromiseState::Fulfilled(ref v) | PromiseState::Rejected(ref v) => {
432                    self.mark_value_for_closures(v, &mut visited_closure_ids, &mut visited_scopes);
433                }
434                PromiseState::Pending => {}
435            }
436        }
437
438        // Retain only reachable closures (plus any newly allocated within a grace threshold of 8 IDs)
439        let min_grace_id = self.next_closure_id.saturating_sub(8);
440        self.closures
441            .retain(|id, _| *id >= min_grace_id || visited_closure_ids.contains(id));
442    }
443
444    fn mark_dom_node_closures(
445        &self,
446        node: &DomNode,
447        visited_ids: &mut HashSet<u64>,
448        visited_scopes: &mut HashSet<usize>,
449    ) {
450        let inner = node.inner.borrow();
451        for listeners in inner.event_listeners.values() {
452            for cb in listeners {
453                self.mark_value_for_closures(cb, visited_ids, visited_scopes);
454            }
455        }
456        for child in &inner.children {
457            self.mark_dom_node_closures(child, visited_ids, visited_scopes);
458        }
459    }
460
461    fn mark_value_for_closures(
462        &self,
463        val: &JsValue,
464        visited_ids: &mut HashSet<u64>,
465        visited_scopes: &mut HashSet<usize>,
466    ) {
467        match val {
468            JsValue::Function(handle) => {
469                if visited_ids.insert(handle.id) {
470                    if let Some(closure) = self.closures.get(&handle.id) {
471                        self.mark_scope_for_closures(&closure.env, visited_ids, visited_scopes);
472                    }
473                }
474            }
475            JsValue::Object(map) => {
476                let b = map.borrow();
477                if let Some(JsValue::Number(cid)) = b.get("__closure_id__") {
478                    let id = *cid as u64;
479                    if visited_ids.insert(id) {
480                        if let Some(closure) = self.closures.get(&id) {
481                            self.mark_scope_for_closures(&closure.env, visited_ids, visited_scopes);
482                        }
483                    }
484                }
485                for v in b.values() {
486                    self.mark_value_for_closures(v, visited_ids, visited_scopes);
487                }
488            }
489            JsValue::Array(items) => {
490                for item in items.borrow().iter() {
491                    self.mark_value_for_closures(item, visited_ids, visited_scopes);
492                }
493            }
494            _ => {}
495        }
496    }
497
498    fn mark_scope_for_closures(
499        &self,
500        scope_rc: &Rc<RefCell<Scope>>,
501        visited_ids: &mut HashSet<u64>,
502        visited_scopes: &mut HashSet<usize>,
503    ) {
504        let ptr = Rc::as_ptr(scope_rc) as usize;
505        if !visited_scopes.insert(ptr) {
506            return;
507        }
508
509        let scope = scope_rc.borrow();
510        for val in scope.bindings.values() {
511            self.mark_value_for_closures(val, visited_ids, visited_scopes);
512        }
513        if let Some(ref parent) = scope.parent {
514            self.mark_scope_for_closures(parent, visited_ids, visited_scopes);
515        }
516    }
517
518    pub fn maybe_prune_closures(&mut self) {
519        if self.closures.len() > 64 && self.anon_counter.is_multiple_of(32) {
520            self.prune_dead_closures();
521        }
522    }
523
524    pub fn compile_regex(&self, pattern: &str, flags: &str) -> Result<regex::Regex, String> {
525        let mut builder = regex::RegexBuilder::new(pattern);
526        if flags.contains('i') {
527            builder.case_insensitive(true);
528        }
529        if flags.contains('m') {
530            builder.multi_line(true);
531        }
532        if flags.contains('s') {
533            builder.dot_matches_new_line(true);
534        }
535        builder.build().map_err(|e| {
536            format!("SyntaxError: Invalid regular expression: /{pattern}/{flags}: {e}")
537        })
538    }
539
540    pub fn create_regex_value(&self, pattern: &str, flags: &str) -> Result<JsValue, String> {
541        let _ = self.compile_regex(pattern, flags)?;
542
543        let mut map = BTreeMap::new();
544        map.insert("__is_regex__".to_string(), JsValue::Bool(true));
545        map.insert("source".to_string(), JsValue::String(pattern.to_string()));
546        map.insert("flags".to_string(), JsValue::String(flags.to_string()));
547        map.insert("global".to_string(), JsValue::Bool(flags.contains('g')));
548        map.insert("ignoreCase".to_string(), JsValue::Bool(flags.contains('i')));
549        map.insert("multiline".to_string(), JsValue::Bool(flags.contains('m')));
550        map.insert("dotAll".to_string(), JsValue::Bool(flags.contains('s')));
551        map.insert("unicode".to_string(), JsValue::Bool(flags.contains('u')));
552        map.insert("sticky".to_string(), JsValue::Bool(flags.contains('y')));
553        map.insert("lastIndex".to_string(), JsValue::Number(0.0));
554        Ok(JsValue::new_object(map))
555    }
556
557    pub fn create_promise_value(&mut self, promise: JsPromise<JsValue>) -> JsValue {
558        let pid = self.next_promise_id;
559        self.next_promise_id += 1;
560        self.promises.insert(pid, promise.clone());
561        JsValue::Promise(promise)
562    }
563
564    pub fn tick_engine_timers(&mut self) -> usize {
565        let fired_timers = crate::web::tick_timers();
566        let mut executed = 0;
567        loop {
568            let next_cb = ENGINE_TIMER_CALLBACKS.with(|q| q.borrow_mut().pop_front());
569            match next_cb {
570                Some((cb, args)) => {
571                    let _ = self.call_value(&cb, args);
572                    crate::promise::drain_microtasks();
573                    executed += 1;
574                }
575                None => break,
576            }
577        }
578        fired_timers + executed
579    }
580
581    pub fn tick_timers(&mut self) -> usize {
582        self.tick_engine_timers()
583    }
584
585    pub fn resolve_constructor(
586        &self,
587        class_name: &str,
588    ) -> Option<(Vec<String>, Vec<Stmt>, Option<String>)> {
589        let cls = self.classes.get(class_name)?;
590        if let Some(ref ctor) = cls.constructor {
591            Some((ctor.0.clone(), ctor.1.clone(), cls.super_class.clone()))
592        } else if let Some(ref super_name) = cls.super_class {
593            self.resolve_constructor(super_name)
594        } else {
595            None
596        }
597    }
598
599    pub fn resolve_method(
600        &self,
601        class_name: &str,
602        method_name: &str,
603    ) -> Option<(Vec<String>, Vec<Stmt>, Option<String>)> {
604        let mut curr_class = Some(class_name.to_string());
605        while let Some(cls_name) = curr_class {
606            if let Some(cls) = self.classes.get(&cls_name) {
607                if let Some(m) = cls.methods.get(method_name) {
608                    return Some((m.0.clone(), m.1.clone(), cls.super_class.clone()));
609                }
610                curr_class = cls.super_class.clone();
611            } else {
612                break;
613            }
614        }
615        None
616    }
617
618    pub fn is_instance_of(&self, instance: &JsValue, class_name: &str) -> bool {
619        if class_name == "Object" {
620            return matches!(instance, JsValue::Object(_) | JsValue::Array(_));
621        }
622        if class_name == "Array" {
623            return matches!(instance, JsValue::Array(_));
624        }
625        if let JsValue::Object(map) = instance {
626            let b = map.borrow();
627            if class_name == "Error"
628                || class_name == "TypeError"
629                || class_name == "ReferenceError"
630                || class_name == "SyntaxError"
631                || class_name == "RangeError"
632            {
633                if let Some(JsValue::String(name)) = b.get("name") {
634                    if name == class_name || class_name == "Error" {
635                        return true;
636                    }
637                }
638            }
639
640            if let Some(JsValue::String(inst_class)) = b.get("__class__") {
641                let mut curr = Some(inst_class.clone());
642                while let Some(c) = curr {
643                    if c == class_name {
644                        return true;
645                    }
646                    curr = self.classes.get(&c).and_then(|cd| cd.super_class.clone());
647                }
648            }
649
650            // Walk __proto__ chain
651            let mut cur_proto = b.get("__proto__").cloned();
652            let mut depth = 0;
653            while let Some(JsValue::Object(p_map)) = cur_proto {
654                depth += 1;
655                if depth > 64 {
656                    break;
657                }
658                let pb = p_map.borrow();
659                if let Some(JsValue::String(p_cls)) = pb.get("__class__") {
660                    if p_cls == class_name {
661                        return true;
662                    }
663                }
664                if let Some(JsValue::String(p_name)) = pb.get("name") {
665                    if p_name == class_name || (class_name == "Error" && p_name.ends_with("Error"))
666                    {
667                        return true;
668                    }
669                }
670                cur_proto = pb.get("__proto__").cloned();
671            }
672        }
673        false
674    }
675
676    pub fn instantiate_class(
677        &mut self,
678        class_name: &str,
679        args: Vec<JsValue>,
680    ) -> Result<JsValue, String> {
681        let _cls = self
682            .classes
683            .get(class_name)
684            .cloned()
685            .ok_or_else(|| format!("ReferenceError: {class_name} is not defined"))?;
686
687        let mut instance_map = BTreeMap::new();
688        instance_map.insert(
689            "__class__".to_string(),
690            JsValue::String(class_name.to_string()),
691        );
692        let instance_obj = JsValue::new_object(instance_map);
693
694        if let Some((params, body, super_opt)) = self.resolve_constructor(class_name) {
695            let ctor_scope = Scope::new_child(self.current_scope.clone());
696            ctor_scope.borrow_mut().declare("this", instance_obj);
697            if let Some(super_name) = super_opt {
698                ctor_scope
699                    .borrow_mut()
700                    .declare("__super_class__", JsValue::String(super_name));
701            }
702            ctor_scope
703                .borrow_mut()
704                .declare("__current_class__", JsValue::String(class_name.to_string()));
705
706            bind_parameters(&params, args, &ctor_scope);
707
708            let saved_scope = self.current_scope.clone();
709            self.current_scope = ctor_scope.clone();
710
711            let mut ret_val = None;
712            let mut err = None;
713            for stmt in &body {
714                match self.execute_stmt_flow(stmt) {
715                    Ok(StatementFlow::Normal(_)) => {}
716                    Ok(StatementFlow::Return(v)) => {
717                        if let JsValue::Object(_) = v {
718                            ret_val = Some(v);
719                        }
720                        break;
721                    }
722                    Ok(StatementFlow::Throw(v)) => {
723                        err = Some(format!("Uncaught exception: {v}"));
724                        break;
725                    }
726                    Ok(StatementFlow::Break(_)) => {
727                        err = Some("SyntaxError: Illegal break statement".to_string());
728                        break;
729                    }
730                    Ok(StatementFlow::Continue(_)) => {
731                        err = Some("SyntaxError: Illegal continue statement".to_string());
732                        break;
733                    }
734                    Ok(StatementFlow::Yield(v)) => {
735                        return Ok(v);
736                    }
737                    Err(e) => {
738                        err = Some(e);
739                        break;
740                    }
741                }
742            }
743
744            self.current_scope = saved_scope;
745            if let Some(e) = err {
746                return Err(e);
747            }
748
749            if let Some(ret) = ret_val {
750                return Ok(ret);
751            }
752
753            let final_this = ctor_scope
754                .borrow()
755                .get("this")
756                .unwrap_or(JsValue::Undefined);
757            Ok(final_this)
758        } else {
759            Ok(instance_obj)
760        }
761    }
762
763    pub fn eval(&mut self, script: &str) -> Result<JsValue, String> {
764        let mut parser = JsParser::new(script);
765        let stmts = parser.parse_program()?;
766
767        for (k, v) in &self.globals {
768            self.root_scope.borrow_mut().declare(k, v.clone());
769        }
770        self.current_scope = self.root_scope.clone();
771
772        let mut result = JsValue::Undefined;
773        for stmt in &stmts {
774            self.maybe_prune_closures();
775            match self.execute_stmt_flow(stmt)? {
776                StatementFlow::Normal(v) => result = v,
777                StatementFlow::Return(v) | StatementFlow::Yield(v) => {
778                    result = v;
779                    break;
780                }
781                StatementFlow::Throw(err) => {
782                    return Err(format!("Uncaught exception: {err}"));
783                }
784                StatementFlow::Break(_) => {
785                    return Err("SyntaxError: Illegal break statement".to_string());
786                }
787                StatementFlow::Continue(_) => {
788                    return Err("SyntaxError: Illegal continue statement".to_string());
789                }
790            }
791        }
792
793        for (k, v) in &self.root_scope.borrow().bindings {
794            self.globals.insert(k.clone(), v.clone());
795        }
796
797        self.prune_dead_closures();
798
799        Ok(result)
800    }
801
802    pub fn dom_node_to_js(&self, node: &DomNode) -> JsValue {
803        self.live_nodes
804            .borrow_mut()
805            .insert(node.uid(), node.clone());
806        let mut map = BTreeMap::new();
807        map.insert("__uid__".to_string(), JsValue::Number(node.uid() as f64));
808        let id_val = node
809            .id()
810            .unwrap_or_else(|| format!("dom_node_{}", node.uid()));
811        map.insert("__dom_id__".to_string(), JsValue::String(id_val));
812        map.insert(
813            "id".to_string(),
814            JsValue::String(node.id().unwrap_or_default()),
815        );
816        map.insert(
817            "tagName".to_string(),
818            JsValue::String(node.tag_name().unwrap_or_default()),
819        );
820        map.insert("className".to_string(), JsValue::String(node.class_name()));
821        map.insert("innerHTML".to_string(), JsValue::String(node.inner_html()));
822        map.insert(
823            "textContent".to_string(),
824            JsValue::String(node.text_content()),
825        );
826        map.insert(
827            "value".to_string(),
828            JsValue::String(node.get_attribute("value").unwrap_or_default()),
829        );
830        JsValue::new_object(map)
831    }
832
833    pub fn create_error_from_string(&self, err_msg: &str) -> JsValue {
834        let (err_name, msg) = if let Some(idx) = err_msg.find(": ") {
835            let prefix = &err_msg[..idx];
836            if matches!(
837                prefix,
838                "TypeError" | "ReferenceError" | "SyntaxError" | "RangeError" | "Error"
839            ) {
840                (prefix.to_string(), err_msg[idx + 2..].to_string())
841            } else {
842                ("Error".to_string(), err_msg.to_string())
843            }
844        } else {
845            ("Error".to_string(), err_msg.to_string())
846        };
847
848        let mut map = BTreeMap::new();
849        map.insert("__is_error__".to_string(), JsValue::Bool(true));
850        map.insert("name".to_string(), JsValue::String(err_name.clone()));
851        map.insert("message".to_string(), JsValue::String(msg.clone()));
852        map.insert(
853            "stack".to_string(),
854            JsValue::String(format!("{err_name}: {msg}\n    at strata_js")),
855        );
856        map.insert(
857            "__proto__".to_string(),
858            JsValue::new_object(self.error_prototype.clone()),
859        );
860        JsValue::new_object(map)
861    }
862}
863
864pub fn days_from_civil(mut y: i64, m: u64, d: u64) -> i64 {
865    if m <= 2 {
866        y -= 1;
867    }
868    let era = if y >= 0 { y } else { y - 399 } / 400;
869    let yoe = (y - era * 400) as u64;
870    let m_adj = if m > 2 { m - 3 } else { m + 9 };
871    let doy = (153 * m_adj + 2) / 5 + d - 1;
872    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
873    era * 146097 + (doe as i64) - 719468
874}
875
876pub fn civil_from_days(z: i64) -> (i64, u64, u64) {
877    let z_adj = z + 719468;
878    let era = if z_adj >= 0 { z_adj } else { z_adj - 146096 } / 146097;
879    let doe = (z_adj - era * 146097) as u64;
880    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
881    let mut y = (yoe as i64) + era * 400;
882    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
883    let mp = (5 * doy + 2) / 153;
884    let d = doy - (153 * mp + 2) / 5 + 1;
885    let m = if mp < 10 { mp + 3 } else { mp - 9 };
886    if m <= 2 {
887        y += 1;
888    }
889    (y, m, d)
890}
891
892pub fn ms_to_date(ms: f64) -> (i64, u64, u64, u64, u64, u64, u64) {
893    if ms.is_nan() || ms.is_infinite() {
894        return (1970, 0, 1, 0, 0, 0, 0);
895    }
896    let total_ms = ms as i64;
897    let days = total_ms.div_euclid(86_400_000);
898    let rem_ms = total_ms.rem_euclid(86_400_000);
899    let (y, m, d) = civil_from_days(days);
900    let hours = (rem_ms / 3_600_000) as u64;
901    let rem_hours = rem_ms % 3_600_000;
902    let minutes = (rem_hours / 60_000) as u64;
903    let rem_min = rem_hours % 60_000;
904    let seconds = (rem_min / 1_000) as u64;
905    let millis = (rem_min % 1_000) as u64;
906    (y, m.saturating_sub(1), d, hours, minutes, seconds, millis)
907}
908
909pub fn date_to_ms(
910    year: f64,
911    month: f64,
912    day: f64,
913    hours: f64,
914    minutes: f64,
915    seconds: f64,
916    ms: f64,
917) -> f64 {
918    let y = year as i64;
919    let m = (month as u64) + 1;
920    let d = (day as u64).max(1);
921    let days = days_from_civil(y, m, d);
922    let total_ms = days * 86_400_000
923        + (hours as i64) * 3_600_000
924        + (minutes as i64) * 60_000
925        + (seconds as i64) * 1_000
926        + (ms as i64);
927    total_ms as f64
928}