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
#![feature(let_chains)]
mod vec_or_str;
use std::{
  collections::HashMap,
  fs::File,
  io::Read,
  path::{Path, PathBuf},
  rc::Rc,
};

pub use boa_engine;
use boa_engine::{
  js_string,
  module::SimpleModuleLoader,
  object::builtins::{JsArray, JsUint8Array},
  property::{Attribute, PropertyKey},
  string::JsString,
  Context, JsArgs, JsError, JsNativeError, JsObject, JsResult, JsValue, Module, NativeFunction,
  Source,
};
use boa_runtime::Console;
use thiserror::Error;
use tracing::error;
pub use vec_or_str::VecOrStr;

#[derive(Error, Debug)]
pub enum Error {
  #[error("Js: {0}\n{1}")]
  Js(String, String),
}

fn read_file_to_vec(path: impl AsRef<Path>) -> std::io::Result<Vec<u8>> {
  // 打开文件
  let mut file = File::open(path)?;
  // 创建一个空的 Vec<u8>
  let mut buffer = Vec::new();
  // 读取文件内容到 Vec<u8>
  file.read_to_end(&mut buffer)?;
  // 返回结果
  Ok(buffer)
}

fn vec_to_uint8array(context: &mut Context, data: Vec<u8>) -> JsResult<JsValue> {
  Ok(JsValue::Object(
    JsUint8Array::from_iter(data, context)?.into(),
  ))
}

macro_rules! throw {
  ($str:expr $(,$arg:tt)* $(,)?) => {{
    let err: JsError = JsNativeError::typ()
      .with_message(format!($str,$($arg,)*))
      .into();
    return Err(err);
  }};
}

pub fn ctx(root: &str) -> Context {
  let loader = Rc::new(SimpleModuleLoader::new(root).unwrap());
  let mut binding = Context::builder()
    .module_loader(loader.clone())
    .build()
    .unwrap();
  let ctx = &mut binding;

  let console = Console::init(ctx);

  {
    ctx
      .register_global_builtin_callable("rDir".into(), 1, unsafe {
        NativeFunction::from_closure(move |_, args, ctx| {
          let fp = args.get_or_undefined(0);
          if fp.is_undefined() {
            throw!("rDir: miss arg dir")
          }

          match std::fs::read_dir(fp.to_string(ctx)?.to_std_string_escaped()) {
            Ok(r) => {
              let dir_li = JsArray::new(ctx);
              let file_li = JsArray::new(ctx);
              for i in r.flatten() {
                if let Ok(file_type) = i.file_type() {
                  let li = if file_type.is_dir() {
                    &dir_li
                  } else {
                    &file_li
                  };
                  let name = i.file_name().to_os_string().to_string_lossy().to_string();
                  let name = JsString::from(name);
                  li.push(name, ctx)?;
                }
              }
              let li = JsArray::new(ctx);
              li.push(dir_li, ctx)?;
              li.push(file_li, ctx)?;
              Ok(li.into())
            }
            Err(e) => {
              throw!("rDir: {e}")
            }
          }
        })
      })
      .unwrap();
  };
  {
    ctx
      .register_global_builtin_callable("wPath".into(), 1, unsafe {
        NativeFunction::from_closure(move |_, args, ctx| {
          let fp = args.get_or_undefined(0);

          if fp.is_undefined() {
            throw!("wPath: miss arg path")
          }

          let fpstr = &fp.to_string(ctx)?.to_std_string_escaped();
          let fp: PathBuf = fpstr.into();

          let bin = args.get_or_undefined(1);
          if bin.is_undefined() {
            throw!("wPath {fpstr}: miss data")
          }

          if let Some(dir) = fp.parent() {
            if let Err(err) = std::fs::create_dir_all(dir) {
              throw!("wPath {fpstr}: {err}")
            }
          }

          if let Some(txt) = bin.as_string() {
            let txt = txt.to_std_string_escaped();
            return match std::fs::write(fp, txt.as_bytes()) {
              Ok(_) => Ok(JsValue::undefined()),
              Err(e) => {
                throw!("wPath {fpstr}: {e}")
              }
            };
          };
          throw!("wPath {fpstr}: unsupport data type")
        })
      })
      .unwrap();
  }

  {
    ctx
      .register_global_builtin_callable("rBin".into(), 1, unsafe {
        NativeFunction::from_closure(move |_, args, ctx| {
          let name = args.get_or_undefined(0);

          if name.is_undefined() {
            throw!("rBin: miss arg path")
          }

          let fp = name.to_string(ctx)?.to_std_string_escaped();

          match read_file_to_vec(&fp) {
            Ok(s) => Ok(vec_to_uint8array(ctx, s)?),
            Err(e) => {
              throw!("rBin('{fp}') : {e}")
            }
          }
        })
      })
      .unwrap();
  }

  ctx
    .register_global_builtin_callable("rStr".into(), 1, unsafe {
      NativeFunction::from_closure(move |_, args, ctx| {
        let name = args.get_or_undefined(0);

        if name.is_undefined() {
          throw!("rStr: miss arg path")
        }

        let fp = name.to_string(ctx)?.to_std_string_escaped();
        match std::fs::read_to_string(&fp) {
          Ok(s) => Ok(JsValue::String(JsString::from(s))),
          Err(e) => {
            throw!("rStr('{fp}') : {e}")
          }
        }
      })
    })
    .unwrap();

  ctx
    .register_global_property(js_string!(Console::NAME), console, Attribute::all())
    .unwrap();

  binding
}

// https://github.com/boa-dev/boa/blob/main/examples/src/bin/modules.rs
pub fn _default(ctx: &mut Context, js_code: &str, args: &[JsValue]) -> JsResult<JsValue> {
  let code = Source::from_bytes(js_code);
  let module = Module::parse(code, None, ctx)?;
  let _promise = module.load_link_evaluate(ctx);

  ctx.run_jobs();
  let namespace = module.namespace(ctx);

  let mix = namespace
    .get(js_string!("default"), ctx)?
    .as_callable()
    .cloned()
    .ok_or_else(|| JsNativeError::typ().with_message("export default not function !"))?;

  let r = mix.call(&JsValue::undefined(), args, ctx)?;
  Ok(r)
}

pub fn default(
  ctx: &mut Context,
  fp: impl Into<PathBuf>,
  args: &[JsValue],
) -> Result<JsValue, Error> {
  let fp = fp.into();

  macro_rules! ok {
    ($r:expr) => {
      match $r {
        Ok(r) => r,
        Err(e) => return Err(Error::Js(fp.display().to_string(), e.to_string())),
      }
    };
  }

  let js_code = ok!(std::fs::read_to_string(&fp));

  Ok(ok!(_default(ctx, &js_code, args)))
}

pub fn obj2map(obj: JsValue) -> Result<HashMap<String, JsValue>, JsError> {
  if let JsValue::Object(ref obj) = obj {
    let obj = obj.borrow();
    let key_li = obj.shape().keys();
    let mut r = HashMap::with_capacity(key_li.len());
    let map = obj.properties();
    for key in key_li {
      if let Some(val) = map.get(&key) {
        if let Some(val) = val.value() {
          if let PropertyKey::String(key) = key {
            r.insert(key.to_std_string_escaped(), val.clone());
          }
        }
      }
    }
    return Ok(r);
  }
  Ok(Default::default())
}

pub fn obj_get(obj: &JsValue, key: &str) -> Result<Option<JsValue>, JsError> {
  if let JsValue::Object(ref obj) = obj {
    let obj = obj.borrow();
    let map = obj.properties();

    let key = boa_engine::property::PropertyKey::from(JsString::from(key));
    if let Some(val) = map.get(&key) {
      if let Some(val) = val.value() {
        return Ok(Some(val.clone()));
      }
    }
  }
  Ok(None)
}

pub fn li_str(ctx: &mut Context, li: JsValue) -> Vec<(String, String)> {
  if let JsValue::Object(ref li) = li
    && li.is_array()
  {
    let li = JsArray::from_object(li.clone()).unwrap();
    let len = li.length(ctx).unwrap();
    let mut r = Vec::with_capacity(len as usize);
    for i in 0..len {
      if let Ok(e) = li.get(i, ctx) {
        if let JsValue::Object(e) = e
          && e.is_array()
        {
          let e = JsArray::from_object(e).unwrap();
          let len = e.length(ctx).unwrap();
          if len >= 2 {
            if let Ok(fp) = e.get(0, ctx) {
              if let JsValue::String(fp) = fp {
                if let Ok(txt) = e.get(1, ctx) {
                  if let JsValue::String(txt) = txt {
                    r.push((fp.to_std_string_escaped(), txt.to_std_string_escaped()));
                  } else {
                    error!("{:?} is not string", txt)
                  }
                }
              } else {
                error!("fp {:?} is not string", fp)
              }
            }
          }
        }
      }
    }
    r
  } else {
    // error!("return {:?} is not array", li);
    vec![]
  }
}

pub struct JsMap<'a> {
  pub ctx: &'a mut Context,
  pub obj: JsObject,
}

impl<'a> JsMap<'a> {
  pub fn new(ctx: &'a mut Context) -> Self {
    let obj = JsObject::with_object_proto(ctx.intrinsics());
    JsMap { ctx, obj }
  }
  pub fn set(&mut self, key: impl AsRef<str>, value: impl Into<JsValue>) {
    let key_js = PropertyKey::from(JsString::from(key.as_ref()));
    self.obj.set(key_js, value, false, self.ctx).unwrap();
  }

  pub fn value(self) -> JsValue {
    self.obj.into()
  }

  pub fn set_str(&mut self, key: impl AsRef<str>, value: impl AsRef<str>) {
    let value_js = JsString::from(value.as_ref());
    self.set(key, value_js);
  }
}

// pub fn li_str_to_jsvalue<S: Copy + Into<JsString>>(ctx: &mut Context, li: &[S]) -> JsValue {
//   let array = JsArray::new(ctx);
//   for (i, s) in li.iter().enumerate() {
//     let s: JsString = (*s).into();
//     array.set(i as u32, s, false, ctx).unwrap();
//   }
//   array.into()
// }
//
// pub fn li_hashmap_to_jsvalue(ctx: &mut Context, li: &[HashMap<&str, String>]) -> JsValue {
//   let array = JsArray::new(ctx);
//
//   for (i, hashmap) in li.iter().enumerate() {
//     let obj = JsObject::with_object_proto(ctx.intrinsics());
//
//     for (key, value) in hashmap {
//       let key_js = PropertyKey::from(JsString::from(*key));
//       let value_js = JsString::from(value.as_str());
//       obj.set(key_js, value_js, false, ctx).unwrap();
//     }
//
//     array.set(i as u32, obj, false, ctx).unwrap();
//   }
//
//   array.into()
// }

pub fn to_str(value: JsValue) -> Option<String> {
  if let JsValue::String(s) = value {
    return Some(s.to_std_string_escaped());
  }
  None
}