1use super::*;
4use crate::os_lib::ecma::regex::{self, RegExpData};
7
8pub(crate) fn text_encode(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
10 let s = match arg(a, 0) {
12 Value::Undefined => String::new(),
13 v => v.to_js_string(),
14 };
15 Ok(make_uint8array(it, s.as_bytes().to_vec()))
16}
17pub(crate) fn text_encode_into(_it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
24 let source = arg(a, 0).to_js_string();
25 let dest = arg(a, 1);
26 let Value::Object(dest_obj) = &dest else {
27 return Ok(Value::Undefined);
28 };
29 let capacity = match &dest_obj.borrow().kind {
30 ObjKind::Array(items) => items.len(),
31 ObjKind::Bytes(st) => st.len,
32 _ => 0,
33 };
34 let mut read_units = 0usize;
35 let mut written_bytes: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
36 for c in source.chars() {
37 let mut buf = [0u8; 4];
38 let bytes = c.encode_utf8(&mut buf).as_bytes();
39 if written_bytes.len() + bytes.len() > capacity {
40 break;
41 }
42 written_bytes.extend_from_slice(bytes);
43 read_units += c.len_utf16();
44 }
45 if let ObjKind::Bytes(st) = &dest_obj.borrow().kind {
46 for (i, b) in written_bytes.iter().enumerate() {
47 st.set(i, *b as f64);
48 }
49 }
50 if let ObjKind::Array(items) = &mut dest_obj.borrow_mut().kind {
51 for (i, b) in written_bytes.iter().enumerate() {
52 if let Some(slot) = items.get_mut(i) {
53 *slot = Value::Number(*b as f64);
54 }
55 }
56 }
57 let result = Obj::plain();
58 {
59 let mut b = result.borrow_mut();
60 b.props.insert("read".into(), Value::Number(read_units as f64));
61 b.props
62 .insert("written".into(), Value::Number(written_bytes.len() as f64));
63 }
64 Ok(Value::Object(result))
65}
66pub(crate) fn normalize_text_encoding_label(label: &str) -> Option<&'static str> {
76 let l = label.trim_matches(|c| matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')).to_ascii_lowercase();
77 let i = ENCODING_LABELS.binary_search_by(|(k, _)| (*k).cmp(l.as_str())).ok()?;
78 let name = ENCODING_LABELS[i].1;
79 if name == "replacement" {
80 None
81 } else {
82 Some(name)
83 }
84}
85static ENCODING_LABELS: &[(&str, &str)] = &[
87 ("866", "ibm866"),
88 ("ansi_x3.4-1968", "windows-1252"),
89 ("arabic", "iso-8859-6"),
90 ("ascii", "windows-1252"),
91 ("asmo-708", "iso-8859-6"),
92 ("big5", "big5"),
93 ("big5-hkscs", "big5"),
94 ("chinese", "gbk"),
95 ("cn-big5", "big5"),
96 ("cp1250", "windows-1250"),
97 ("cp1251", "windows-1251"),
98 ("cp1252", "windows-1252"),
99 ("cp1253", "windows-1253"),
100 ("cp1254", "windows-1254"),
101 ("cp1255", "windows-1255"),
102 ("cp1256", "windows-1256"),
103 ("cp1257", "windows-1257"),
104 ("cp1258", "windows-1258"),
105 ("cp819", "windows-1252"),
106 ("cp866", "ibm866"),
107 ("csbig5", "big5"),
108 ("cseuckr", "euc-kr"),
109 ("cseucpkdfmtjapanese", "euc-jp"),
110 ("csgb2312", "gbk"),
111 ("csibm866", "ibm866"),
112 ("csiso2022jp", "iso-2022-jp"),
113 ("csiso2022kr", "replacement"),
114 ("csiso58gb231280", "gbk"),
115 ("csiso88596e", "iso-8859-6"),
116 ("csiso88596i", "iso-8859-6"),
117 ("csiso88598e", "iso-8859-8"),
118 ("csiso88598i", "iso-8859-8-i"),
119 ("csisolatin1", "windows-1252"),
120 ("csisolatin2", "iso-8859-2"),
121 ("csisolatin3", "iso-8859-3"),
122 ("csisolatin4", "iso-8859-4"),
123 ("csisolatin5", "windows-1254"),
124 ("csisolatin6", "iso-8859-10"),
125 ("csisolatin9", "iso-8859-15"),
126 ("csisolatinarabic", "iso-8859-6"),
127 ("csisolatincyrillic", "iso-8859-5"),
128 ("csisolatingreek", "iso-8859-7"),
129 ("csisolatinhebrew", "iso-8859-8"),
130 ("cskoi8r", "koi8-r"),
131 ("csksc56011987", "euc-kr"),
132 ("csmacintosh", "macintosh"),
133 ("csshiftjis", "shift_jis"),
134 ("csunicode", "utf-16le"),
135 ("cyrillic", "iso-8859-5"),
136 ("dos-874", "windows-874"),
137 ("ecma-114", "iso-8859-6"),
138 ("ecma-118", "iso-8859-7"),
139 ("elot_928", "iso-8859-7"),
140 ("euc-jp", "euc-jp"),
141 ("euc-kr", "euc-kr"),
142 ("gb18030", "gb18030"),
143 ("gb2312", "gbk"),
144 ("gb_2312", "gbk"),
145 ("gb_2312-80", "gbk"),
146 ("gbk", "gbk"),
147 ("greek", "iso-8859-7"),
148 ("greek8", "iso-8859-7"),
149 ("hebrew", "iso-8859-8"),
150 ("hz-gb-2312", "replacement"),
151 ("ibm819", "windows-1252"),
152 ("ibm866", "ibm866"),
153 ("iso-10646-ucs-2", "utf-16le"),
154 ("iso-2022-cn", "replacement"),
155 ("iso-2022-cn-ext", "replacement"),
156 ("iso-2022-jp", "iso-2022-jp"),
157 ("iso-2022-kr", "replacement"),
158 ("iso-8859-1", "windows-1252"),
159 ("iso-8859-10", "iso-8859-10"),
160 ("iso-8859-11", "windows-874"),
161 ("iso-8859-13", "iso-8859-13"),
162 ("iso-8859-14", "iso-8859-14"),
163 ("iso-8859-15", "iso-8859-15"),
164 ("iso-8859-16", "iso-8859-16"),
165 ("iso-8859-2", "iso-8859-2"),
166 ("iso-8859-3", "iso-8859-3"),
167 ("iso-8859-4", "iso-8859-4"),
168 ("iso-8859-5", "iso-8859-5"),
169 ("iso-8859-6", "iso-8859-6"),
170 ("iso-8859-6-e", "iso-8859-6"),
171 ("iso-8859-6-i", "iso-8859-6"),
172 ("iso-8859-7", "iso-8859-7"),
173 ("iso-8859-8", "iso-8859-8"),
174 ("iso-8859-8-e", "iso-8859-8"),
175 ("iso-8859-8-i", "iso-8859-8-i"),
176 ("iso-8859-9", "windows-1254"),
177 ("iso-ir-100", "windows-1252"),
178 ("iso-ir-101", "iso-8859-2"),
179 ("iso-ir-109", "iso-8859-3"),
180 ("iso-ir-110", "iso-8859-4"),
181 ("iso-ir-126", "iso-8859-7"),
182 ("iso-ir-127", "iso-8859-6"),
183 ("iso-ir-138", "iso-8859-8"),
184 ("iso-ir-144", "iso-8859-5"),
185 ("iso-ir-148", "windows-1254"),
186 ("iso-ir-149", "euc-kr"),
187 ("iso-ir-157", "iso-8859-10"),
188 ("iso-ir-58", "gbk"),
189 ("iso8859-1", "windows-1252"),
190 ("iso8859-10", "iso-8859-10"),
191 ("iso8859-11", "windows-874"),
192 ("iso8859-13", "iso-8859-13"),
193 ("iso8859-14", "iso-8859-14"),
194 ("iso8859-15", "iso-8859-15"),
195 ("iso8859-2", "iso-8859-2"),
196 ("iso8859-3", "iso-8859-3"),
197 ("iso8859-4", "iso-8859-4"),
198 ("iso8859-5", "iso-8859-5"),
199 ("iso8859-6", "iso-8859-6"),
200 ("iso8859-7", "iso-8859-7"),
201 ("iso8859-8", "iso-8859-8"),
202 ("iso8859-9", "windows-1254"),
203 ("iso88591", "windows-1252"),
204 ("iso885910", "iso-8859-10"),
205 ("iso885911", "windows-874"),
206 ("iso885913", "iso-8859-13"),
207 ("iso885914", "iso-8859-14"),
208 ("iso885915", "iso-8859-15"),
209 ("iso88592", "iso-8859-2"),
210 ("iso88593", "iso-8859-3"),
211 ("iso88594", "iso-8859-4"),
212 ("iso88595", "iso-8859-5"),
213 ("iso88596", "iso-8859-6"),
214 ("iso88597", "iso-8859-7"),
215 ("iso88598", "iso-8859-8"),
216 ("iso88599", "windows-1254"),
217 ("iso_8859-1", "windows-1252"),
218 ("iso_8859-15", "iso-8859-15"),
219 ("iso_8859-1:1987", "windows-1252"),
220 ("iso_8859-2", "iso-8859-2"),
221 ("iso_8859-2:1987", "iso-8859-2"),
222 ("iso_8859-3", "iso-8859-3"),
223 ("iso_8859-3:1988", "iso-8859-3"),
224 ("iso_8859-4", "iso-8859-4"),
225 ("iso_8859-4:1988", "iso-8859-4"),
226 ("iso_8859-5", "iso-8859-5"),
227 ("iso_8859-5:1988", "iso-8859-5"),
228 ("iso_8859-6", "iso-8859-6"),
229 ("iso_8859-6:1987", "iso-8859-6"),
230 ("iso_8859-7", "iso-8859-7"),
231 ("iso_8859-7:1987", "iso-8859-7"),
232 ("iso_8859-8", "iso-8859-8"),
233 ("iso_8859-8:1988", "iso-8859-8"),
234 ("iso_8859-9", "windows-1254"),
235 ("iso_8859-9:1989", "windows-1254"),
236 ("koi", "koi8-r"),
237 ("koi8", "koi8-r"),
238 ("koi8-r", "koi8-r"),
239 ("koi8-ru", "koi8-u"),
240 ("koi8-u", "koi8-u"),
241 ("koi8_r", "koi8-r"),
242 ("korean", "euc-kr"),
243 ("ks_c_5601-1987", "euc-kr"),
244 ("ks_c_5601-1989", "euc-kr"),
245 ("ksc5601", "euc-kr"),
246 ("ksc_5601", "euc-kr"),
247 ("l1", "windows-1252"),
248 ("l2", "iso-8859-2"),
249 ("l3", "iso-8859-3"),
250 ("l4", "iso-8859-4"),
251 ("l5", "windows-1254"),
252 ("l6", "iso-8859-10"),
253 ("l9", "iso-8859-15"),
254 ("latin1", "windows-1252"),
255 ("latin2", "iso-8859-2"),
256 ("latin3", "iso-8859-3"),
257 ("latin4", "iso-8859-4"),
258 ("latin5", "windows-1254"),
259 ("latin6", "iso-8859-10"),
260 ("logical", "iso-8859-8-i"),
261 ("mac", "macintosh"),
262 ("macintosh", "macintosh"),
263 ("ms932", "shift_jis"),
264 ("ms_kanji", "shift_jis"),
265 ("replacement", "replacement"),
266 ("shift-jis", "shift_jis"),
267 ("shift_jis", "shift_jis"),
268 ("sjis", "shift_jis"),
269 ("sun_eu_greek", "iso-8859-7"),
270 ("tis-620", "windows-874"),
271 ("ucs-2", "utf-16le"),
272 ("unicode", "utf-16le"),
273 ("unicode-1-1-utf-8", "utf-8"),
274 ("unicode11utf8", "utf-8"),
275 ("unicode20utf8", "utf-8"),
276 ("unicodefeff", "utf-16le"),
277 ("unicodefffe", "utf-16be"),
278 ("us-ascii", "windows-1252"),
279 ("utf-16", "utf-16le"),
280 ("utf-16be", "utf-16be"),
281 ("utf-16le", "utf-16le"),
282 ("utf-8", "utf-8"),
283 ("utf8", "utf-8"),
284 ("visual", "iso-8859-8"),
285 ("windows-1250", "windows-1250"),
286 ("windows-1251", "windows-1251"),
287 ("windows-1252", "windows-1252"),
288 ("windows-1253", "windows-1253"),
289 ("windows-1254", "windows-1254"),
290 ("windows-1255", "windows-1255"),
291 ("windows-1256", "windows-1256"),
292 ("windows-1257", "windows-1257"),
293 ("windows-1258", "windows-1258"),
294 ("windows-31j", "shift_jis"),
295 ("windows-874", "windows-874"),
296 ("windows-949", "euc-kr"),
297 ("x-cp1250", "windows-1250"),
298 ("x-cp1251", "windows-1251"),
299 ("x-cp1252", "windows-1252"),
300 ("x-cp1253", "windows-1253"),
301 ("x-cp1254", "windows-1254"),
302 ("x-cp1255", "windows-1255"),
303 ("x-cp1256", "windows-1256"),
304 ("x-cp1257", "windows-1257"),
305 ("x-cp1258", "windows-1258"),
306 ("x-euc-jp", "euc-jp"),
307 ("x-gbk", "gbk"),
308 ("x-mac-cyrillic", "x-mac-cyrillic"),
309 ("x-mac-roman", "macintosh"),
310 ("x-mac-ukrainian", "x-mac-cyrillic"),
311 ("x-sjis", "shift_jis"),
312 ("x-unicode20utf8", "utf-8"),
313 ("x-user-defined", "x-user-defined"),
314 ("x-x-big5", "big5"),
315];
316pub(crate) fn decode_utf16_checked(bytes: &[u8], little_endian: bool, fatal: bool) -> Option<alloc::string::String> {
319 let units: alloc::vec::Vec<u16> = bytes
320 .chunks_exact(2)
321 .map(|c| {
322 let (lo, hi) = (c[0] as u16, c[1] as u16);
323 if little_endian {
324 lo | (hi << 8)
325 } else {
326 (lo << 8) | hi
327 }
328 })
329 .collect();
330 let mut out = alloc::string::String::new();
331 for r in core::char::decode_utf16(units) {
332 match r {
333 Ok(c) => out.push(c),
334 Err(_) if fatal => return None,
335 Err(_) => out.push(core::char::REPLACEMENT_CHARACTER),
336 }
337 }
338 if bytes.len() % 2 == 1 {
340 if fatal {
341 return None;
342 }
343 out.push(core::char::REPLACEMENT_CHARACTER);
344 }
345 Some(out)
346}
347pub(crate) fn decode_utf16_bytes(bytes: &[u8], little_endian: bool) -> alloc::string::String {
348 decode_utf16_checked(bytes, little_endian, false).unwrap_or_default()
349}
350const WIN1252_HIGH: [u16; 32] = [
352 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D,
353 0x017D, 0x008F, 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A,
354 0x0153, 0x009D, 0x017E, 0x0178,
355];
356fn decode_single_byte(enc: &str, bytes: &[u8]) -> alloc::string::String {
357 bytes
358 .iter()
359 .map(|&b| match (enc, b) {
360 (_, 0..=0x7F) => b as char,
361 ("x-user-defined", _) => char::from_u32(0xF780 + (b as u32 - 0x80)).unwrap_or('\u{FFFD}'),
362 (_, 0x80..=0x9F) => char::from_u32(WIN1252_HIGH[(b - 0x80) as usize] as u32).unwrap_or('\u{FFFD}'),
363 _ => b as char,
364 })
365 .collect()
366}
367pub(crate) fn utf8_incomplete_trailing_len(bytes: &[u8]) -> usize {
373 let len = bytes.len();
374 for back in 1..=3.min(len) {
375 let b = bytes[len - back];
376 if b & 0b1100_0000 == 0b1000_0000 {
377 continue; }
379 let (needed, lo, hi) = match b {
380 0xC2..=0xDF => (2, 0x80, 0xBF),
381 0xE0 => (3, 0xA0, 0xBF),
382 0xE1..=0xEC | 0xEE..=0xEF => (3, 0x80, 0xBF),
383 0xED => (3, 0x80, 0x9F),
384 0xF0 => (4, 0x90, 0xBF),
385 0xF1..=0xF3 => (4, 0x80, 0xBF),
386 0xF4 => (4, 0x80, 0x8F),
387 _ => return 0, };
389 if needed <= back {
390 return 0;
391 }
392 let tail = &bytes[len - back + 1..];
394 let ok = tail.iter().enumerate().all(|(i, &t)| {
395 if i == 0 {
396 t >= lo && t <= hi
397 } else {
398 t & 0b1100_0000 == 0b1000_0000
399 }
400 });
401 return if ok { back } else { 0 };
402 }
403 0
404}
405fn decoder_pending(this: &Value) -> Vec<u8> {
407 if let Value::Object(o) = this {
408 if let Some(Value::Object(p)) = o.borrow().props.get("_pending") {
409 if let ObjKind::Array(items) = &p.borrow().kind {
410 return items.iter().map(|v| v.to_number() as u8).collect();
411 }
412 }
413 }
414 Vec::new()
415}
416fn decoder_store(this: &Value, pending: &[u8], bom_seen: bool) {
417 if let Value::Object(o) = this {
418 let vals: Vec<Value> = pending.iter().map(|&b| Value::Number(b as f64)).collect();
419 let mut b = o.borrow_mut();
420 b.props.insert("_pending".into(), Value::Object(Obj::array(vals)));
421 b.props.insert("_bom_seen".into(), Value::Bool(bom_seen));
422 }
423}
424fn decoder_flag(this: &Value, key: &str) -> bool {
425 match this {
426 Value::Object(o) => o.borrow().props.get(key).map(|v| v.truthy()).unwrap_or(false),
427 _ => false,
428 }
429}
430pub(crate) fn text_decode(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
437 let mut bytes: Vec<u8> = decoder_pending(&this);
438 let input = arg(a, 0);
439 match &input {
440 Value::Undefined => {}
441 Value::Object(_) => {
442 let mut v = alloc::vec::Vec::new();
443 if !buffer_source_bytes(&input, &mut v) {
444 return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'."));
445 }
446 bytes.extend(v.iter().map(|x| *x as i64 as u8));
447 }
448 _ => {
449 return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'."));
450 }
451 }
452 let stream = match arg(a, 1) {
453 o @ Value::Object(_) => obj_prop(&o, "stream").map(|v| v.truthy()).unwrap_or(false),
454 Value::Undefined | Value::Null => false,
455 _ => {
456 return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': parameter 2 is not of type 'TextDecodeOptions'."));
457 }
458 };
459 let enc = if let Value::Object(o) = &this {
460 o.borrow().props.get("_enc").map(|v| v.to_js_string()).unwrap_or_else(|| String::from("utf-8"))
461 } else {
462 String::from("utf-8")
463 };
464 let fatal = decoder_flag(&this, "_fatal");
465 let ignore_bom = decoder_flag(&this, "_ignore_bom");
466 let bom_seen = decoder_flag(&this, "_bom_seen");
467 let pending_len = if stream {
468 match enc.as_str() {
469 "utf-16le" | "utf-16be" => bytes.len() % 2,
473 "utf-8" => utf8_incomplete_trailing_len(&bytes),
474 _ => 0,
475 }
476 } else {
477 0
478 };
479 let ready_len = bytes.len() - pending_len;
480 let (ready, pending) = bytes.split_at(ready_len);
481 let decoded: Option<String> = match enc.as_str() {
482 "utf-16le" => decode_utf16_checked(ready, true, fatal),
483 "utf-16be" => decode_utf16_checked(ready, false, fatal),
484 "windows-1252" | "x-user-defined" => Some(decode_single_byte(&enc, ready)),
485 "utf-8" => {
486 if fatal {
487 core::str::from_utf8(ready).ok().map(String::from)
488 } else {
489 Some(alloc::string::String::from_utf8_lossy(ready).into_owned())
490 }
491 }
492 _ => Some(ready.iter().map(|&b| if b < 0x80 { b as char } else { '\u{FFFD}' }).collect()),
494 };
495 let Some(mut out) = decoded else {
496 decoder_store(&this, &[], false);
497 return Err(it.type_error("Failed to execute 'decode' on 'TextDecoder': The encoded data was not valid."));
498 };
499 let mut seen = bom_seen;
500 if !seen && !out.is_empty() {
501 seen = true;
502 if !ignore_bom && matches!(enc.as_str(), "utf-8" | "utf-16le" | "utf-16be") && out.starts_with('\u{FEFF}') {
503 out.remove(0);
504 }
505 }
506 if stream {
507 decoder_store(&this, pending, seen);
508 } else {
509 decoder_store(&this, &[], false);
510 }
511 Ok(Value::str(out))
512}
513pub(crate) fn text_encoder_ctor(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
514 let o = Obj::plain();
515 {
516 let mut b = o.borrow_mut();
517 b.props.insert("encoding".into(), Value::str("utf-8"));
518 b.props.insert("encode".into(), nv("encode", text_encode));
519 b.props
520 .insert("encodeInto".into(), nv("encodeInto", text_encode_into));
521 }
522 Ok(Value::Object(o))
523}
524pub(crate) fn text_decoder_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
528 let (enc, fatal, ignore_bom) = text_decoder_params(it, a, "TextDecoder")?;
529 let o = Obj::plain();
530 {
531 let mut b = o.borrow_mut();
532 b.props.insert("_enc".into(), Value::str(enc));
533 b.props.insert("_fatal".into(), Value::Bool(fatal));
534 b.props.insert("_ignore_bom".into(), Value::Bool(ignore_bom));
535 b.props.insert("decode".into(), nv("decode", text_decode));
536 insert_decoder_accessors(&mut b);
537 }
538 Ok(Value::Object(o))
539}
540fn decoder_get_encoding(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
541 Ok(match &this {
542 Value::Object(o) => o.borrow().props.get("_enc").cloned().unwrap_or_else(|| Value::str("utf-8")),
543 _ => Value::Undefined,
544 })
545}
546fn decoder_get_fatal(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
547 Ok(Value::Bool(decoder_flag(&this, "_fatal")))
548}
549fn decoder_get_ignore_bom(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
550 Ok(Value::Bool(decoder_flag(&this, "_ignore_bom")))
551}
552pub(crate) fn insert_decoder_accessors(b: &mut Obj) {
554 let acc = |g: NativeFn, n: &str| crate::os_lib::ecma::value::Accessor { get: Some(nv(n, g)), set: None };
555 b.insert_accessor(String::from("encoding"), acc(decoder_get_encoding, "encoding"));
556 b.insert_accessor(String::from("fatal"), acc(decoder_get_fatal, "fatal"));
557 b.insert_accessor(String::from("ignoreBOM"), acc(decoder_get_ignore_bom, "ignoreBOM"));
558}
559pub(crate) fn text_decoder_params(it: &mut Interp, a: &[Value], who: &str) -> Result<(&'static str, bool, bool), Value> {
561 let label = match arg(a, 0) {
562 Value::Undefined => String::from("utf-8"),
563 v => v.to_js_string(),
564 };
565 let Some(enc) = normalize_text_encoding_label(&label) else {
566 return Err(it.range_error(alloc::format!("Failed to construct '{}': The encoding label provided ('{}') is invalid.", who, label)));
567 };
568 let (mut fatal, mut ignore_bom) = (false, false);
569 match arg(a, 1) {
570 Value::Undefined | Value::Null => {}
571 o @ Value::Object(_) => {
572 fatal = obj_prop(&o, "fatal").map(|v| v.truthy()).unwrap_or(false);
573 ignore_bom = obj_prop(&o, "ignoreBOM").map(|v| v.truthy()).unwrap_or(false);
574 }
575 _ => {
576 return Err(it.type_error(alloc::format!("Failed to construct '{}': parameter 2 is not of type 'TextDecoderOptions'.", who)));
577 }
578 }
579 Ok((enc, fatal, ignore_bom))
580}
581
582pub(crate) fn url_create_object_url(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
588 let target = arg(a, 0);
589 let is_media_source = if let Value::Object(o) = &target {
590 let borrow = o.borrow();
591 borrow.props.contains_key("sourceBuffers")
592 || borrow.props.get("_is_media_source").map(|v| v.truthy()).unwrap_or(false)
593 } else {
594 false
595 };
596
597 let id = crypto_random_uuid(it, t, &[])?.to_js_string();
598 let url = if is_media_source {
599 alloc::format!("blob:mediasource-{}", id)
600 } else {
601 alloc::format!("blob:{}", id)
602 };
603
604 if is_media_source {
605 let existing = match it.global.borrow().vars.get("__media_source_urls") {
606 Some(Value::Object(r)) => Some(r.clone()),
607 _ => None,
608 };
609 let registry = match existing {
610 Some(r) => r,
611 None => {
612 let r = Obj::plain();
613 it.global.borrow_mut().vars.insert("__media_source_urls".into(), Value::Object(r.clone()));
614 r
615 }
616 };
617 super::mse::register_media_source_url(&url, &target);
618 registry.borrow_mut().props.insert(url.clone().into(), target);
619 } else {
620 let is_blob = if let Value::Object(o) = &target {
621 o.borrow().props.contains_key("_blob_bytes")
622 } else {
623 false
624 };
625 if is_blob {
626 let existing = match it.global.borrow().vars.get("__blob_urls") {
627 Some(Value::Object(r)) => Some(r.clone()),
628 _ => None,
629 };
630 let registry = match existing {
631 Some(r) => r,
632 None => {
633 let r = Obj::plain();
634 it.global.borrow_mut().vars.insert("__blob_urls".into(), Value::Object(r.clone()));
635 r
636 }
637 };
638 registry.borrow_mut().props.insert(url.clone().into(), target);
639 }
640 }
641
642 Ok(Value::str(url))
643}
644pub(crate) fn url_revoke_object_url(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
646 let url = arg(a, 0).to_js_string();
647 if let Some(Value::Object(registry)) = it.global.borrow().vars.get("__media_source_urls") {
648 registry.borrow_mut().props.shift_remove(&url);
649 }
650 if let Some(Value::Object(registry)) = it.global.borrow().vars.get("__blob_urls") {
651 registry.borrow_mut().props.shift_remove(&url);
652 }
653 Ok(Value::Undefined)
654}
655pub(crate) fn crypto_random_uuid(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
656 let mut bytes = [0u8; 16];
657 for b in bytes.iter_mut() {
658 *b = (next_rand_u64() & 0xff) as u8;
659 }
660 bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; let mut s = String::new();
663 for (i, b) in bytes.iter().enumerate() {
664 if i == 4 || i == 6 || i == 8 || i == 10 {
665 s.push('-');
666 }
667 s.push_str(&format!("{:02x}", b));
668 }
669 Ok(Value::str(s))
670}
671pub(crate) fn crypto_get_random_values(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
678 let v = arg(a, 0);
679 if let Value::Object(o) = &v {
680 let kind = o
681 .borrow()
682 .props
683 .get("_ta_kind")
684 .map(|v| v.to_js_string())
685 .map(|tag| TaKind::from_name(tag.as_str()));
686 if let ObjKind::Bytes(st) = &o.borrow().kind {
687 let mut pool = 0u64;
692 let mut left = 0u32;
693 st.fill_bytes_with(|| {
694 if left == 0 {
695 pool = next_rand_u64();
696 left = 8;
697 }
698 left -= 1;
699 let b = pool as u8;
700 pool >>= 8;
701 b
702 });
703 return Ok(v.clone());
704 }
705 let mut b = o.borrow_mut();
706 if let ObjKind::Array(items) = &mut b.kind {
707 for it2 in items.iter_mut() {
708 let raw = Value::Number((next_rand_u64() >> 11) as f64);
710 *it2 = Value::Number(match kind {
711 Some(k) => k.convert(&raw),
712 None => (next_rand_u64() & 0xff) as f64,
713 });
714 }
715 }
716 }
717 Ok(v)
718}
719
720pub(crate) fn deep_clone_value(
728 it: &mut Interp,
729 v: &Value,
730 seen: &mut Vec<(crate::os_lib::ecma::value::ObjRef, crate::os_lib::ecma::value::ObjRef)>,
731) -> Result<Value, Value> {
732 deep_clone_value_depth(it, v, seen, 0)
733}
734
735fn deep_clone_value_depth(
736 it: &mut Interp,
737 v: &Value,
738 seen: &mut Vec<(crate::os_lib::ecma::value::ObjRef, crate::os_lib::ecma::value::ObjRef)>,
739 depth: usize,
740) -> Result<Value, Value> {
741 if depth > 30 {
750 return Err(make_dom_exception("DataCloneError", "Exceeded maximum call stack size / nesting depth limit"));
751 }
752 let error_proto = match it.global.borrow().vars.get("Error") {
753 Some(Value::Object(ctor)) => match ctor.borrow().props.get("prototype") {
754 Some(Value::Object(p)) => Some(p.clone()),
755 _ => None,
756 },
757 _ => None,
758 };
759 match v {
760 Value::Object(o) => {
761 if let Some((_, cloned)) = seen.iter().find(|(orig, _)| Rc::ptr_eq(orig, o)) {
762 return Ok(Value::Object(cloned.clone()));
763 }
764 if o.borrow().is_callable() {
773 return Err(make_dom_exception("DataCloneError", "could not be cloned"));
774 }
775 if matches!(&o.borrow().kind, ObjKind::PromiseObj(_)) {
784 return Err(make_dom_exception("DataCloneError", "could not be cloned"));
785 }
786 if matches!(&o.borrow().kind, ObjKind::Proxy(_)) {
795 let target = unwrap_proxy_target(o);
796 let cloned = deep_clone_value_depth(it, &Value::Object(target), seen, depth + 1)?;
797 if let Value::Object(c) = &cloned {
798 seen.push((o.clone(), c.clone()));
799 }
800 return Ok(cloned);
801 }
802 if let ObjKind::DateObj(ms) = &o.borrow().kind {
809 return Ok(Value::Object(Obj::date_obj(*ms)));
810 }
811 let regex_info = match &o.borrow().kind {
812 ObjKind::RegExpObj(r) => {
813 let d = r.borrow();
814 Some((d.re.source.clone(), d.re.flags.clone(), d.last_index))
815 }
816 _ => None,
817 };
818 if let Some((source, flags, last_index)) = regex_info {
819 let re = regex::Regex::new(&source, &flags);
820 return Ok(Value::Object(Obj::regexp(RegExpData { re, last_index })));
821 }
822 let bytes_ta = match &o.borrow().kind {
824 ObjKind::Bytes(st) => Some(st.clone()),
825 _ => None,
826 };
827 if let Some(st) = bytes_ta {
828 let tag = o.borrow().props.get("_ta_kind").map(|v| v.to_js_string()).unwrap_or_default();
829 let new_val = crate::os_lib::ecma::builtins::typed_array::make_bytes_ta(
830 it,
831 crate::os_lib::ecma::value::ByteStore::new(st.to_vec(), st.kind),
832 TaKind::from_name(tag.as_str()),
833 );
834 if let Value::Object(new) = &new_val {
835 seen.push((o.clone(), new.clone()));
836 }
837 return Ok(new_val);
838 }
839 let is_array = matches!(&o.borrow().kind, ObjKind::Array(_));
840 if is_array {
841 let ta_kind_tag = o.borrow().props.get("_ta_kind").map(|v| v.to_js_string());
848 if let Some(tag) = ta_kind_tag {
849 let items = match &o.borrow().kind {
850 ObjKind::Array(items) => items.iter().map(|v| v.to_number()).collect(),
851 _ => unreachable!(),
852 };
853 let new_val = make_typed_array(it, items, TaKind::from_name(tag.as_str()));
854 if let Value::Object(new) = &new_val {
855 seen.push((o.clone(), new.clone()));
856 }
857 return Ok(new_val);
858 }
859 let new = Obj::array(Vec::new());
860 seen.push((o.clone(), new.clone()));
861 let items = match &o.borrow().kind {
862 ObjKind::Array(items) => items.clone(),
863 _ => unreachable!(),
864 };
865 let mut cloned_items: Vec<Value> = Vec::with_capacity(items.len());
866 for x in &items {
867 cloned_items.push(deep_clone_value_depth(it, x, seen, depth + 1)?);
868 }
869 if let ObjKind::Array(v) = &mut new.borrow_mut().kind {
870 *v = cloned_items;
871 }
872 return Ok(Value::Object(new));
873 }
874 let is_map = matches!(&o.borrow().kind, ObjKind::MapObj(_));
878 if is_map {
879 let new = Obj::map_obj(Vec::new());
880 seen.push((o.clone(), new.clone()));
881 let entries = match &o.borrow().kind {
882 ObjKind::MapObj(e) => e.clone(),
883 _ => unreachable!(),
884 };
885 let mut cloned: Vec<(Value, Value)> = Vec::with_capacity(entries.len());
886 for (k, val) in &entries {
887 let ck = deep_clone_value_depth(it, k, seen, depth + 1)?;
888 let cv = deep_clone_value_depth(it, val, seen, depth + 1)?;
889 cloned.push((ck, cv));
890 }
891 if let ObjKind::MapObj(e) = &mut new.borrow_mut().kind {
892 *e = cloned;
893 }
894 return Ok(Value::Object(new));
895 }
896 let is_set = matches!(&o.borrow().kind, ObjKind::SetObj(_));
897 if is_set {
898 let new = Obj::set_obj(Vec::new());
899 seen.push((o.clone(), new.clone()));
900 let items = match &o.borrow().kind {
901 ObjKind::SetObj(s) => s.clone(),
902 _ => unreachable!(),
903 };
904 let mut cloned: Vec<Value> = Vec::with_capacity(items.len());
905 for x in &items {
906 cloned.push(deep_clone_value_depth(it, x, seen, depth + 1)?);
907 }
908 if let ObjKind::SetObj(s) = &mut new.borrow_mut().kind {
909 *s = cloned;
910 }
911 return Ok(Value::Object(new));
912 }
913 if let Some(Value::Object(bytes_obj)) = o.borrow().props.get("_blob_bytes").cloned() {
920 let bytes: alloc::vec::Vec<f64> = match &bytes_obj.borrow().kind {
921 ObjKind::Array(items) => items.iter().map(|v| v.to_number()).collect(),
922 _ => alloc::vec::Vec::new(),
923 };
924 let mime = o.borrow().props.get("type").map(|v| v.to_js_string()).unwrap_or_default();
925 let file_meta = o.borrow().props.get("name").cloned().map(|name| {
935 let last_modified =
936 o.borrow().props.get("lastModified").cloned().unwrap_or(Value::Number(0.0));
937 let webkit_relative_path =
938 o.borrow().props.get("webkitRelativePath").cloned().unwrap_or_else(|| Value::str(""));
939 (name, last_modified, webkit_relative_path)
940 });
941 let new_val = make_blob(bytes, mime);
942 if let (Value::Object(new), Some((name, last_modified, webkit_relative_path))) = (&new_val, file_meta) {
943 new.borrow_mut().props.insert("name".into(), name);
944 new.borrow_mut().props.insert("lastModified".into(), last_modified);
945 new.borrow_mut().props.insert("webkitRelativePath".into(), webkit_relative_path);
946 }
947 if let Value::Object(new) = &new_val {
948 seen.push((o.clone(), new.clone()));
949 }
950 return Ok(new_val);
951 }
952 if o.borrow().props.contains_key("_dv_bytes") {
953 let byte_values: alloc::vec::Vec<Value> = crate::os_lib::ecma::builtins::typed_array::dv_slice_bytes(o)
954 .unwrap_or_default()
955 .into_iter()
956 .map(Value::Number)
957 .collect();
958 let new_buffer = make_arraybuffer_with_bytes(byte_values.iter().map(|v| v.to_number()).collect());
959 let new_val = make_dataview(new_buffer, 0, byte_values);
960 if let Value::Object(new) = &new_val {
961 seen.push((o.clone(), new.clone()));
962 }
963 return Ok(new_val);
964 }
965 let is_arraybuffer = {
969 let b = o.borrow();
970 b.props.contains_key("byteLength")
971 && matches!(b.props.get("slice"), Some(Value::Object(f)) if f.borrow().is_callable())
972 };
973 if is_arraybuffer {
974 let is_resizable = matches!(o.borrow().props.get("resizable"), Some(Value::Bool(true)));
982 let max_byte_length = o.borrow().props.get("maxByteLength").map(|v| v.to_number() as usize);
983 let bytes_prop = o.borrow().props.get("_bytes").cloned();
984 let byte_length = o
985 .borrow()
986 .props
987 .get("byteLength")
988 .map(|v| v.to_number() as usize)
989 .unwrap_or(0);
990 let new_val = make_arraybuffer_ex(byte_length, if is_resizable { max_byte_length } else { None });
991 if let (Value::Object(new), Some(Value::Object(bytes_obj))) = (&new_val, &bytes_prop) {
992 let bytes = crate::os_lib::ecma::builtins::typed_array::obj_byte_values(bytes_obj).unwrap_or_default();
993 new.borrow_mut().props.insert(
994 "_bytes".into(),
995 Value::Object(Obj::bytes(crate::os_lib::ecma::value::ByteStore::new(bytes, 0))),
996 );
997 }
998 if let Value::Object(new) = &new_val {
999 seen.push((o.clone(), new.clone()));
1000 }
1001 return Ok(new_val);
1002 }
1003 let is_error = error_proto.as_ref().is_some_and(|ep| {
1013 let mut cur = o.borrow().proto.clone();
1014 let mut guard = 0;
1015 while let Some(c) = cur {
1016 if Rc::ptr_eq(&c, ep) {
1017 return true;
1018 }
1019 cur = c.borrow().proto.clone();
1020 guard += 1;
1021 if guard > 1000 {
1022 break;
1023 }
1024 }
1025 false
1026 });
1027 let new = Obj::plain();
1028 if is_error {
1029 new.borrow_mut().proto = o.borrow().proto.clone();
1030 }
1031 seen.push((o.clone(), new.clone()));
1032 let props: Vec<(String, Value)> =
1033 o.borrow().props.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
1034 for (k, val) in props {
1035 let cv = deep_clone_value_depth(it, &val, seen, depth + 1)?;
1036 new.borrow_mut().props.insert(k.into(), cv);
1037 }
1038 Ok(Value::Object(new))
1039 }
1040 other => Ok(other.clone()),
1041 }
1042}
1043pub(crate) fn structured_clone(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1051 let mut seen = Vec::new();
1052 let result = deep_clone_value(it, &arg(a, 0), &mut seen)?;
1053 if let Value::Object(opts) = arg(a, 1) {
1054 let transfer_list = opts.borrow().props.get("transfer").cloned();
1055 if let Some(list) = transfer_list {
1056 for item in this_items(&list) {
1057 if let Value::Object(o) = &item {
1058 let is_arraybuffer = {
1059 let b = o.borrow();
1060 b.props.contains_key("byteLength")
1061 && matches!(b.props.get("slice"), Some(Value::Object(f)) if f.borrow().is_callable())
1062 };
1063 if is_arraybuffer {
1064 let mut b = o.borrow_mut();
1065 b.props.insert("detached".into(), Value::Bool(true));
1066 b.props.shift_remove("_bytes");
1067 }
1068 }
1069 }
1070 }
1071 }
1072 Ok(result)
1073}
1074