1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::{
    cmp::min,
    collections::{HashMap, HashSet},
    ffi::CStr,
    future::Future,
    str::FromStr,
    sync::{Arc, Mutex},
};

// use once_cell::sync::Lazy;

// use chrono::Utc;
// use ring::rand::SecureRandom;
use rquickjs::{
    atom::PredefinedAtom, context::EvalOptions, function::Opt, prelude::Func, qjs, CatchResultExt,
    CaughtError, Ctx, Error, Function, IntoJs, Module, Object, Promise, Result, String as JsString,
    Value,
};
// use tokio::sync::oneshot::{self, Receiver};
// use tracing::trace;
// use zstd::{bulk::Decompressor, dict::DecoderDictionary};

// use crate::modules::{
//     console,
//     crypto::SYSTEM_RANDOM,
//     path::{dirname, join_path, resolve_path},
// };

// use crate::{
//     bytecode::{BYTECODE_COMPRESSED, BYTECODE_UNCOMPRESSED, BYTECODE_VERSION, SIGNATURE_LENGTH},
//     environment,
//     json::{parse::json_parse, stringify::json_stringify_replacer_space},
//     number::number_to_string,
//     utils::{
//         clone::structured_clone,
//         io::get_js_path,
//         object::{get_bytes, ObjectExt},
//     },
// };

// pub static TIME_ORIGIN: AtomicUsize = AtomicUsize::new(0);

// #[inline]
// pub fn uncompressed_size(input: &[u8]) -> StdResult<(usize, &[u8]), io::Error> {
//     let size = input.get(..4).ok_or(io::ErrorKind::InvalidInput)?;
//     let size: &[u8; 4] = size.try_into().map_err(|_| io::ErrorKind::InvalidInput)?;
//     let uncompressed_size = u32::from_le_bytes(*size) as usize;
//     let rest = &input[4..];
//     Ok((uncompressed_size, rest))
// }

// pub(crate) static COMPRESSION_DICT: &[u8] = include_bytes!("../../bundle/lrt/compression.dict");

// static DECOMPRESSOR_DICT: Lazy<DecoderDictionary> =
//     Lazy::new(|| DecoderDictionary::copy(COMPRESSION_DICT));

fn print(value: String, stdout: Opt<bool>) {
    if stdout.0.unwrap_or_default() {
        println!("{value}");
    } else {
        eprintln!("{value}")
    }
}

// #[derive(Debug)]
// pub struct BinaryResolver {
//     paths: Vec<PathBuf>,
//     cwd: PathBuf,
// }
// impl BinaryResolver {
//     pub fn add_path<P: Into<PathBuf>>(&mut self, path: P) -> &mut Self {
//         self.paths.push(path.into());
//         self
//     }

//     pub fn get_bin_path(path: &Path) -> PathBuf {
//         path.with_extension("lrt")
//     }

//     pub fn normalize<P: AsRef<Path>>(path: P) -> PathBuf {
//         let ends_with_slash = path.as_ref().to_str().map_or(false, |s| s.ends_with('/'));
//         let mut normalized = PathBuf::new();
//         for component in path.as_ref().components() {
//             match &component {
//                 Component::ParentDir => {
//                     if !normalized.pop() {
//                         normalized.push(component);
//                     }
//                 },
//                 _ => {
//                     normalized.push(component);
//                 },
//             }
//         }
//         if ends_with_slash {
//             normalized.push("");
//         }
//         normalized
//     }
// }

// impl Default for BinaryResolver {
//     fn default() -> Self {
//         let cwd = env::current_dir().unwrap();
//         Self {
//             cwd,
//             paths: Vec::with_capacity(10),
//         }
//     }
// }

// #[allow(clippy::manual_strip)]
// impl Resolver for BinaryResolver {
//     fn resolve(&mut self, _ctx: &Ctx, base: &str, name: &str) -> Result<String> {
//         trace!("Try resolve \"{}\" from \"{}\"", name, base);

//         if BYTECODE_CACHE.contains_key(name) {
//             return Ok(name.to_string());
//         }

//         let base_path = Path::new(base);
//         let base_path = if base_path.is_dir() {
//             if base_path == self.cwd {
//                 Path::new(".")
//             } else {
//                 base_path
//             }
//         } else {
//             base_path.parent().unwrap_or(base_path)
//         };

//         let normalized_path = base_path.join(name);

//         let normalized_path = BinaryResolver::normalize(normalized_path);
//         let mut normalized_path = normalized_path.to_str().unwrap();
//         let cache_path = if normalized_path.starts_with("./") {
//             &normalized_path[2..]
//         } else {
//             normalized_path
//         };

//         let cache_key = Path::new(cache_path).with_extension("js");
//         let cache_key = cache_key.to_str().unwrap();

//         trace!("Normalized path: {}, key: {}", normalized_path, cache_key);

//         if BYTECODE_CACHE.contains_key(cache_key) {
//             return Ok(cache_key.to_string());
//         }

//         if BYTECODE_CACHE.contains_key(base) {
//             normalized_path = name;
//             if Path::new(normalized_path).exists() {
//                 return Ok(normalized_path.to_string());
//             }
//         }

//         if Path::new(normalized_path).exists() {
//             return Ok(normalized_path.to_string());
//         }

//         let path = self
//             .paths
//             .iter()
//             .find_map(|path| {
//                 let path = path.join(normalized_path);
//                 let bin_path = BinaryResolver::get_bin_path(&path);
//                 if bin_path.exists() {
//                     return Some(bin_path);
//                 }
//                 get_js_path(path.to_str().unwrap())
//             })
//             .ok_or_else(|| Error::new_resolving(base, name))?;

//         Ok(path.into_os_string().into_string().unwrap())
//     }
// }

// #[derive(Debug)]
// pub struct BinaryLoader;

// impl Default for BinaryLoader {
//     fn default() -> Self {
//         Self
//     }
// }

// struct RawLoaderContainer<T>
// where
//     T: RawLoader + 'static,
// {
//     loader: T,
//     cwd: String,
// }
// impl<T> RawLoaderContainer<T>
// where
//     T: RawLoader + 'static,
// {
//     fn new(loader: T) -> Self {
//         Self {
//             loader,
//             cwd: std::env::current_dir()
//                 .unwrap()
//                 .to_string_lossy()
//                 .to_string(),
//         }
//     }
// }

// unsafe impl<T> RawLoader for RawLoaderContainer<T>
// where
//     T: RawLoader + 'static,
// {
//     #[allow(clippy::manual_strip)]
//     unsafe fn raw_load<'js>(&mut self, ctx: &Ctx<'js>, name: &str) -> Result<Module<'js>> {
//         let res = self.loader.raw_load(ctx, name)?;

//         let name = if name.starts_with("./") {
//             &name[2..]
//         } else {
//             name
//         };

//         if name.starts_with('/') {
//             set_import_meta(&res, name)?;
//         } else {
//             set_import_meta(&res, &format!("{}/{}", &self.cwd, name))?;
//         };

//         Ok(res)
//     }
// }

// impl Loader for BinaryLoader {
//     fn load(&mut self, _ctx: &Ctx<'_>, name: &str) -> Result<ModuleData> {
//         trace!("Loading module: {}", name);
//         if let Some(bytes) = BYTECODE_CACHE.get(name) {
//             trace!("Loading embedded module: {}", name);

//             return load_bytecode_module(name, bytes);
//         }
//         let path = PathBuf::from(name);
//         let mut bytes: &[u8] = &std::fs::read(path)?;

//         if name.ends_with(".lrt") {
//             trace!("Loading binary module: {}", name);
//             return load_bytecode_module(name, bytes);
//         }
//         if bytes.starts_with(b"#!") {
//             bytes = bytes.splitn(2, |&c| c == b'\n').nth(1).unwrap_or(bytes);
//         }
//         Ok(ModuleData::source(name, bytes))
//     }
// }

// pub fn load_bytecode_module(name: &str, buf: &[u8]) -> Result<ModuleData> {
//     let bytes = load_module(buf)?;
//     Ok(unsafe { ModuleData::bytecode(name, bytes) })
// }

// fn load_module(input: &[u8]) -> Result<Vec<u8>> {
//     let (_, compressed, input) = get_bytecode_signature(input)?;

//     if compressed {
//         let (size, input) = uncompressed_size(input)?;
//         let mut buf = Vec::with_capacity(size);
//         let mut decompressor = Decompressor::with_prepared_dictionary(&DECOMPRESSOR_DICT)?;
//         decompressor.decompress_to_buffer(input, &mut buf)?;
//         return Ok(buf);
//     }

//     Ok(input.to_vec())
// }

// fn get_bytecode_signature(input: &[u8]) -> StdResult<(&[u8], bool, &[u8]), io::Error> {
//     let raw_signature = input
//         .get(..SIGNATURE_LENGTH)
//         .ok_or(io::Error::new::<String>(
//             io::ErrorKind::InvalidInput,
//             "Invalid bytecode signature length".into(),
//         ))?;

//     let (last, signature) = raw_signature.split_last().unwrap();

//     if signature != BYTECODE_VERSION.as_bytes() {
//         return Err(io::Error::new::<String>(
//             io::ErrorKind::InvalidInput,
//             "Invalid bytecode version".into(),
//         ));
//     }

//     let mut compressed = None;
//     if *last == BYTECODE_COMPRESSED {
//         compressed = Some(true)
//     } else if *last == BYTECODE_UNCOMPRESSED {
//         compressed = Some(false)
//     }

//     let rest = &input[SIGNATURE_LENGTH..];
//     Ok((
//         signature,
//         compressed.ok_or(io::Error::new::<String>(
//             io::ErrorKind::InvalidInput,
//             "Invalid bytecode signature".into(),
//         ))?,
//         rest,
//     ))
// }

// pub struct Vm {
//     pub runtime: AsyncRuntime,
//     pub ctx: AsyncContext,
// }

struct LifetimeArgs<'js>(Ctx<'js>);

#[allow(dead_code)]
struct ExportArgs<'js>(Ctx<'js>, Object<'js>, Value<'js>, Value<'js>);

// pub struct VmOptions {
//     pub module_builder: crate::module_builder::ModuleBuilder,
//     pub max_stack_size: usize,
//     pub gc_threshold_mb: usize,
// }

// impl Default for VmOptions {
//     fn default() -> Self {
//         Self {
//             module_builder: crate::module_builder::ModuleBuilder::with_default(),
//             max_stack_size: 512 * 1024,
//             gc_threshold_mb: {
//                 const DEFAULT_GC_THRESHOLD_MB: usize = 20;

//                 let gc_threshold_mb: usize = env::var(environment::ENV_LLRT_GC_THRESHOLD_MB)
//                     .map(|threshold| threshold.parse().unwrap_or(DEFAULT_GC_THRESHOLD_MB))
//                     .unwrap_or(DEFAULT_GC_THRESHOLD_MB);

//                 gc_threshold_mb * 1024 * 1024
//             },
//         }
//     }
// }

// impl Vm {
//     pub const ENV_LAMBDA_TASK_ROOT: &'static str = "LAMBDA_TASK_ROOT";

//     pub async fn from_options(
//         vm_options: VmOptions,
//     ) -> StdResult<Self, Box<dyn std::error::Error + Send + Sync>> {
//         if TIME_ORIGIN.load(Ordering::Relaxed) == 0 {
//             let time_origin = Utc::now().timestamp_nanos_opt().unwrap_or_default() as usize;
//             TIME_ORIGIN.store(time_origin, Ordering::Relaxed)
//         }

//         SYSTEM_RANDOM
//             .fill(&mut [0; 8])
//             .expect("Failed to initialize SystemRandom");

//         let mut file_resolver = FileResolver::default();
//         let mut binary_resolver = BinaryResolver::default();
//         let mut paths: Vec<&str> = Vec::with_capacity(10);

//         paths.push(".");

//         let task_root = env::var(Self::ENV_LAMBDA_TASK_ROOT).unwrap_or_else(|_| String::from(""));
//         let task_root = task_root.as_str();
//         if cfg!(debug_assertions) {
//             paths.push("bundle");
//         } else {
//             paths.push("/opt");
//         }

//         if !task_root.is_empty() {
//             paths.push(task_root);
//         }

//         for path in paths.iter() {
//             file_resolver.add_path(*path);
//             binary_resolver.add_path(*path);
//         }

//         let (builtin_resolver, module_loader, module_names, init_globals) =
//             vm_options.module_builder.build();

//         let resolver = (builtin_resolver, binary_resolver, file_resolver);

//         let loader = RawLoaderContainer::new((
//             module_loader,
//             BinaryLoader,
//             BuiltinLoader::default(),
//             ScriptLoader::default()
//                 .with_extension("mjs")
//                 .with_extension("cjs"),
//         ));

//         let runtime = AsyncRuntime::new()?;
//         runtime.set_max_stack_size(vm_options.max_stack_size).await;
//         runtime.set_gc_threshold(vm_options.gc_threshold_mb).await;
//         runtime.set_loader(resolver, loader).await;
//         let ctx = AsyncContext::full(&runtime).await?;
//         ctx.with(|ctx| {
//             for init_global in init_globals {
//                 init_global(&ctx)?;
//             }
//             init(&ctx, module_names)?;
//             Ok::<_, Error>(())
//         })
//         .await?;

//         Ok(Vm { runtime, ctx })
//     }

//     pub async fn new() -> StdResult<Self, Box<dyn std::error::Error + Send + Sync>> {
//         let vm = Self::from_options(VmOptions::default()).await?;
//         Ok(vm)
//     }

//     pub fn load_module<'js>(ctx: &Ctx<'js>, filename: PathBuf) -> Result<Object<'js>> {
//         Module::import(ctx, filename.to_string_lossy().to_string())
//     }

//     pub async fn run_module(ctx: &AsyncContext, filename: &Path) {
//         Self::run_and_handle_exceptions(ctx, |ctx| {
//             let _res = Vm::load_module(&ctx, filename.to_path_buf())?;
//             Ok(())
//         })
//         .await
//     }

//     pub async fn run_and_handle_exceptions<'js, F>(ctx: &AsyncContext, f: F)
//     where
//         F: FnOnce(Ctx) -> rquickjs::Result<()> + Send,
//     {
//         ctx.with(|ctx| {
//             f(ctx.clone())
//                 .catch(&ctx)
//                 .unwrap_or_else(|err| Self::print_error_and_exit(&ctx, err));
//         })
//         .await;
//     }

//     pub fn print_error_and_exit<'js>(ctx: &Ctx<'js>, err: CaughtError<'js>) -> ! {
//         let mut error_str = String::new();
//         write!(error_str, "Error: {:?}", err).unwrap();
//         if let Ok(error) = err.into_value(ctx) {
//             if console::log_std_err(ctx, Rest(vec![error.clone()]), console::LogLevel::Fatal)
//                 .is_err()
//             {
//                 eprintln!("{}", error_str);
//             };
//             exit(1)
//         } else {
//             eprintln!("{}", error_str);
//             exit(1)
//         };
//     }

//     pub async fn idle(self) -> StdResult<(), Box<dyn std::error::Error + Sync + Send>> {
//         self.runtime.idle().await;

//         drop(self.ctx);
//         drop(self.runtime);
//         Ok(())
//     }
// }

use tokio::sync::oneshot::Receiver;

use crate::{
    json::{parse::json_parse, stringify::json_stringify_replacer_space},
    modules::path::{dirname, join_path, resolve_path},
    number::number_to_string,
    utils::object::{get_bytes, ObjectExt},
};

fn json_parse_string<'js>(ctx: Ctx<'js>, value: Value<'js>) -> Result<Value<'js>> {
    let bytes = get_bytes(&ctx, value)?;
    json_parse(&ctx, bytes)
}

fn run_gc(ctx: Ctx<'_>) {
    // trace!("Running GC");

    unsafe {
        let rt = qjs::JS_GetRuntime(ctx.as_raw().as_ptr());
        qjs::JS_RunGC(rt);
    };
}

use crate::utils::clone::structured_clone;
fn init(ctx: &Ctx<'_>, module_names: HashSet<&'static str>) -> Result<()> {
    let globals = ctx.globals();

    globals.set("__gc", Func::from(run_gc))?;

    let number: Function = globals.get(PredefinedAtom::Number)?;
    let number_proto: Object = number.get(PredefinedAtom::Prototype)?;
    number_proto.set(PredefinedAtom::ToString, Func::from(number_to_string))?;

    globals.set("global", ctx.globals())?;
    globals.set("self", ctx.globals())?;
    globals.set("load", Func::from(load))?;
    globals.set("print", Func::from(print))?;
    globals.set(
        "structuredClone",
        Func::from(|ctx, value, options| structured_clone(&ctx, value, options)),
    )?;

    let json_module: Object = globals.get(PredefinedAtom::JSON)?;
    json_module.set("parse", Func::from(json_parse_string))?;
    json_module.set(
        "stringify",
        Func::from(|ctx, value, replacer, space| {
            struct StringifyArgs<'js>(Ctx<'js>, Value<'js>, Opt<Value<'js>>, Opt<Value<'js>>);
            let StringifyArgs(ctx, value, replacer, space) =
                StringifyArgs(ctx, value, replacer, space);

            let mut space_value = None;
            let mut replacer_value = None;

            if let Some(replacer) = replacer.0 {
                if let Some(space) = space.0 {
                    if let Some(space) = space.as_string() {
                        let mut space = space.clone().to_string()?;
                        space.truncate(20);
                        space_value = Some(space);
                    }
                    if let Some(number) = space.as_int() {
                        if number > 0 {
                            space_value = Some(" ".repeat(min(10, number as usize)));
                        }
                    }
                }
                replacer_value = Some(replacer);
            }

            json_stringify_replacer_space(&ctx, value, replacer_value, space_value)
                .map(|v| v.into_js(&ctx))?
        }),
    )?;

    #[allow(clippy::arc_with_non_send_sync)]
    let require_in_progress: Arc<Mutex<HashMap<String, Object>>> =
        Arc::new(Mutex::new(HashMap::new()));

    #[allow(clippy::arc_with_non_send_sync)]
    let require_exports: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));
    let require_exports_ref = require_exports.clone();
    let require_exports_ref_2 = require_exports.clone();

    let js_bootstrap = Object::new(ctx.clone())?;
    js_bootstrap.set(
        "moduleExport",
        Func::from(move |ctx, obj, prop, value| {
            let ExportArgs(_ctx, _, _, value) = ExportArgs(ctx, obj, prop, value);
            let mut exports = require_exports.lock().unwrap();
            exports.replace(value);
            Result::Ok(true)
        }),
    )?;
    js_bootstrap.set(
        "exports",
        Func::from(move |ctx, obj, prop, value| {
            let ExportArgs(ctx, _, prop, value) = ExportArgs(ctx, obj, prop, value);
            let mut exports = require_exports_ref.lock().unwrap();
            let exports = if exports.is_some() {
                exports.as_ref().unwrap()
            } else {
                exports.replace(Object::new(ctx.clone())?.into_value());
                exports.as_ref().unwrap()
            };
            exports.as_object().unwrap().set(prop, value)?;
            Result::Ok(true)
        }),
    )?;
    globals.set("__bootstrap", js_bootstrap)?;

    globals.set(
        "require",
        Func::from(move |ctx, specifier: String| -> Result<Value> {
            let LifetimeArgs(ctx) = LifetimeArgs(ctx);
            let specifier = if let Some(striped_specifier) = &specifier.strip_prefix("node:") {
                striped_specifier.to_string()
            } else {
                specifier
            };
            let import_name = if module_names.contains(specifier.as_str())
                // || BYTECODE_CACHE.contains_key(&specifier)
                || specifier.starts_with('/')
            {
                specifier
            } else {
                let module_name = get_script_or_module_name(ctx.clone());
                let abs_path = resolve_path([module_name].iter());
                let import_directory = dirname(abs_path);
                join_path(vec![import_directory, specifier])
            };

            let mut map = require_in_progress.lock().unwrap();
            if let Some(obj) = map.get(&import_name) {
                return Ok(obj.clone().into_value());
            }

            let obj = Object::new(ctx.clone())?;
            map.insert(import_name.clone(), obj.clone());
            drop(map);

            // trace!("Require: {}", import_name);

            let imported_object: Promise = Module::import(&ctx, import_name.clone()).unwrap();
            require_in_progress.lock().unwrap().remove(&import_name);

            if let Some(exports) = require_exports_ref_2.lock().unwrap().take() {
                if let Some(exports) = exports.as_object() {
                    for prop in exports.props::<Value, Value>() {
                        let (key, value) = prop?;
                        obj.set(key, value)?;
                    }
                } else {
                    return Ok(exports);
                }
            }

            for prop in imported_object.props::<String, Value>() {
                let (key, value) = prop?;
                obj.set(key, value)?;
            }

            Ok(obj.into_value())
        }),
    )?;

    Module::import(ctx, "@llrt/std")?;

    Ok(())
}

fn load<'js>(ctx: Ctx<'js>, filename: String, options: Opt<Object<'js>>) -> Result<Value<'js>> {
    let mut eval_options = EvalOptions::default();
    eval_options.global = true;
    eval_options.strict = false;
    eval_options.backtrace_barrier = false;
    eval_options.promise = true;

    // let mut eval_options = EvalOptions {
    //     global: true,
    //     strict: false,
    //     backtrace_barrier: false,
    //     promise: false,
    // };

    if let Some(options) = options.0 {
        if let Some(global) = options.get_optional("global")? {
            eval_options.global = global;
        }

        if let Some(strict) = options.get_optional("strict")? {
            eval_options.strict = strict;
        }
    }

    ctx.eval_file_with_options(
        std::path::PathBuf::from_str(&filename).unwrap(),
        eval_options,
    )
}

fn get_script_or_module_name(ctx: Ctx<'_>) -> String {
    unsafe {
        let ctx_ptr = ctx.as_raw().as_ptr();
        let atom = qjs::JS_GetScriptOrModuleName(ctx_ptr, 0);
        let c_str = qjs::JS_AtomToCString(ctx_ptr, atom);
        if c_str.is_null() {
            qjs::JS_FreeCString(ctx_ptr, c_str);
            return String::from(".");
        }
        let bytes = CStr::from_ptr(c_str).to_bytes();
        let res = std::str::from_utf8_unchecked(bytes).to_string();
        qjs::JS_FreeCString(ctx_ptr, c_str);
        res
    }
}

fn set_import_meta(module: &Module<'_>, filepath: &str) -> Result<()> {
    let meta: Object = module.meta()?;
    meta.prop("url", format!("file://{}", filepath))?;
    Ok(())
}

pub trait ErrorExtensions<'js> {
    fn into_value(self, ctx: &Ctx<'js>) -> Result<Value<'js>>;
}

impl<'js> ErrorExtensions<'js> for Error {
    fn into_value(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
        Err::<(), _>(self).catch(ctx).unwrap_err().into_value(ctx)
    }
}

impl<'js> ErrorExtensions<'js> for CaughtError<'js> {
    fn into_value(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
        Ok(match self {
            CaughtError::Error(err) => {
                JsString::from_str(ctx.clone(), &err.to_string())?.into_value()
            }
            CaughtError::Exception(ex) => ex.into_value(),
            CaughtError::Value(val) => val,
        })
    }
}

pub trait CtxExtension<'js> {
    fn spawn_exit<F, R>(&self, future: F) -> Result<Receiver<R>>
    where
        F: Future<Output = Result<R>> + 'js,
        R: 'js;
}

impl<'js> CtxExtension<'js> for Ctx<'js> {
    fn spawn_exit<F, R>(&self, future: F) -> Result<Receiver<R>>
    where
        F: Future<Output = Result<R>> + 'js,
        R: 'js,
    {
        todo!();
        // let ctx = self.clone();

        // let type_error_ctor: Constructor = ctx.globals().get(PredefinedAtom::TypeError)?;
        // let type_error: Object = type_error_ctor.construct(())?;
        // let stack: Option<String> = type_error.get(PredefinedAtom::Stack).ok();

        // let (join_channel_tx, join_channel_rx) = oneshot::channel();

        // self.spawn(async move {
        //     match future.await.catch(&ctx) {
        //         Ok(res) => {
        //             //result here dosn't matter if receiver has dropped
        //             let _ = join_channel_tx.send(res);
        //         }
        //         Err(err) => {
        //             // if let CaughtError::Exception(err) = err {
        //             //     if err.stack().is_none() {
        //             //         if let Some(stack) = stack {
        //             //             err.set(PredefinedAtom::Stack, stack).unwrap();
        //             //         }
        //             //     }
        //             //     Vm::print_error_and_exit(&ctx, CaughtError::Exception(err));
        //             // } else {
        //             //     Vm::print_error_and_exit(&ctx, err);
        //             // }
        //         }
        //     }
        // });
        // Ok(join_channel_rx)
    }
}