1use crate::host::{with_host, JsObj};
4use fusevm::Value;
5use indexmap::IndexMap;
6
7pub const METHODS: &[&str] = &[
8 "format",
9 "formatWithOptions",
10 "inspect",
11 "deprecate",
12 "inherits",
13 "types",
14 "types.isMap",
15 "types.isSet",
16 "types.isPromise",
17 "types.isDate",
18 "types.isRegExp",
19 "types.isNativeError",
20 "types.isAsyncFunction",
21 "isDeepStrictEqual",
22 "isArray",
23 "debuglog",
24 "stripVTControlCharacters",
25 "toUSVString",
26 "getSystemErrorName",
27 "getSystemErrorMessage",
28 "getSystemErrorMap",
29 "styleText",
30 "parseArgs",
31 "promisify",
32 "aborted",
33 "callbackify",
34 "parseEnv",
35 "debug",
36];
37
38pub fn constant(name: &str) -> Option<Value> {
41 match name {
42 "types" => Some(with_host(|h| h.alloc(JsObj::Builtin("util/types".into())))),
43 "TextEncoder" | "TextDecoder" | "MIMEType" | "MIMEParams" => {
44 Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
45 }
46 _ => None,
47 }
48}
49
50pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
51 if let Some(pred) = method.strip_prefix("types.") {
52 return Some(Ok(Value::Bool(type_predicate(pred, args.first()))));
53 }
54 Some(match method {
55 "format" => {
56 match format(args) {
59 Ok(s) => Ok(with_host(|h| h.new_str(s))),
60 Err(e) => Err(e),
61 }
62 }
63 "formatWithOptions" => {
67 let opts = args.first().cloned().unwrap_or(Value::Undef);
68 let is_object = with_host(|h| {
69 matches!(opts, Value::Obj(_)) && h.type_of(&opts) == "object" && !h.is_null(&opts)
70 });
71 if !is_object {
72 return Some(Err(crate::host::invalid_arg_type(
73 "inspectOptions",
74 "argument",
75 "object",
76 &opts,
77 )));
78 }
79 apply_inspect_options(&opts);
80 let out = format(args.get(1..).unwrap_or(&[]));
81 reset_inspect_options();
82 out.map(|s| with_host(|h| h.new_str(s)))
83 }
84 "inspect" => {
85 if let Some(v) = args.first() {
86 crate::builtins::materialize_stack(v);
87 }
88 apply_inspect_options(&args.get(1).cloned().unwrap_or(Value::Undef));
89 let rendered = crate::host::inspect_js(&args.first().cloned().unwrap_or(Value::Undef));
90 reset_inspect_options();
91 rendered.map(|s| with_host(|h| h.new_str(s)))
92 }
93 "deprecate" => Ok(args.first().cloned().unwrap_or(Value::Undef)),
97 "inherits" => Ok(inherits(args)),
101 "types" => Ok(Value::Undef),
104 "isDeepStrictEqual" => Ok(Value::Bool(super::assert::deep_equal(
105 &args.first().cloned().unwrap_or(Value::Undef),
106 &args.get(1).cloned().unwrap_or(Value::Undef),
107 true,
108 ))),
109 "isArray" => Ok(Value::Bool(with_host(|h| {
111 matches!(
112 h.get(&args.first().cloned().unwrap_or(Value::Undef)),
113 Some(JsObj::Array(_))
114 )
115 }))),
116 "stripVTControlCharacters" => {
118 let stripped = strip_vt(&super::arg_str(args, 0));
119 Ok(with_host(|h| h.new_str(stripped)))
120 }
121 "toUSVString" => Ok(with_host(|h| {
125 let s = h.str_of(&args.first().cloned().unwrap_or(Value::Undef));
126 h.new_str(s)
127 })),
128 "getSystemErrorName" => {
129 let e = errno_of(super::arg_num(args, 0));
130 let name = errno_name(e)
131 .map(str::to_string)
132 .unwrap_or_else(|| format!("Unknown system error {e}"));
133 Ok(with_host(|h| h.new_str(name)))
134 }
135 "getSystemErrorMessage" => {
136 let e = errno_of(super::arg_num(args, 0));
137 let msg = errno_message(e)
138 .map(str::to_string)
139 .unwrap_or_else(|| format!("Unknown system error {e}"));
140 Ok(with_host(|h| h.new_str(msg)))
141 }
142 "getSystemErrorMap" => Ok(system_error_map()),
143 "styleText" => return Some(style_text(args)),
144 "parseArgs" => return Some(parse_args(args)),
145 "@@nodeError" => return Some(node_error(args)),
146 "@@readableStreamCancel" => return Some(super::stream_web::readable_stream_cancel(args)),
151 "@@promiseState" => {
152 let p = args.first().cloned().unwrap_or(Value::Undef);
153 let state = with_host(|h| h.promise_id(&p).map(|id| h.promise_state(id)));
154 Ok(Value::Int(match state {
155 Some(crate::host::PromiseState::Fulfilled) => 1,
156 Some(crate::host::PromiseState::Rejected) => 2,
157 _ => 0,
158 }))
159 }
160 "debuglog" => return Some(debuglog(args)),
161 "promisify" => return Some(promisify(args)),
162 "aborted" => {
166 let signal = args.first().cloned().unwrap_or(Value::Undef);
167 let resource = args.get(1).cloned().unwrap_or(Value::Undef);
168 return Some(aborted(&signal, &resource));
169 }
170 "callbackify" => return Some(callbackify(args)),
171 "parseEnv" => Ok(parse_env(&super::arg_str(args, 0))),
173 "debug" => return Some(debuglog(args)),
175 _ => return None,
176 })
177}
178
179fn apply_inspect_options(options: &Value) {
183 let depth = match Some(options).filter(|o| !matches!(o, Value::Undef)) {
185 Some(opts) => match crate::builtins::get_property(opts, "depth") {
186 Ok(Value::Undef) => 2,
187 Ok(v) if with_host(|h| h.is_null(&v)) => i64::MAX,
188 Ok(v) => {
189 let n = with_host(|h| h.to_number(&v));
190 match n {
195 _ if n.is_nan() || n == f64::INFINITY => i64::MAX,
196 _ if n == f64::NEG_INFINITY => i64::MIN,
197 _ => n.trunc().clamp(i64::MIN as f64, i64::MAX as f64) as i64,
198 }
199 }
200 Err(_) => 2,
201 },
202 None => 2,
203 };
204 crate::host::set_inspect_max_depth(depth);
205 let opts = options.clone();
209 let read = |k: &str| crate::builtins::get_property(&opts, k).unwrap_or(Value::Undef);
210 let compact = match read("compact") {
211 Value::Undef => 3,
212 Value::Bool(false) => 0,
213 Value::Bool(true) => i64::MAX,
216 v => with_host(|h| h.to_number(&v)).max(0.0) as i64,
217 };
218 let break_length = match read("breakLength") {
219 Value::Undef => 80,
220 v => {
221 let n = with_host(|h| h.to_number(&v));
222 if n.is_finite() {
223 n.max(0.0) as usize
224 } else {
225 usize::MAX
226 }
227 }
228 };
229 let sorted_opt = read("sorted");
236 let sorted = with_host(|h| h.truthy(&sorted_opt));
237 let custom_inspect = match read("customInspect") {
240 Value::Undef => true,
241 v => with_host(|h| h.truthy(&v)),
242 };
243 let show_hidden_opt = read("showHidden");
244 let show_hidden = with_host(|h| h.truthy(&show_hidden_opt));
245 let max_array_length = match read("maxArrayLength") {
249 Value::Undef => crate::host::DEFAULT_MAX_ARRAY_LENGTH,
250 v if with_host(|h| h.is_null(&v)) => usize::MAX,
251 v => {
252 let n = with_host(|h| h.to_number(&v));
253 if n.is_finite() {
254 n.max(0.0) as usize
255 } else {
256 usize::MAX
257 }
258 }
259 };
260 let numeric_separator_opt = read("numericSeparator");
261 let numeric_separator = with_host(|h| h.truthy(&numeric_separator_opt));
262 let show_proxy_opt = read("showProxy");
263 let show_proxy = with_host(|h| h.truthy(&show_proxy_opt));
264 let max_string_length = match read("maxStringLength") {
266 Value::Undef => crate::host::DEFAULT_MAX_STRING_LENGTH,
267 v if with_host(|h| h.is_null(&v)) => usize::MAX,
268 v => {
269 let n = with_host(|h| h.to_number(&v));
270 if n.is_finite() {
271 n.max(0.0) as usize
272 } else {
273 usize::MAX
274 }
275 }
276 };
277 let getters_opt = read("getters");
279 let getters = with_host(|h| match h.as_str(&getters_opt).as_deref() {
280 Some("get") => 2,
281 Some("set") => 3,
282 _ if h.truthy(&getters_opt) => 1,
283 _ => 0,
284 });
285 crate::host::set_inspect_getters(getters);
286 crate::host::set_inspect_numeric_separator(numeric_separator);
287 crate::host::set_inspect_show_proxy(show_proxy);
288 crate::host::set_inspect_max_string_length(max_string_length);
289 crate::host::set_inspect_compact(compact);
290 crate::host::set_inspect_break_length(break_length);
291 crate::host::set_inspect_sorted(sorted);
292 crate::host::set_inspect_max_array_length(max_array_length);
293 crate::host::set_inspect_custom(custom_inspect);
294 crate::host::set_inspect_show_hidden(show_hidden);
295}
296
297fn reset_inspect_options() {
299 crate::host::set_inspect_max_depth(2);
300 crate::host::set_inspect_compact(3);
301 crate::host::set_inspect_break_length(80);
302 crate::host::set_inspect_sorted(false);
303 crate::host::set_inspect_max_array_length(crate::host::DEFAULT_MAX_ARRAY_LENGTH);
304 crate::host::set_inspect_custom(true);
305 crate::host::set_inspect_getters(0);
306 crate::host::set_inspect_numeric_separator(false);
307 crate::host::set_inspect_show_proxy(false);
308 crate::host::set_inspect_max_string_length(crate::host::DEFAULT_MAX_STRING_LENGTH);
309 crate::host::set_inspect_show_hidden(false);
310}
311
312fn inherits(args: &[Value]) -> Value {
314 let ctor = args.first().cloned().unwrap_or(Value::Undef);
315 let sup = args.get(1).cloned().unwrap_or(Value::Undef);
316 with_host(|h| {
317 let sup_proto = h.fn_prop(&sup, "prototype").unwrap_or_else(|| {
320 let mut props = indexmap::IndexMap::new();
321 props.insert("constructor".to_string(), sup.clone());
322 let p = h.new_object(props);
323 h.set_fn_prop(&sup, "prototype", p.clone());
324 p
325 });
326 let ctor_proto = h.fn_prop(&ctor, "prototype").unwrap_or_else(|| {
328 let mut props = indexmap::IndexMap::new();
329 props.insert("constructor".to_string(), ctor.clone());
330 let p = h.new_object(props);
331 h.set_fn_prop(&ctor, "prototype", p.clone());
332 p
333 });
334 h.set_proto(&ctor_proto, sup_proto);
335 h.set_fn_prop(&ctor, "super_", sup);
336 });
337 Value::Undef
338}
339
340fn type_predicate(pred: &str, v: Option<&Value>) -> bool {
341 let Some(v) = v else { return false };
342 with_host(|h| match pred {
343 "isMap" => matches!(h.get(v), Some(JsObj::Map { weak: false, .. })),
344 "isSet" => matches!(h.get(v), Some(JsObj::Set { weak: false, .. })),
345 "isPromise" => matches!(h.get(v), Some(JsObj::Promise { .. })),
346 _ => false,
347 })
348}
349
350fn fmt_directive_number(n: f64) -> String {
354 if n == 0.0 && n.is_sign_negative() {
355 return "-0".into();
356 }
357 crate::host::fmt_number(n)
358}
359
360fn coerce_via(parser: &str, arg: &Value) -> Result<f64, String> {
364 let v = crate::builtins::call_builtin_function(parser, vec![arg.clone()])?;
369 Ok(with_host(|h| h.to_number(&v)))
370}
371
372pub fn format(args: &[Value]) -> Result<String, String> {
380 for a in args {
385 crate::builtins::materialize_stack(a);
386 }
387 if args.is_empty() {
388 return Ok(String::new());
389 }
390 if args.len() == 1 {
393 return crate::host::console_format_js(&args[0]);
394 }
395 let fmt = with_host(|h| h.str_of(&args[0]));
396 if !matches!(args[0], Value::Str(_))
398 && !with_host(|h| matches!(h.get(&args[0]), Some(JsObj::Str(_))))
399 {
400 return Ok(args
401 .iter()
402 .map(crate::host::console_format_js)
403 .collect::<Result<Vec<_>, _>>()?
404 .join(" "));
405 }
406
407 let mut out = String::new();
408 let mut ai = 1usize;
409 let mut chars = fmt.chars().peekable();
410 while let Some(c) = chars.next() {
411 if c != '%' {
412 out.push(c);
413 continue;
414 }
415 let Some(&spec) = chars.peek() else {
416 out.push('%');
417 break;
418 };
419 if spec == '%' {
420 out.push('%');
421 chars.next();
422 continue;
423 }
424 if !matches!(spec, 's' | 'd' | 'i' | 'f' | 'j' | 'o' | 'O' | 'c') || ai >= args.len() {
425 out.push('%');
426 continue;
427 }
428 chars.next();
429 let arg = &args[ai];
430 ai += 1;
431 match spec {
432 's' => {
443 if let Value::Float(n) = arg {
447 out.push_str(&fmt_directive_number(*n));
448 continue;
449 }
450 let (bigint, use_inspect) = with_host(|h| match h.get(arg) {
451 Some(JsObj::BigInt(b)) => (Some(format!("{b}n")), false),
452 _ => {
453 let is_obj = h.type_of(arg) == "object" && !h.is_null(arg);
454 let stringifies = matches!(h.get(arg), Some(JsObj::Object(p))
473 if matches!(
474 p.get("@@native").map(|t| h.str_of(t)).as_deref(),
475 Some("Buffer") | Some("TypedArray")
476 ));
477 if stringifies {
478 return (None, false);
479 }
480 let scripted = ["toString", "@@toPrimitive"].iter().any(|k| {
481 crate::host::lookup_chain(h, arg, k).is_some_and(|f| {
482 matches!(
483 h.get(&f),
484 Some(JsObj::Func(_))
485 | Some(JsObj::Class(_))
486 | Some(JsObj::BoundFunc { .. })
487 )
488 })
489 });
490 (None, is_obj && !scripted)
491 }
492 });
493 if let Some(b) = bigint {
494 out.push_str(&b);
495 } else if use_inspect {
496 let (depth, compact) = (
498 crate::host::inspect_max_depth(),
499 crate::host::inspect_compact(),
500 );
501 crate::host::set_inspect_max_depth(0);
502 crate::host::set_inspect_compact(3);
503 let s = crate::host::inspect_js(arg);
504 crate::host::set_inspect_max_depth(depth);
505 crate::host::set_inspect_compact(compact);
506 let s = s?;
507 out.push_str(&s);
508 } else {
509 let s = crate::host::to_string_value(arg)
513 .map(|v| with_host(|h| h.str_of(&v)))
514 .unwrap_or_else(|_| with_host(|h| h.str_of(arg)));
515 out.push_str(&s);
516 }
517 }
518 'd' | 'i' => {
527 let big = with_host(|h| match h.get(arg) {
528 Some(JsObj::BigInt(b)) => Some(format!("{b}n")),
529 _ => None,
530 });
531 let is_symbol = with_host(|h| h.type_of(arg) == "symbol");
535 match big {
536 Some(s) => out.push_str(&s),
537 None if is_symbol => out.push_str("NaN"),
538 None if spec == 'd' => {
539 out.push_str(&fmt_directive_number(crate::host::to_number_value(arg)?))
540 }
541 None => out.push_str(&fmt_directive_number(coerce_via("parseInt", arg)?)),
542 }
543 }
544 'f' => {
545 let is_symbol = with_host(|h| h.type_of(arg) == "symbol");
546 if is_symbol {
547 out.push_str("NaN");
548 } else {
549 out.push_str(&fmt_directive_number(coerce_via("parseFloat", arg)?));
550 }
551 }
552 'j' => {
553 match crate::builtins::call_builtin_function("JSON.stringify", vec![arg.clone()]) {
557 Ok(v) => out.push_str(&with_host(|h| h.str_of(&v))),
558 Err(e) if e.contains("circular structure") => out.push_str("[Circular]"),
559 Err(e) => return Err(e),
560 }
561 }
562 'O' => out.push_str(&crate::host::inspect_js(arg)?),
569 'o' => {
572 let saved = (
573 crate::host::inspect_show_proxy(),
574 crate::host::inspect_show_hidden(),
575 crate::host::inspect_max_depth(),
576 );
577 crate::host::set_inspect_show_proxy(true);
578 crate::host::set_inspect_show_hidden(true);
579 crate::host::set_inspect_max_depth(4);
580 let s = crate::host::inspect_js(arg);
581 crate::host::set_inspect_show_proxy(saved.0);
582 crate::host::set_inspect_show_hidden(saved.1);
583 crate::host::set_inspect_max_depth(saved.2);
584 out.push_str(&s?);
585 }
586 'c' => {} _ => {}
588 }
589 }
590 for a in &args[ai..] {
592 out.push(' ');
593 out.push_str(&crate::host::console_format_js(a)?);
594 }
595 Ok(out)
596}
597
598fn run_completion(src: &str) -> Result<Value, String> {
608 crate::eval_internal(src)
609}
610
611const PROMISIFY_SRC: &str = "(function(original, custom, argNames, sym){\n\
622 var c = custom || original[sym];\n\
623 if (c) {\n\
624 if (typeof c !== 'function') return [c];\n\
625 try { Object.defineProperty(c, sym, { value: c, enumerable: false, writable: false, configurable: true }); } catch (_) {}\n\
626 return c;\n\
627 }\n\
628 function fn(...args) {\n\
629 var self = this;\n\
630 return new Promise(function(resolve, reject){\n\
631 args.push(function(err, ...values){\n\
632 if (err) return reject(err);\n\
633 if (argNames !== undefined && values.length > 1) {\n\
634 var obj = {};\n\
635 for (var i = 0; i < argNames.length; i++) obj[argNames[i]] = values[i];\n\
636 resolve(obj);\n\
637 } else {\n\
638 resolve(values[0]);\n\
639 }\n\
640 });\n\
641 Reflect.apply(original, self, args);\n\
642 });\n\
643 }\n\
644 Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\
645 Object.defineProperty(fn, sym, { value: fn, enumerable: false, writable: false, configurable: true });\n\
646 return Object.defineProperties(fn, Object.getOwnPropertyDescriptors(original));\n\
647})";
648
649const EXISTS_PROMISIFIED_SRC: &str = "(function exists(path){\n\
652 return new Promise(function(resolve){ require('fs').exists(path, resolve); });\n\
653})";
654
655const CUSTOM_EXEC_SRC: &str = "(function(orig, name){\n\
659 const f = function(...args) {\n\
660 const { promise, resolve, reject } = Promise.withResolvers();\n\
661 promise.child = orig(...args, (err, stdout, stderr) => {\n\
662 if (err !== null) {\n\
663 err.stdout = stdout;\n\
664 err.stderr = stderr;\n\
665 reject(err);\n\
666 } else {\n\
667 resolve({ stdout, stderr });\n\
668 }\n\
669 });\n\
670 return promise;\n\
671 };\n\
672 Object.defineProperty(f, 'name', { value: name });\n\
673 return f;\n\
674})";
675
676pub(crate) fn custom_promisified(builtin: &str) -> Option<Result<Value, String>> {
682 let alias = |target: &str| Some(Ok(with_host(|h| h.alloc(JsObj::Builtin(target.into())))));
683 match builtin {
684 "setTimeout" => return alias("timers/promises.setTimeout"),
685 "setImmediate" => return alias("timers/promises.setImmediate"),
686 "stream.pipeline" | "Stream.pipeline" => return alias("stream/promises.pipeline"),
687 "stream.finished" | "Stream.finished" => return alias("stream/promises.finished"),
688 "fs.exists" | "child_process.exec" | "child_process.execFile" => {}
689 _ => return None,
690 }
691 thread_local! {
692 static MADE: std::cell::RefCell<std::collections::HashMap<String, Value>> =
693 std::cell::RefCell::new(std::collections::HashMap::new());
694 }
695 if let Some(v) = MADE.with(|m| m.borrow().get(builtin).cloned()) {
696 return Some(Ok(v));
697 }
698 let made = (|| {
699 if builtin == "fs.exists" {
700 return run_completion(EXISTS_PROMISIFIED_SRC);
701 }
702 let factory = run_completion(CUSTOM_EXEC_SRC)?;
703 let (orig, name) = with_host(|h| {
704 let short = builtin.trim_start_matches("child_process.");
705 (h.alloc(JsObj::Builtin(builtin.into())), h.new_str(short))
706 });
707 crate::host::invoke(&factory, vec![orig, name], None)
708 })();
709 if let Ok(v) = &made {
710 MADE.with(|m| m.borrow_mut().insert(builtin.to_string(), v.clone()));
711 }
712 Some(made)
713}
714
715const CALLBACKIFY_SRC: &str = "(function(original){\n\
716 return function(){\n\
717 var self = this;\n\
718 var args = Array.prototype.slice.call(arguments);\n\
719 var cb = args.pop();\n\
720 Promise.resolve(original.apply(self, args)).then(\n\
721 function(value){ cb.call(self, null, value); },\n\
722 function(err){ cb.call(self, err || new Error('Promise was rejected with a falsy value')); }\n\
723 );\n\
724 };\n\
725})";
726
727fn aborted(signal: &Value, resource: &Value) -> Result<Value, String> {
736 if !with_host(|h| {
737 matches!(
738 h.get(resource),
739 Some(crate::host::JsObj::Object(_)) | Some(crate::host::JsObj::Array(_))
740 ) || crate::host::is_callable(h, resource)
741 }) {
742 return Err(crate::host::invalid_arg_type(
743 "resource", "argument", "object", resource,
744 ));
745 }
746 let already = crate::builtins::get_property(signal, "aborted").unwrap_or(Value::Undef);
747 if with_host(|h| h.truthy(&already)) {
748 return crate::builtins::promise_resolve_pub(Value::Undef);
749 }
750 let (promise, resolve) = crate::builtins::pending_promise_with_resolver();
755 crate::host::call_method(
756 signal,
757 "addEventListener",
758 vec![with_host(|h| h.new_str("abort")), resolve],
759 )?;
760 Ok(promise)
761}
762
763fn promisify(args: &[Value]) -> Result<Value, String> {
764 let orig = args.first().cloned().unwrap_or(Value::Undef);
765 if !with_host(|h| crate::host::is_callable(h, &orig)) {
766 return Err(std::format!(
767 "TypeError [ERR_INVALID_ARG_TYPE]: The \"original\" argument must be of \
768 type function. Received {}",
769 super::received_desc(&orig)
770 ));
771 }
772 let builtin = with_host(|h| match h.get(&orig) {
776 Some(JsObj::Builtin(name)) => Some(name.clone()),
777 _ => None,
778 });
779 let custom = match builtin.as_deref() {
780 Some(name) => custom_promisified(name).transpose()?,
781 None => None,
782 };
783 let arg_names: Option<&[&str]> = match builtin.as_deref() {
784 Some("fs.read") | Some("fs.readv") => Some(&["bytesRead", "buffer"]),
785 Some("fs.write") => Some(&["bytesWritten", "buffer"]),
786 Some("fs.writev") => Some(&["bytesWritten", "buffers"]),
787 Some("dns.lookup") => Some(&["address", "family"]),
788 Some("dns.lookupService") => Some(&["hostname", "service"]),
789 _ => None,
790 };
791 let (custom, names, sym) = with_host(|h| {
792 let names = match arg_names {
793 Some(list) => {
794 let items = list.iter().map(|n| h.new_str(*n)).collect();
795 h.new_array(items)
796 }
797 None => Value::Undef,
798 };
799 let sym = h.symbol_for("nodejs.util.promisify.custom");
800 (custom.unwrap_or(Value::Undef), names, sym)
801 });
802 let factory = run_completion(PROMISIFY_SRC)?;
803 let out = crate::host::invoke(&factory, vec![orig, custom, names, sym], None)?;
804 if with_host(|h| crate::host::is_callable(h, &out)) {
807 return Ok(out);
808 }
809 let bad = crate::builtins::get_property(&out, "0")?;
810 Err(crate::host::invalid_arg_type(
811 "util.promisify.custom",
812 "property",
813 "function",
814 &bad,
815 ))
816}
817
818fn callbackify(args: &[Value]) -> Result<Value, String> {
821 let orig = args.first().cloned().unwrap_or(Value::Undef);
822 if !with_host(|h| crate::host::is_callable(h, &orig)) {
823 return Err(std::format!(
824 "TypeError [ERR_INVALID_ARG_TYPE]: The \"original\" argument must be of \
825 type function. Received {}",
826 super::received_desc(&orig)
827 ));
828 }
829 let factory = run_completion(CALLBACKIFY_SRC)?;
830 crate::host::invoke(&factory, vec![orig], None)
831}
832
833const DEBUGLOG_ENABLED_SRC: &str = "(function(prefix){\n\
836 var util = require('util');\n\
837 return function(){\n\
838 console.error(prefix + ' ' + util.format.apply(null, arguments));\n\
839 };\n\
840})";
841
842fn debuglog(args: &[Value]) -> Result<Value, String> {
845 let section = super::arg_str(args, 0);
846 if debuglog_enabled(§ion) {
847 let prefix = format!("{} {}:", section.to_uppercase(), std::process::id());
848 let factory = run_completion(DEBUGLOG_ENABLED_SRC)?;
849 let pfx = with_host(|h| h.new_str(prefix));
850 crate::host::invoke(&factory, vec![pfx], None)
851 } else {
852 run_completion("(function(){})")
853 }
854}
855
856fn debuglog_enabled(section: &str) -> bool {
859 let Ok(env) = std::env::var("NODE_DEBUG") else {
860 return false;
861 };
862 let sec = section.to_uppercase();
863 env.split(|c: char| c == ',' || c.is_whitespace())
864 .filter(|s| !s.is_empty())
865 .any(|pat| {
866 let pat = pat.to_uppercase();
867 if pat.contains('*') {
868 wildcard_match(&pat, &sec)
869 } else {
870 pat == sec
871 }
872 })
873}
874
875fn wildcard_match(pat: &str, s: &str) -> bool {
877 let parts: Vec<&str> = pat.split('*').collect();
878 if parts.len() == 1 {
879 return pat == s;
880 }
881 let mut pos = 0usize;
882 for (i, part) in parts.iter().enumerate() {
883 if part.is_empty() {
884 continue;
885 }
886 if i == 0 {
887 if !s[pos..].starts_with(part) {
888 return false;
889 }
890 pos += part.len();
891 } else if i == parts.len() - 1 {
892 return s[pos..].ends_with(part);
893 } else if let Some(idx) = s[pos..].find(part) {
894 pos += idx + part.len();
895 } else {
896 return false;
897 }
898 }
899 true
900}
901
902pub(crate) fn strip_vt(s: &str) -> String {
907 let mut out = String::with_capacity(s.len());
908 let mut chars = s.chars().peekable();
909 while let Some(c) = chars.next() {
910 if c == '\u{9b}' {
911 while let Some(&n) = chars.peek() {
913 chars.next();
914 if ('\u{40}'..='\u{7e}').contains(&n) {
915 break;
916 }
917 }
918 continue;
919 }
920 if c != '\u{1b}' {
921 out.push(c);
922 continue;
923 }
924 match chars.peek() {
925 Some('[') => {
926 chars.next();
927 while let Some(&n) = chars.peek() {
928 chars.next();
929 if ('\u{40}'..='\u{7e}').contains(&n) {
930 break;
931 }
932 }
933 }
934 Some(']') => {
935 chars.next();
936 while let Some(&n) = chars.peek() {
937 if n == '\u{7}' {
938 chars.next();
939 break;
940 }
941 if n == '\u{1b}' {
942 chars.next();
943 if chars.peek() == Some(&'\\') {
944 chars.next();
945 }
946 break;
947 }
948 chars.next();
949 }
950 }
951 Some(_) => {
952 chars.next();
953 }
954 None => {}
955 }
956 }
957 out
958}
959
960fn style_names(v: &Value) -> Vec<String> {
964 with_host(|h| match h.get(v) {
965 Some(JsObj::Array(items)) => items.iter().map(|x| h.str_of(x)).collect(),
966 _ => vec![h.str_of(v)],
967 })
968}
969
970pub(crate) const STYLES: &[(&str, u16, u16)] = &[
981 ("reset", 0, 0),
982 ("bold", 1, 22),
983 ("dim", 2, 22),
984 ("italic", 3, 23),
985 ("underline", 4, 24),
986 ("blink", 5, 25),
987 ("inverse", 7, 27),
988 ("hidden", 8, 28),
989 ("strikethrough", 9, 29),
990 ("doubleunderline", 21, 24),
991 ("black", 30, 39),
992 ("red", 31, 39),
993 ("green", 32, 39),
994 ("yellow", 33, 39),
995 ("blue", 34, 39),
996 ("magenta", 35, 39),
997 ("cyan", 36, 39),
998 ("white", 37, 39),
999 ("bgBlack", 40, 49),
1000 ("bgRed", 41, 49),
1001 ("bgGreen", 42, 49),
1002 ("bgYellow", 43, 49),
1003 ("bgBlue", 44, 49),
1004 ("bgMagenta", 45, 49),
1005 ("bgCyan", 46, 49),
1006 ("bgWhite", 47, 49),
1007 ("framed", 51, 54),
1008 ("overlined", 53, 55),
1009 ("gray", 90, 39),
1010 ("redBright", 91, 39),
1011 ("greenBright", 92, 39),
1012 ("yellowBright", 93, 39),
1013 ("blueBright", 94, 39),
1014 ("magentaBright", 95, 39),
1015 ("cyanBright", 96, 39),
1016 ("whiteBright", 97, 39),
1017 ("bgGray", 100, 49),
1018 ("bgRedBright", 101, 49),
1019 ("bgGreenBright", 102, 49),
1020 ("bgYellowBright", 103, 49),
1021 ("bgBlueBright", 104, 49),
1022 ("bgMagentaBright", 105, 49),
1023 ("bgCyanBright", 106, 49),
1024 ("bgWhiteBright", 107, 49),
1025];
1026
1027pub(crate) const STYLE_ALIASES: &[(&str, u16, u16)] = &[
1030 ("grey", 90, 39),
1031 ("blackBright", 90, 39),
1032 ("bgGrey", 100, 49),
1033 ("bgBlackBright", 100, 49),
1034 ("faint", 2, 22),
1035 ("crossedout", 9, 29),
1036 ("strikeThrough", 9, 29),
1037 ("crossedOut", 9, 29),
1038 ("conceal", 8, 28),
1039 ("swapColors", 7, 27),
1040 ("swapcolors", 7, 27),
1041 ("doubleUnderline", 21, 24),
1042];
1043
1044fn style_codes(name: &str) -> Option<(u16, u16)> {
1046 STYLES
1047 .iter()
1048 .chain(STYLE_ALIASES.iter())
1049 .find(|(n, _, _)| *n == name)
1050 .map(|(_, o, c)| (*o, *c))
1051}
1052
1053fn style_text(args: &[Value]) -> Result<Value, String> {
1063 let fmt = args.first().cloned().unwrap_or(Value::Undef);
1064 let text_v = args.get(1).cloned().unwrap_or(Value::Undef);
1065 let Some(text) = with_host(|h| h.as_str(&text_v)) else {
1066 return Err(crate::host::invalid_arg_type(
1067 "text", "argument", "string", &text_v,
1068 ));
1069 };
1070 let options = args.get(2).cloned().unwrap_or(Value::Undef);
1071 let has_options = !matches!(options, Value::Undef);
1072 if has_options && !is_plain_object_arg(&options) {
1073 return Err(crate::host::invalid_arg_type(
1074 "options", "argument", "object", &options,
1075 ));
1076 }
1077 let opt = |k: &str| -> Result<Value, String> {
1078 if has_options {
1079 crate::builtins::get_property(&options, k)
1080 } else {
1081 Ok(Value::Undef)
1082 }
1083 };
1084 let validate_stream = match opt("validateStream")? {
1085 Value::Undef => true,
1086 Value::Bool(b) => b,
1087 v => {
1088 return Err(crate::host::invalid_arg_type(
1089 "options.validateStream",
1090 "property",
1091 "boolean",
1092 &v,
1093 ))
1094 }
1095 };
1096 let mut skip_colorize = false;
1097 if validate_stream {
1098 let stream = match opt("stream")? {
1099 Value::Undef => crate::builtins::namespace_property("process", "stdout"),
1100 s => s,
1101 };
1102 if !is_stream_like(&stream)? {
1103 return Err(crate::host::coded_error(
1104 "TypeError",
1105 "ERR_INVALID_ARG_TYPE",
1106 &format!(
1107 "The \"stream\" argument must be an instance of ReadableStream, WritableStream, or Stream. Received {}",
1108 super::received_desc(&stream)
1109 ),
1110 ));
1111 }
1112 skip_colorize = !should_colorize(&stream)?;
1113 }
1114 let (mut open_codes, mut close_codes, mut processed) =
1115 (String::new(), String::new(), text.clone());
1116 for name in style_names(&fmt) {
1117 if name == "none" {
1118 continue;
1119 }
1120 let (open, close, keep_close) = if let Some(hex) = name.strip_prefix('#') {
1121 let Some((r, g, b)) = hex_rgb(hex) else {
1122 return Err(crate::host::coded_error(
1123 "TypeError",
1124 "ERR_INVALID_ARG_VALUE",
1125 &format!(
1126 "The argument 'format' must be a valid hex color (#RGB or #RRGGBB). Received '{name}'"
1127 ),
1128 ));
1129 };
1130 if skip_colorize {
1131 continue;
1132 }
1133 (
1134 format!("\u{1b}[38;2;{r};{g};{b}m"),
1135 "\u{1b}[39m".to_string(),
1136 false,
1137 )
1138 } else {
1139 let (open, close) = style_codes(&name).ok_or_else(|| {
1140 let listed: Vec<String> = STYLES
1144 .iter()
1145 .chain(STYLE_ALIASES.iter())
1146 .map(|(n, _, _)| format!("'{n}'"))
1147 .collect();
1148 crate::host::coded_error(
1149 "TypeError",
1150 "ERR_INVALID_ARG_VALUE",
1151 &format!(
1152 "The argument 'format' must be one of: {}. Received '{name}'",
1153 listed.join(", ")
1154 ),
1155 )
1156 })?;
1157 (
1158 format!("\u{1b}[{open}m"),
1159 format!("\u{1b}[{close}m"),
1160 close == 22,
1161 )
1162 };
1163 open_codes.push_str(&open);
1164 close_codes.insert_str(0, &close);
1165 let replacement = if keep_close {
1166 format!("{close}{open}")
1167 } else {
1168 open
1169 };
1170 processed = processed.replace(&close, &replacement);
1171 }
1172 let out = if skip_colorize {
1173 text
1174 } else {
1175 format!("{open_codes}{processed}{close_codes}")
1176 };
1177 Ok(with_host(|h| h.new_str(out)))
1178}
1179
1180fn hex_rgb(hex: &str) -> Option<(u8, u8, u8)> {
1182 if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
1183 return None;
1184 }
1185 let channel = |s: &str| u8::from_str_radix(s, 16).ok();
1186 match hex.len() {
1187 3 => {
1188 let d = |i: usize| channel(&hex[i..i + 1].repeat(2));
1189 Some((d(0)?, d(1)?, d(2)?))
1190 }
1191 6 => Some((
1192 channel(&hex[0..2])?,
1193 channel(&hex[2..4])?,
1194 channel(&hex[4..6])?,
1195 )),
1196 _ => None,
1197 }
1198}
1199
1200fn is_plain_object_arg(v: &Value) -> bool {
1202 with_host(|h| {
1203 h.type_of(v) == "object" && !h.is_null(v) && !matches!(h.get(v), Some(JsObj::Array(_)))
1204 })
1205}
1206
1207fn is_stream_like(v: &Value) -> Result<bool, String> {
1209 if super::stream_web::is_readable_stream(v)? || super::stream_web::is_writable_stream(v)? {
1210 return Ok(true);
1211 }
1212 if !with_host(|h| matches!(h.type_of(v), "object" | "function") && !h.is_null(v)) {
1213 return Ok(false);
1214 }
1215 let get = |k: &str| crate::builtins::get_property(v, k);
1216 let truthy = |x: &Value| with_host(|h| h.truthy(x));
1217 let callable = |x: &Value| with_host(|h| crate::host::is_callable(h, x));
1218 if truthy(&get("_readableState")?) || truthy(&get("_writableState")?) {
1219 return Ok(true);
1220 }
1221 let on = callable(&get("on")?);
1222 Ok(on && (callable(&get("write")?) || callable(&get("pipe")?)))
1223}
1224
1225fn should_colorize(stream: &Value) -> Result<bool, String> {
1229 if let Ok(fc) = std::env::var("FORCE_COLOR") {
1230 return Ok(matches!(fc.as_str(), "" | "1" | "true" | "2" | "3"));
1231 }
1232 let is_tty = crate::builtins::get_property(stream, "isTTY")?;
1233 if !with_host(|h| h.truthy(&is_tty)) {
1234 return Ok(false);
1235 }
1236 let depth = crate::builtins::get_property(stream, "getColorDepth")?;
1237 if !with_host(|h| crate::host::is_callable(h, &depth)) {
1238 return Ok(true);
1239 }
1240 let d = crate::host::invoke(&depth, Vec::new(), Some(stream.clone()))?;
1241 Ok(with_host(|h| h.to_number(&d)) > 2.0)
1242}
1243
1244const ERRNO_TABLE: &[(&str, i32, &str)] = &[
1252 ("E2BIG", libc::E2BIG, "argument list too long"),
1253 ("EACCES", libc::EACCES, "permission denied"),
1254 ("EADDRINUSE", libc::EADDRINUSE, "address already in use"),
1255 (
1256 "EADDRNOTAVAIL",
1257 libc::EADDRNOTAVAIL,
1258 "address not available",
1259 ),
1260 (
1261 "EAFNOSUPPORT",
1262 libc::EAFNOSUPPORT,
1263 "address family not supported",
1264 ),
1265 ("EAGAIN", libc::EAGAIN, "resource temporarily unavailable"),
1266 ("EALREADY", libc::EALREADY, "connection already in progress"),
1267 ("EBADF", libc::EBADF, "bad file descriptor"),
1268 ("EBUSY", libc::EBUSY, "resource busy or locked"),
1269 ("ECANCELED", libc::ECANCELED, "operation canceled"),
1270 (
1271 "ECONNABORTED",
1272 libc::ECONNABORTED,
1273 "software caused connection abort",
1274 ),
1275 ("ECONNREFUSED", libc::ECONNREFUSED, "connection refused"),
1276 ("ECONNRESET", libc::ECONNRESET, "connection reset by peer"),
1277 (
1278 "EDESTADDRREQ",
1279 libc::EDESTADDRREQ,
1280 "destination address required",
1281 ),
1282 ("EEXIST", libc::EEXIST, "file already exists"),
1283 (
1284 "EFAULT",
1285 libc::EFAULT,
1286 "bad address in system call argument",
1287 ),
1288 ("EFBIG", libc::EFBIG, "file too large"),
1289 ("EHOSTDOWN", libc::EHOSTDOWN, "host is down"),
1290 ("EHOSTUNREACH", libc::EHOSTUNREACH, "host is unreachable"),
1291 ("EINTR", libc::EINTR, "interrupted system call"),
1292 ("EINVAL", libc::EINVAL, "invalid argument"),
1293 ("EIO", libc::EIO, "i/o error"),
1294 ("EISCONN", libc::EISCONN, "socket is already connected"),
1295 ("EISDIR", libc::EISDIR, "illegal operation on a directory"),
1296 ("ELOOP", libc::ELOOP, "too many symbolic links encountered"),
1297 ("EMFILE", libc::EMFILE, "too many open files"),
1298 ("EMLINK", libc::EMLINK, "too many links"),
1299 ("EMSGSIZE", libc::EMSGSIZE, "message too long"),
1300 ("ENAMETOOLONG", libc::ENAMETOOLONG, "name too long"),
1301 ("ENETDOWN", libc::ENETDOWN, "network is down"),
1302 ("ENETUNREACH", libc::ENETUNREACH, "network is unreachable"),
1303 ("ENFILE", libc::ENFILE, "file table overflow"),
1304 ("ENOBUFS", libc::ENOBUFS, "no buffer space available"),
1305 ("ENODEV", libc::ENODEV, "no such device"),
1306 ("ENOENT", libc::ENOENT, "no such file or directory"),
1307 ("ENOMEM", libc::ENOMEM, "not enough memory"),
1308 ("ENOPROTOOPT", libc::ENOPROTOOPT, "protocol not available"),
1309 ("ENOSPC", libc::ENOSPC, "no space left on device"),
1310 ("ENOSYS", libc::ENOSYS, "function not implemented"),
1311 ("ENOTCONN", libc::ENOTCONN, "socket is not connected"),
1312 ("ENOTDIR", libc::ENOTDIR, "not a directory"),
1313 ("ENOTEMPTY", libc::ENOTEMPTY, "directory not empty"),
1314 ("ENOTSOCK", libc::ENOTSOCK, "socket operation on non-socket"),
1315 ("ENXIO", libc::ENXIO, "no such device or address"),
1316 (
1317 "EOPNOTSUPP",
1318 libc::EOPNOTSUPP,
1319 "operation not supported on socket",
1320 ),
1321 (
1322 "EOVERFLOW",
1323 libc::EOVERFLOW,
1324 "value too large for defined data type",
1325 ),
1326 ("EPERM", libc::EPERM, "operation not permitted"),
1327 ("EPIPE", libc::EPIPE, "broken pipe"),
1328 ("EPROTO", libc::EPROTO, "protocol error"),
1329 (
1330 "EPROTONOSUPPORT",
1331 libc::EPROTONOSUPPORT,
1332 "protocol not supported",
1333 ),
1334 (
1335 "EPROTOTYPE",
1336 libc::EPROTOTYPE,
1337 "protocol wrong type for socket",
1338 ),
1339 ("ERANGE", libc::ERANGE, "result too large"),
1340 ("EROFS", libc::EROFS, "read-only file system"),
1341 (
1342 "ESHUTDOWN",
1343 libc::ESHUTDOWN,
1344 "cannot send after transport endpoint shutdown",
1345 ),
1346 ("ESPIPE", libc::ESPIPE, "invalid seek"),
1347 ("ESRCH", libc::ESRCH, "no such process"),
1348 ("ETIMEDOUT", libc::ETIMEDOUT, "connection timed out"),
1349 ("ETXTBSY", libc::ETXTBSY, "text file is busy"),
1350 ("EXDEV", libc::EXDEV, "cross-device link not permitted"),
1351];
1352
1353fn errno_of(err: f64) -> i32 {
1356 if err < 0.0 {
1357 (-err) as i32
1358 } else {
1359 err as i32
1360 }
1361}
1362
1363pub(crate) fn errno_name(e: i32) -> Option<&'static str> {
1364 ERRNO_TABLE
1365 .iter()
1366 .find(|(_, code, _)| *code == e)
1367 .map(|(n, _, _)| *n)
1368}
1369
1370fn errno_message(e: i32) -> Option<&'static str> {
1371 ERRNO_TABLE
1372 .iter()
1373 .find(|(_, code, _)| *code == e)
1374 .map(|(_, _, m)| *m)
1375}
1376
1377pub(crate) fn errno_by_name(name: &str) -> Option<(i32, &'static str)> {
1381 ERRNO_TABLE
1382 .iter()
1383 .find(|(n, _, _)| *n == name)
1384 .map(|(_, code, m)| (*code, *m))
1385}
1386
1387fn system_error_map() -> Value {
1389 with_host(|h| {
1390 let mut entries = indexmap::IndexMap::new();
1391 for (name, code, msg) in ERRNO_TABLE {
1392 let key_val = Value::Float(-(*code as f64));
1393 let name_v = h.new_str(*name);
1394 let msg_v = h.new_str(*msg);
1395 let pair = h.new_array(vec![name_v, msg_v]);
1396 let key = crate::host::map_key(h, &key_val);
1397 entries.insert(key, (key_val, pair));
1398 }
1399 h.alloc(JsObj::Map {
1400 entries,
1401 weak: false,
1402 })
1403 })
1404}
1405
1406const PARSE_ARGS_SRC: &str = r#"(function (fail, evalMode) {
1417'use strict';
1418const ObjectHasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
1419const uncurry = (f) => (self, ...args) => Reflect.apply(f, self, args);
1420const StringPrototypeCharAt = uncurry(String.prototype.charAt);
1421const StringPrototypeIncludes = uncurry(String.prototype.includes);
1422const StringPrototypeIndexOf = uncurry(String.prototype.indexOf);
1423const StringPrototypeSlice = uncurry(String.prototype.slice);
1424const StringPrototypeStartsWith = uncurry(String.prototype.startsWith);
1425function ERR_INVALID_ARG_TYPE(name, expected, value) { fail('type', name, expected, value); }
1426function ERR_INVALID_ARG_VALUE(name, value, reason) { fail('value', name, value, reason); }
1427function ERR_PARSE_ARGS_INVALID_OPTION_VALUE(message) { fail('code', 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE', message); }
1428function ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(value) {
1429 fail('code', 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL', `Unexpected argument '${value}'. This command does not take positional arguments`);
1430}
1431function ERR_PARSE_ARGS_UNKNOWN_OPTION(option, allowPositionals) {
1432 const suggestDashDash = allowPositionals ? '. To specify a positional ' +
1433 "argument starting with a '-', place it at the end of the command after " +
1434 `'--', as in '-- ${JSON.stringify(option)}` : '';
1435 fail('code', 'ERR_PARSE_ARGS_UNKNOWN_OPTION', `Unknown option '${option}'${suggestDashDash}`);
1436}
1437
1438// internal/validators
1439function validateObject(value, name) {
1440 if (value === null || Array.isArray(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
1441 if (typeof value !== 'object') throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
1442}
1443function validateArray(value, name, minLength = 0) {
1444 if (!Array.isArray(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Array', value);
1445 if (value.length < minLength) throw new ERR_INVALID_ARG_VALUE(name, value, `must be longer than ${minLength}`);
1446}
1447function validateString(value, name) {
1448 if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
1449}
1450function validateBoolean(value, name) {
1451 if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value);
1452}
1453function validateStringArray(value, name) {
1454 validateArray(value, name);
1455 for (let i = 0; i < value.length; ++i) validateString(value[i], `${name}[${i}]`);
1456}
1457function validateBooleanArray(value, name) {
1458 validateArray(value, name);
1459 for (let i = 0; i < value.length; ++i) validateBoolean(value[i], `${name}[${i}]`);
1460}
1461function validateUnion(value, name, union) {
1462 if (!union.includes(value)) throw new ERR_INVALID_ARG_TYPE(name, `('${union.join('|')}')`, value);
1463}
1464
1465// internal/util/parse_args/utils
1466function objectGetOwn(obj, prop) {
1467 if (ObjectHasOwn(obj, prop))
1468 return obj[prop];
1469}
1470function optionsGetOwn(options, longOption, prop) {
1471 if (ObjectHasOwn(options, longOption))
1472 return objectGetOwn(options[longOption], prop);
1473}
1474function isOptionValue(value) {
1475 if (value == null) return false;
1476 return true; // greedy!
1477}
1478function isOptionLikeValue(value) {
1479 if (value == null) return false;
1480 return value.length > 1 && StringPrototypeCharAt(value, 0) === '-';
1481}
1482function isLoneShortOption(arg) {
1483 return arg.length === 2 && StringPrototypeCharAt(arg, 0) === '-' && StringPrototypeCharAt(arg, 1) !== '-';
1484}
1485function isLoneLongOption(arg) {
1486 return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && !StringPrototypeIncludes(arg, '=', 3);
1487}
1488function isLongOptionAndValue(arg) {
1489 return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && StringPrototypeIncludes(arg, '=', 3);
1490}
1491function isShortOptionGroup(arg, options) {
1492 if (arg.length <= 2) return false;
1493 if (StringPrototypeCharAt(arg, 0) !== '-') return false;
1494 if (StringPrototypeCharAt(arg, 1) === '-') return false;
1495 const firstShort = StringPrototypeCharAt(arg, 1);
1496 const longOption = findLongOptionForShort(firstShort, options);
1497 return optionsGetOwn(options, longOption, 'type') !== 'string';
1498}
1499function isShortOptionAndValue(arg, options) {
1500 validateObject(options, 'options');
1501 if (arg.length <= 2) return false;
1502 if (StringPrototypeCharAt(arg, 0) !== '-') return false;
1503 if (StringPrototypeCharAt(arg, 1) === '-') return false;
1504 const shortOption = StringPrototypeCharAt(arg, 1);
1505 const longOption = findLongOptionForShort(shortOption, options);
1506 return optionsGetOwn(options, longOption, 'type') === 'string';
1507}
1508function findLongOptionForShort(shortOption, options) {
1509 validateObject(options, 'options');
1510 const longOptionEntry = Object.entries(options).find(
1511 ({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption,
1512 );
1513 return longOptionEntry?.[0] ?? shortOption;
1514}
1515function useDefaultValueOption(longOption, optionConfig, values) {
1516 return objectGetOwn(optionConfig, 'default') !== undefined &&
1517 values[longOption] === undefined;
1518}
1519
1520// internal/util/parse_args/parse_args
1521function getMainArgs() {
1522 if (evalMode) return process.argv.slice(1);
1523 return process.argv.slice(2);
1524}
1525function checkOptionLikeValue(token) {
1526 if (!token.inlineValue && isOptionLikeValue(token.value)) {
1527 const example = StringPrototypeStartsWith(token.rawName, '--') ?
1528 `'${token.rawName}=-XYZ'` :
1529 `'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`;
1530 const errorMessage = `Option '${token.rawName}' argument is ambiguous.
1531Did you forget to specify the option argument for '${token.rawName}'?
1532To specify an option argument starting with a dash use ${example}.`;
1533 throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage);
1534 }
1535}
1536function checkOptionUsage(config, token) {
1537 let tokenName = token.name;
1538 if (!ObjectHasOwn(config.options, tokenName)) {
1539 if (config.allowNegative && StringPrototypeStartsWith(tokenName, 'no-')) {
1540 tokenName = StringPrototypeSlice(tokenName, 3);
1541 if (!ObjectHasOwn(config.options, tokenName) || optionsGetOwn(config.options, tokenName, 'type') !== 'boolean') {
1542 throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(token.rawName, config.allowPositionals);
1543 }
1544 } else {
1545 throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(token.rawName, config.allowPositionals);
1546 }
1547 }
1548 const short = optionsGetOwn(config.options, tokenName, 'short');
1549 const shortAndLong = `${short ? `-${short}, ` : ''}--${tokenName}`;
1550 const type = optionsGetOwn(config.options, tokenName, 'type');
1551 if (type === 'string' && typeof token.value !== 'string') {
1552 throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} <value>' argument missing`);
1553 }
1554 if (type === 'boolean' && token.value != null) {
1555 throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`);
1556 }
1557}
1558function storeOption(token, options, values, allowNegative) {
1559 let longOption = token.name;
1560 let optionValue = token.value;
1561 if (longOption === '__proto__') {
1562 return;
1563 }
1564 if (allowNegative && StringPrototypeStartsWith(longOption, 'no-') && optionValue === undefined) {
1565 longOption = StringPrototypeSlice(longOption, 3);
1566 token.name = longOption;
1567 optionValue = false;
1568 }
1569 const newValue = optionValue ?? true;
1570 if (optionsGetOwn(options, longOption, 'multiple')) {
1571 if (values[longOption]) {
1572 values[longOption].push(newValue);
1573 } else {
1574 values[longOption] = [newValue];
1575 }
1576 } else {
1577 values[longOption] = newValue;
1578 }
1579}
1580function storeDefaultOption(longOption, optionValue, values) {
1581 if (longOption === '__proto__') {
1582 return;
1583 }
1584 values[longOption] = optionValue;
1585}
1586function argsToTokens(args, options) {
1587 const tokens = [];
1588 let index = -1;
1589 let groupCount = 0;
1590 const remainingArgs = args.slice();
1591 while (remainingArgs.length > 0) {
1592 const arg = remainingArgs.shift();
1593 const nextArg = remainingArgs[0];
1594 if (groupCount > 0)
1595 groupCount--;
1596 else
1597 index++;
1598 if (arg === '--') {
1599 tokens.push({ kind: 'option-terminator', index });
1600 tokens.push(...remainingArgs.map((arg) => {
1601 return { kind: 'positional', index: ++index, value: arg };
1602 }));
1603 break;
1604 }
1605 if (isLoneShortOption(arg)) {
1606 const shortOption = StringPrototypeCharAt(arg, 1);
1607 const longOption = findLongOptionForShort(shortOption, options);
1608 let value;
1609 let inlineValue;
1610 if (optionsGetOwn(options, longOption, 'type') === 'string' &&
1611 isOptionValue(nextArg)) {
1612 value = remainingArgs.shift();
1613 inlineValue = false;
1614 }
1615 tokens.push({ kind: 'option', name: longOption, rawName: arg, index, value, inlineValue });
1616 if (value != null) ++index;
1617 continue;
1618 }
1619 if (isShortOptionGroup(arg, options)) {
1620 const expanded = [];
1621 for (let index = 1; index < arg.length; index++) {
1622 const shortOption = StringPrototypeCharAt(arg, index);
1623 const longOption = findLongOptionForShort(shortOption, options);
1624 if (optionsGetOwn(options, longOption, 'type') !== 'string' ||
1625 index === arg.length - 1) {
1626 expanded.push(`-${shortOption}`);
1627 } else {
1628 expanded.push(`-${StringPrototypeSlice(arg, index)}`);
1629 break;
1630 }
1631 }
1632 remainingArgs.unshift(...expanded);
1633 groupCount = expanded.length;
1634 continue;
1635 }
1636 if (isShortOptionAndValue(arg, options)) {
1637 const shortOption = StringPrototypeCharAt(arg, 1);
1638 const longOption = findLongOptionForShort(shortOption, options);
1639 const value = StringPrototypeSlice(arg, 2);
1640 tokens.push({ kind: 'option', name: longOption, rawName: `-${shortOption}`, index, value, inlineValue: true });
1641 continue;
1642 }
1643 if (isLoneLongOption(arg)) {
1644 const longOption = StringPrototypeSlice(arg, 2);
1645 let value;
1646 let inlineValue;
1647 if (optionsGetOwn(options, longOption, 'type') === 'string' &&
1648 isOptionValue(nextArg)) {
1649 value = remainingArgs.shift();
1650 inlineValue = false;
1651 }
1652 tokens.push({ kind: 'option', name: longOption, rawName: arg, index, value, inlineValue });
1653 if (value != null) ++index;
1654 continue;
1655 }
1656 if (isLongOptionAndValue(arg)) {
1657 const equalIndex = StringPrototypeIndexOf(arg, '=');
1658 const longOption = StringPrototypeSlice(arg, 2, equalIndex);
1659 const value = StringPrototypeSlice(arg, equalIndex + 1);
1660 tokens.push({ kind: 'option', name: longOption, rawName: `--${longOption}`, index, value, inlineValue: true });
1661 continue;
1662 }
1663 tokens.push({ kind: 'positional', index, value: arg });
1664 }
1665 return tokens;
1666}
1667const parseArgs = (config = {}) => {
1668 const args = objectGetOwn(config, 'args') ?? getMainArgs();
1669 const strict = objectGetOwn(config, 'strict') ?? true;
1670 const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict;
1671 const returnTokens = objectGetOwn(config, 'tokens') ?? false;
1672 const allowNegative = objectGetOwn(config, 'allowNegative') ?? false;
1673 const options = objectGetOwn(config, 'options') ?? { __proto__: null };
1674 const parseConfig = { args, strict, options, allowPositionals, allowNegative };
1675 validateArray(args, 'args');
1676 validateBoolean(strict, 'strict');
1677 validateBoolean(allowPositionals, 'allowPositionals');
1678 validateBoolean(returnTokens, 'tokens');
1679 validateBoolean(allowNegative, 'allowNegative');
1680 validateObject(options, 'options');
1681 Object.entries(options).forEach(
1682 ({ 0: longOption, 1: optionConfig }) => {
1683 validateObject(optionConfig, `options.${longOption}`);
1684 const optionType = objectGetOwn(optionConfig, 'type');
1685 validateUnion(optionType, `options.${longOption}.type`, ['string', 'boolean']);
1686 if (ObjectHasOwn(optionConfig, 'short')) {
1687 const shortOption = optionConfig.short;
1688 validateString(shortOption, `options.${longOption}.short`);
1689 if (shortOption.length !== 1) {
1690 throw new ERR_INVALID_ARG_VALUE(
1691 `options.${longOption}.short`,
1692 shortOption,
1693 'must be a single character',
1694 );
1695 }
1696 }
1697 const multipleOption = objectGetOwn(optionConfig, 'multiple');
1698 if (ObjectHasOwn(optionConfig, 'multiple')) {
1699 validateBoolean(multipleOption, `options.${longOption}.multiple`);
1700 }
1701 const defaultValue = objectGetOwn(optionConfig, 'default');
1702 if (defaultValue !== undefined) {
1703 let validator;
1704 switch (optionType) {
1705 case 'string':
1706 validator = multipleOption ? validateStringArray : validateString;
1707 break;
1708 case 'boolean':
1709 validator = multipleOption ? validateBooleanArray : validateBoolean;
1710 break;
1711 }
1712 validator(defaultValue, `options.${longOption}.default`);
1713 }
1714 },
1715 );
1716 const tokens = argsToTokens(args, options);
1717 const result = {
1718 values: { __proto__: null },
1719 positionals: [],
1720 };
1721 if (returnTokens) {
1722 result.tokens = tokens;
1723 }
1724 tokens.forEach((token) => {
1725 if (token.kind === 'option') {
1726 if (strict) {
1727 checkOptionUsage(parseConfig, token);
1728 checkOptionLikeValue(token);
1729 }
1730 storeOption(token, options, result.values, parseConfig.allowNegative);
1731 } else if (token.kind === 'positional') {
1732 if (!allowPositionals) {
1733 throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value);
1734 }
1735 result.positionals.push(token.value);
1736 }
1737 });
1738 Object.entries(options).forEach(({ 0: longOption, 1: optionConfig }) => {
1739 const mustSetDefault = useDefaultValueOption(longOption, optionConfig, result.values);
1740 if (mustSetDefault) {
1741 storeDefaultOption(longOption, objectGetOwn(optionConfig, 'default'), result.values);
1742 }
1743 });
1744 return result;
1745};
1746return parseArgs;
1747})"#;
1748
1749fn parse_args(args: &[Value]) -> Result<Value, String> {
1751 thread_local! {
1752 static PARSER: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
1753 }
1754 let parser = match PARSER.with(|p| p.borrow().clone()) {
1755 Some(p) => p,
1756 None => {
1757 let factory = run_completion(PARSE_ARGS_SRC)?;
1758 let fail = with_host(|h| h.alloc(JsObj::Builtin("util.@@nodeError".into())));
1759 let eval_mode = Value::Bool(super::process::eval_entry());
1760 let made = crate::host::invoke(&factory, vec![fail, eval_mode], None)?;
1761 PARSER.with(|p| *p.borrow_mut() = Some(made.clone()));
1762 made
1763 }
1764 };
1765 let config = args.first().cloned().unwrap_or(Value::Undef);
1766 crate::host::invoke(&parser, vec![config], None)
1767}
1768
1769fn node_error(args: &[Value]) -> Result<Value, String> {
1778 let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Undef);
1779 let kind_arg = super::arg_str(args, 0);
1780 let (kind, class) = kind_arg.split_once(':').unwrap_or((kind_arg.as_str(), ""));
1781 let class_or = |default: &str| {
1782 if class.is_empty() {
1783 default.to_string()
1784 } else {
1785 class.to_string()
1786 }
1787 };
1788 let name = super::arg_str(args, 1);
1789 let noun = if name.contains('.') {
1792 "property"
1793 } else {
1794 "argument"
1795 };
1796 Err(match kind {
1797 "type" => {
1798 let spec = super::arg_str(args, 2);
1799 let expected = match spec.as_str() {
1800 "Array" => "an instance of Array".to_string(),
1801 "Object" => "of type object".to_string(),
1802 s if s.starts_with('(') || s.contains(' ') => s.to_string(),
1804 s => format!("of type {s}"),
1805 };
1806 crate::host::coded_error(
1807 "TypeError",
1808 "ERR_INVALID_ARG_TYPE",
1809 &format!(
1810 "The \"{name}\" {noun} must be {expected}. Received {}",
1811 super::received_desc(&arg(3))
1812 ),
1813 )
1814 }
1815 "value" => {
1816 let mut shown = crate::host::inspect_js(&arg(2))?;
1817 if shown.chars().count() > 128 {
1818 shown = format!("{}...", shown.chars().take(128).collect::<String>());
1819 }
1820 let reason = match arg(3) {
1821 Value::Undef => "is invalid".to_string(),
1822 v => with_host(|h| h.str_of(&v)),
1823 };
1824 crate::host::coded_error(
1825 &class_or("TypeError"),
1826 "ERR_INVALID_ARG_VALUE",
1827 &format!("The {noun} '{name}' {reason}. Received {shown}"),
1828 )
1829 }
1830 "range" => {
1832 let n = with_host(|h| h.to_number(&arg(3)));
1833 super::out_of_range(&name, &super::arg_str(args, 2), n)
1834 }
1835 "error" => crate::host::coded_error(&class_or("Error"), &name, &super::arg_str(args, 2)),
1837 _ => crate::host::coded_error(&class_or("TypeError"), &name, &super::arg_str(args, 2)),
1838 })
1839}
1840
1841fn env_trim(s: &str) -> &str {
1851 s.trim_matches(|c: char| c == ' ' || c == '\t' || c == '\n')
1852}
1853
1854fn parse_env(input: &str) -> Value {
1856 let lines = input.replace('\r', "");
1857 let mut pairs: IndexMap<String, String> = IndexMap::new();
1858 let mut content: &str = env_trim(&lines);
1859
1860 while !content.is_empty() {
1861 let first = content.as_bytes()[0];
1862 if first == b'\n' || first == b'#' {
1864 match content.find('\n') {
1865 Some(nl) => content = &content[nl + 1..],
1866 None => content = "",
1867 }
1868 continue;
1869 }
1870 let Some(eq_or_nl) = content.find(['=', '\n']) else {
1872 break;
1873 };
1874 if content.as_bytes()[eq_or_nl] == b'\n' {
1875 content = env_trim(&content[eq_or_nl + 1..]);
1876 continue;
1877 }
1878 let mut key = env_trim(&content[..eq_or_nl]);
1880 content = &content[eq_or_nl + 1..];
1881 if content.is_empty() || content.as_bytes()[0] == b'\n' {
1883 pairs.insert(key.to_string(), String::new());
1884 continue;
1885 }
1886 content = env_trim(content);
1887 if key.is_empty() {
1889 continue;
1890 }
1891 if let Some(rest) = key.strip_prefix("export ") {
1893 key = env_trim(rest);
1894 }
1895 if content.is_empty() {
1896 pairs.insert(key.to_string(), String::new());
1897 break;
1898 }
1899 let vfirst = content.as_bytes()[0];
1900 if vfirst == b'"' {
1902 if let Some(rel) = content[1..].find('"') {
1903 let closing = rel + 1;
1904 let value = content[1..closing].replace("\\n", "\n");
1905 pairs.insert(key.to_string(), value);
1906 match content[closing + 1..].find('\n') {
1907 Some(nl) => content = &content[closing + 1 + nl + 1..],
1908 None => content = "",
1909 }
1910 continue;
1911 }
1912 }
1914 if vfirst == b'\'' || vfirst == b'"' || vfirst == b'`' {
1916 match content[1..].find(vfirst as char) {
1917 None => match content.find('\n') {
1918 Some(nl) => {
1919 pairs.insert(key.to_string(), content[..nl].to_string());
1920 content = &content[nl + 1..];
1921 }
1922 None => {
1923 pairs.insert(key.to_string(), content.to_string());
1924 break;
1925 }
1926 },
1927 Some(rel) => {
1928 let closing = rel + 1;
1929 pairs.insert(key.to_string(), content[1..closing].to_string());
1930 match content[closing + 1..].find('\n') {
1931 Some(nl) => content = &content[closing + 1 + nl + 1..],
1932 None => content = "",
1933 }
1934 continue;
1935 }
1936 }
1937 } else {
1938 let (raw, next) = match content.find('\n') {
1940 Some(nl) => (&content[..nl], &content[nl + 1..]),
1941 None => (content, ""),
1942 };
1943 let value = match raw.find('#') {
1944 Some(h) => &raw[..h],
1945 None => raw,
1946 };
1947 pairs.insert(key.to_string(), env_trim(value).to_string());
1948 content = next;
1949 }
1950 content = env_trim(content);
1951 }
1952
1953 pairs.sort_keys();
1954 with_host(|h| {
1955 let mut m = IndexMap::new();
1956 for (k, v) in pairs {
1957 let val = h.new_str(v);
1958 m.insert(k, val);
1959 }
1960 h.new_object(m)
1961 })
1962}
1963
1964fn is_token_char(c: char) -> bool {
1973 c.is_ascii_alphanumeric()
1974 || matches!(
1975 c,
1976 '!' | '#'
1977 | '$'
1978 | '%'
1979 | '&'
1980 | '\''
1981 | '*'
1982 | '+'
1983 | '-'
1984 | '.'
1985 | '^'
1986 | '_'
1987 | '`'
1988 | '|'
1989 | '~'
1990 )
1991}
1992
1993fn is_quoted_string_char(c: char) -> bool {
1996 c == '\t' || ('\u{20}'..='\u{7e}').contains(&c) || ('\u{80}'..='\u{ff}').contains(&c)
1997}
1998
1999fn is_http_ws(c: char) -> bool {
2001 matches!(c, '\r' | '\n' | '\t' | ' ')
2002}
2003
2004fn ascii_lower(s: &str) -> String {
2007 s.to_ascii_lowercase()
2008}
2009
2010fn mime_syntax_err(part: &str, s: &str, index: Option<usize>) -> String {
2013 match index {
2014 Some(i) => format!(
2015 "TypeError [ERR_INVALID_MIME_SYNTAX]: The MIME syntax for a {part} in \"{s}\" is invalid at {i}"
2016 ),
2017 None => format!(
2018 "TypeError [ERR_INVALID_MIME_SYNTAX]: The MIME syntax for a {part} in \"{s}\" is invalid"
2019 ),
2020 }
2021}
2022
2023fn parse_type_and_subtype(s: &str) -> Result<(String, String, String), String> {
2026 let chars: Vec<char> = s.chars().collect();
2027 let n = chars.len();
2028 let mut pos = 0;
2030 while pos < n && is_http_ws(chars[pos]) {
2031 pos += 1;
2032 }
2033 let type_end = (pos..n).find(|&i| chars[i] == '/');
2035 let trimmed_type: String = match type_end {
2036 Some(e) => chars[pos..e].iter().collect(),
2037 None => chars[pos..].iter().collect(),
2038 };
2039 let type_invalid = trimmed_type.chars().position(|c| !is_token_char(c));
2040 if trimmed_type.is_empty() || type_invalid.is_some() || type_end.is_none() {
2041 return Err(mime_syntax_err("type", s, type_invalid));
2042 }
2043 let type_end = type_end.unwrap();
2044 pos = type_end + 1;
2045 let mime_type = ascii_lower(&trimmed_type);
2046 let sub_end = (pos..n).find(|&i| chars[i] == ';');
2048 let raw_subtype: &[char] = match sub_end {
2049 Some(e) => &chars[pos..e],
2050 None => &chars[pos..],
2051 };
2052 let mut new_pos = pos + raw_subtype.len();
2053 if sub_end.is_some() {
2054 new_pos += 1;
2055 }
2056 let mut end = raw_subtype.len();
2058 while end > 0 && is_http_ws(raw_subtype[end - 1]) {
2059 end -= 1;
2060 }
2061 let trimmed_subtype: String = raw_subtype[..end].iter().collect();
2062 let sub_invalid = trimmed_subtype.chars().position(|c| !is_token_char(c));
2063 if trimmed_subtype.is_empty() || sub_invalid.is_some() {
2064 return Err(mime_syntax_err("subtype", s, sub_invalid));
2065 }
2066 let subtype = ascii_lower(&trimmed_subtype);
2067 let params: String = chars[new_pos.min(n)..].iter().collect();
2068 Ok((mime_type, subtype, params))
2069}
2070
2071fn scan_quoted(chars: &[char], start: usize) -> (usize, bool, bool) {
2074 let n = chars.len();
2075 let mut i = start;
2076 let mut lone_backslash = false;
2077 let mut closing_quote = false;
2078 while i < n {
2079 match chars[i] {
2080 '\\' => {
2081 if i + 1 >= n {
2082 lone_backslash = true;
2083 i += 1;
2084 break;
2085 }
2086 i += 2;
2087 }
2088 '"' => {
2089 closing_quote = true;
2090 i += 1;
2091 break;
2092 }
2093 _ => i += 1,
2094 }
2095 }
2096 (i - start, lone_backslash, closing_quote)
2097}
2098
2099fn remove_backslashes(s: &[char]) -> String {
2101 let n = s.len();
2102 if n == 0 {
2103 return String::new();
2104 }
2105 let mut ret = String::new();
2106 let mut i = 0usize;
2107 while i < n - 1 {
2108 if s[i] == '\\' {
2109 i += 1;
2110 ret.push(s[i]);
2111 } else {
2112 ret.push(s[i]);
2113 }
2114 i += 1;
2115 }
2116 if i == n - 1 {
2117 ret.push(s[i]);
2118 }
2119 ret
2120}
2121
2122fn parse_mime_params(s: &str) -> Vec<(String, String)> {
2124 let chars: Vec<char> = s.chars().collect();
2125 let n = chars.len();
2126 let mut end_of_source = n;
2128 while end_of_source > 0 && is_http_ws(chars[end_of_source - 1]) {
2129 end_of_source -= 1;
2130 }
2131 let mut out: Vec<(String, String)> = Vec::new();
2132 let mut position = 0usize;
2133 while position < end_of_source {
2134 while position < n && is_http_ws(chars[position]) {
2136 position += 1;
2137 }
2138 let mut after = position;
2140 while after < n && chars[after] != ';' && chars[after] != '=' {
2141 after += 1;
2142 }
2143 let name = ascii_lower(&chars[position..after].iter().collect::<String>());
2144 position = after;
2145 if position < end_of_source {
2146 let ch = chars[position];
2147 position += 1;
2148 if ch == ';' {
2150 continue;
2151 }
2152 }
2153 if position >= end_of_source {
2154 break;
2155 }
2156 let value = if chars[position] == '"' {
2157 position += 1;
2159 let (matched_len, lone_backslash, closing_quote) = scan_quoted(&chars, position);
2160 let matched = &chars[position..position + matched_len];
2161 position += matched_len;
2162 let inside: &[char] = if lone_backslash || closing_quote {
2163 &matched[..matched.len().saturating_sub(1)]
2164 } else {
2165 matched
2166 };
2167 let mut v = remove_backslashes(inside);
2168 if lone_backslash {
2169 v.push('\\');
2170 }
2171 v
2172 } else {
2173 let value_end = (position..n).find(|&i| chars[i] == ';').unwrap_or(n);
2175 let raw = &chars[position..value_end];
2176 position += raw.len();
2177 let mut end = raw.len();
2178 while end > 0 && is_http_ws(raw[end - 1]) {
2179 end -= 1;
2180 }
2181 let trimmed: String = raw[..end].iter().collect();
2182 if trimmed.is_empty() {
2183 continue;
2186 }
2187 trimmed
2188 };
2189 let name_ok = !name.is_empty() && name.chars().all(is_token_char);
2191 let value_ok = value.chars().all(is_quoted_string_char);
2192 if name_ok && value_ok && !out.iter().any(|(k, _)| *k == name) {
2193 out.push((name, value));
2194 }
2195 position += 1;
2196 }
2197 out
2198}
2199
2200fn encode_param_value(value: &str) -> String {
2203 if value.is_empty() {
2204 return "\"\"".to_string();
2205 }
2206 if value.chars().all(is_token_char) {
2207 return value.to_string();
2208 }
2209 let mut escaped = String::with_capacity(value.len() + 2);
2210 for c in value.chars() {
2211 if c == '"' || c == '\\' {
2212 escaped.push('\\');
2213 }
2214 escaped.push(c);
2215 }
2216 format!("\"{escaped}\"")
2217}
2218
2219fn serialize_mime_params(pairs: &[(String, String)]) -> String {
2221 let mut ret = String::new();
2222 for (k, v) in pairs {
2223 if !ret.is_empty() {
2224 ret.push(';');
2225 }
2226 ret.push_str(k);
2227 ret.push('=');
2228 ret.push_str(&encode_param_value(v));
2229 }
2230 ret
2231}
2232
2233pub const MIME_PARAMS_METHODS: &[&str] = &[
2236 "get",
2237 "set",
2238 "has",
2239 "delete",
2240 "entries",
2241 "keys",
2242 "values",
2243 "toString",
2244 "toJSON",
2245 "@@iterator",
2246];
2247
2248pub const MIME_TYPE_METHODS: &[&str] = &["toString", "toJSON"];
2250
2251fn make_mime_params(pairs: &[(String, String)]) -> Value {
2253 with_host(|h| {
2254 let items: Vec<Value> = pairs
2255 .iter()
2256 .map(|(k, v)| {
2257 let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
2258 h.new_array(kv)
2259 })
2260 .collect();
2261 let arr = h.new_array(items);
2262 let mut m = IndexMap::new();
2263 m.insert("@@native".into(), h.new_str("MIMEParams"));
2264 m.insert("@@pairs".into(), arr);
2265 h.new_object(m)
2266 })
2267}
2268
2269fn mime_pairs_of(recv: &Value) -> Vec<(String, String)> {
2271 with_host(|h| {
2272 let items: Vec<Value> = match h.get(recv) {
2273 Some(JsObj::Object(p)) => match p.get("@@pairs").and_then(|a| h.get(a)) {
2274 Some(JsObj::Array(items)) => items.clone(),
2275 _ => Vec::new(),
2276 },
2277 _ => Vec::new(),
2278 };
2279 items
2280 .iter()
2281 .map(|it| match h.get(it) {
2282 Some(JsObj::Array(kv)) => {
2283 let kv = kv.clone();
2284 let k = kv.first().map(|x| h.str_of(x)).unwrap_or_default();
2285 let v = kv.get(1).map(|x| h.str_of(x)).unwrap_or_default();
2286 (k, v)
2287 }
2288 _ => (h.str_of(it), String::new()),
2289 })
2290 .collect()
2291 })
2292}
2293
2294fn set_mime_pairs(recv: &Value, pairs: &[(String, String)]) {
2296 with_host(|h| {
2297 let items: Vec<Value> = pairs
2298 .iter()
2299 .map(|(k, v)| {
2300 let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
2301 h.new_array(kv)
2302 })
2303 .collect();
2304 let arr = h.new_array(items);
2305 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2306 p.insert("@@pairs".into(), arr);
2307 }
2308 });
2309}
2310
2311pub fn construct_mime_params(_args: &[Value]) -> Result<Value, String> {
2314 Ok(make_mime_params(&[]))
2315}
2316
2317pub fn mime_params_instance_call(
2319 recv: &Value,
2320 method: &str,
2321 args: &[Value],
2322) -> Result<Value, String> {
2323 match method {
2324 "get" => {
2325 let name = super::arg_str(args, 0);
2326 match mime_pairs_of(recv).into_iter().find(|(k, _)| *k == name) {
2327 Some((_, v)) => Ok(with_host(|h| h.new_str(v))),
2328 None => Ok(with_host(|h| h.null())),
2329 }
2330 }
2331 "has" => {
2332 let name = super::arg_str(args, 0);
2333 Ok(Value::Bool(
2334 mime_pairs_of(recv).iter().any(|(k, _)| *k == name),
2335 ))
2336 }
2337 "set" => {
2338 let name = super::arg_str(args, 0);
2339 let value = super::arg_str(args, 1);
2340 if let Some(i) = name.chars().position(|c| !is_token_char(c)) {
2341 return Err(mime_syntax_err("parameter name", &name, Some(i)));
2342 }
2343 if name.is_empty() {
2344 return Err(mime_syntax_err("parameter name", &name, None));
2345 }
2346 if let Some(i) = value.chars().position(|c| !is_quoted_string_char(c)) {
2347 return Err(mime_syntax_err("parameter value", &value, Some(i)));
2348 }
2349 let mut pairs = mime_pairs_of(recv);
2350 match pairs.iter_mut().find(|(k, _)| *k == name) {
2351 Some(slot) => slot.1 = value,
2352 None => pairs.push((name, value)),
2353 }
2354 set_mime_pairs(recv, &pairs);
2355 Ok(Value::Undef)
2356 }
2357 "delete" => {
2358 let name = super::arg_str(args, 0);
2359 let mut pairs = mime_pairs_of(recv);
2360 pairs.retain(|(k, _)| *k != name);
2361 set_mime_pairs(recv, &pairs);
2362 Ok(Value::Undef)
2363 }
2364 "keys" => {
2365 let pairs = mime_pairs_of(recv);
2366 Ok(with_host(|h| {
2367 let items = pairs.into_iter().map(|(k, _)| h.new_str(k)).collect();
2368 h.alloc(JsObj::Iter {
2369 items,
2370 idx: 0,
2371 array: None,
2372 brand: Some("Generator"),
2373 })
2374 }))
2375 }
2376 "values" => {
2377 let pairs = mime_pairs_of(recv);
2378 Ok(with_host(|h| {
2379 let items = pairs.into_iter().map(|(_, v)| h.new_str(v)).collect();
2380 h.alloc(JsObj::Iter {
2381 items,
2382 idx: 0,
2383 array: None,
2384 brand: Some("Generator"),
2385 })
2386 }))
2387 }
2388 "entries" | "@@iterator" => {
2389 let pairs = mime_pairs_of(recv);
2390 Ok(with_host(|h| {
2391 let items = pairs
2392 .into_iter()
2393 .map(|(k, v)| {
2394 let kv = vec![h.new_str(k), h.new_str(v)];
2395 h.new_array(kv)
2396 })
2397 .collect();
2398 h.alloc(JsObj::Iter {
2399 items,
2400 idx: 0,
2401 array: None,
2402 brand: Some("Generator"),
2403 })
2404 }))
2405 }
2406 "toString" | "toJSON" => {
2407 let s = serialize_mime_params(&mime_pairs_of(recv));
2408 Ok(with_host(|h| h.new_str(s)))
2409 }
2410 _ => Err(crate::host::type_error(&format!(
2411 "mimeParams.{method} is not a function"
2412 ))),
2413 }
2414}
2415
2416pub fn construct_mime_type(args: &[Value]) -> Result<Value, String> {
2418 let input = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
2421 let (mime_type, subtype, params_str) = parse_type_and_subtype(&input)?;
2422 let essence = format!("{mime_type}/{subtype}");
2423 let params = make_mime_params(&parse_mime_params(¶ms_str));
2425 Ok(with_host(|h| {
2426 let mut m = IndexMap::new();
2427 m.insert("@@native".into(), h.new_str("MIMEType"));
2428 m.insert("type".into(), h.new_str(mime_type));
2429 m.insert("subtype".into(), h.new_str(subtype));
2430 m.insert("essence".into(), h.new_str(essence));
2431 m.insert("params".into(), params);
2432 h.new_object(m)
2433 }))
2434}
2435
2436pub fn mime_type_instance_call(
2440 recv: &Value,
2441 method: &str,
2442 _args: &[Value],
2443) -> Result<Value, String> {
2444 match method {
2445 "toString" | "toJSON" => {
2446 let (essence, params) = with_host(|h| match h.get(recv) {
2448 Some(JsObj::Object(p)) => (
2449 p.get("essence").map(|x| h.str_of(x)).unwrap_or_default(),
2450 p.get("params").cloned().unwrap_or(Value::Undef),
2451 ),
2452 _ => (String::new(), Value::Undef),
2453 });
2454 let param_str = serialize_mime_params(&mime_pairs_of(¶ms));
2455 let out = if param_str.is_empty() {
2456 essence
2457 } else {
2458 format!("{essence};{param_str}")
2459 };
2460 Ok(with_host(|h| h.new_str(out)))
2461 }
2462 _ => Err(crate::host::type_error(&format!(
2463 "mimeType.{method} is not a function"
2464 ))),
2465 }
2466}