ps-blitz-script 0.5.1

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

use blitz_dom::NodeId;
use blitz_dom::local_name;
use boa_engine::object::builtins::JsArray;
use boa_engine::object::{JsObject, ObjectInitializer};
use boa_engine::value::JsValue;
use boa_engine::{Context, JsResult, JsString, NativeFunction, js_string};

use super::{
    define_accessor, define_method, dom_ctx, node_or_null, node_wrapper, qual_name, qual_name_ns,
    this_node_id, to_rust_string,
};
use crate::state::DomCtx;

pub(crate) fn init_document_proto(proto: &JsObject, context: &mut Context) {
    define_accessor(
        proto,
        "documentElement",
        Some(document_element),
        None,
        context,
    );
    define_accessor(proto, "body", Some(body), None, context);
    define_accessor(proto, "head", Some(head), None, context);
    define_accessor(proto, "activeElement", Some(active_element), None, context);
    define_accessor(proto, "implementation", Some(implementation), None, context);
    define_accessor(proto, "title", Some(title), Some(set_title), context);
    define_accessor(proto, "defaultView", Some(default_view), None, context);
    define_accessor(
        proto,
        "location",
        Some(get_location),
        Some(set_location),
        context,
    );
    define_accessor(proto, "domain", Some(get_domain), Some(set_domain), context);

    define_method(proto, "createElement", 1, create_element, context);
    define_method(proto, "createElementNS", 2, create_element_ns, context);
    define_method(proto, "createTextNode", 1, create_text_node, context);
    define_method(proto, "importNode", 2, import_node, context);
    define_method(proto, "createRange", 0, super::range::create_range, context);
    define_method(
        proto,
        "getSelection",
        0,
        super::range::document_selection,
        context,
    );
    define_method(proto, "createComment", 1, create_comment, context);
    define_method(
        proto,
        "createDocumentFragment",
        0,
        create_document_fragment,
        context,
    );
    define_method(proto, "getElementById", 1, get_element_by_id, context);
    define_method(proto, "querySelector", 1, query_selector, context);
    define_method(proto, "querySelectorAll", 1, query_selector_all, context);
}

/// The first element with `tag` inside `root_id`'s subtree.
///
/// Scoped to `root_id` rather than the page, because `createHTMLDocument`
/// makes a second document in the same arena. A page-wide search answered
/// `newDoc.body` with the live page's `body`, which is worse than answering
/// `null`: jQuery writes two `<form>` elements into whatever it gets back.
fn find_tag_within(ctx: &DomCtx, root_id: NodeId, tag: blitz_dom::LocalName) -> Option<NodeId> {
    let doc = ctx.doc.borrow();

    // `document > html > body` is the shape in nearly every case, so try the
    // root element and its children before walking anything. Without this,
    // reading `document.body` scans the whole of `head` first, every time.
    let root_element = doc
        .get_node(root_id)?
        .children
        .iter()
        .copied()
        .find(|id| doc.get_node(*id).is_some_and(|child| child.is_element()));
    if let Some(element_id) = root_element {
        let element = doc.get_node(element_id)?;
        if element.data.is_element_with_tag_name(&tag) {
            return Some(element_id);
        }
        if let Some(found) = element.children.iter().copied().find(|child_id| {
            doc.get_node(*child_id)
                .is_some_and(|child| child.data.is_element_with_tag_name(&tag))
        }) {
            return Some(found);
        }
    }

    // Otherwise walk. A missing node is skipped rather than ending the search:
    // returning `None` from inside the loop would abandon siblings that are
    // still there.
    let mut stack = vec![root_id];
    while let Some(node_id) = stack.pop() {
        let Some(node) = doc.get_node(node_id) else {
            continue;
        };
        if node.data.is_element_with_tag_name(&tag) {
            return Some(node_id);
        }
        stack.extend(node.children.iter().rev().copied());
    }
    None
}

fn document_element(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    let root_id = ctx.doc.borrow().try_root_element().map(|root| root.id);
    // A created document answers with its own root element; the page document
    // keeps the cached root it already had.
    let root_id = if Some(this_id) == ctx.doc.borrow().root_node().id.into() {
        root_id
    } else {
        let doc = ctx.doc.borrow();
        doc.get_node(this_id).and_then(|node| {
            node.children
                .iter()
                .copied()
                .find(|id| doc.get_node(*id).is_some_and(|c| c.is_element()))
        })
    };
    Ok(node_or_null(&ctx, root_id, context))
}

fn body(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    let body_id = if ctx
        .doc
        .borrow()
        .get_node(this_id)
        .is_some_and(|node| node.is_html_document())
    {
        find_tag_within(&ctx, this_id, local_name!("body"))
    } else {
        None
    };
    Ok(node_or_null(&ctx, body_id, context))
}

fn head(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    let head_id = if ctx
        .doc
        .borrow()
        .get_node(this_id)
        .is_some_and(|node| node.is_html_document())
    {
        find_tag_within(&ctx, this_id, local_name!("head"))
    } else {
        None
    };
    Ok(node_or_null(&ctx, head_id, context))
}

fn active_element(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    let focus_id = if this_id == ctx.doc.borrow().root_node().id {
        ctx.doc.borrow().get_focussed_node_id()
    } else {
        None
    };
    Ok(node_or_null(&ctx, focus_id, context))
}

fn default_view(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    if this_id == ctx.doc.borrow().root_node().id {
        Ok(context.global_object().into())
    } else {
        Ok(JsValue::null())
    }
}

/// `document.location`: the window's `Location`, the same object.
fn get_location(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    if this_id != ctx.doc.borrow().root_node().id {
        return Ok(JsValue::null());
    }
    context.global_object().get(js_string!("location"), context)
}

/// `document.location = url` navigates, as `location.href = url` does.
fn set_location(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    if this_id != ctx.doc.borrow().root_node().id {
        return Ok(JsValue::undefined());
    }
    let location = context
        .global_object()
        .get(js_string!("location"), context)?;
    if let Some(location) = location.as_object() {
        location.set(
            js_string!("href"),
            args.first().cloned().unwrap_or_default(),
            true,
            context,
        )?;
    }
    Ok(JsValue::undefined())
}

/// `document.domain`: the host of the document's URL.
fn get_domain(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = this_node_id(this)?;
    let location = context
        .global_object()
        .get(js_string!("location"), context)?;
    match location.as_object() {
        Some(location) => location.get(js_string!("hostname"), context),
        None => Ok(js_string!("").into()),
    }
}

/// Setting `document.domain` to the current host or one of its parent
/// domains is accepted and changes nothing, which is what Chromium does now
/// that documents are origin-keyed; anything else is a SecurityError.
fn set_domain(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let requested = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?
        .to_ascii_lowercase();
    let current = get_domain(this, &[], context)?
        .to_string(context)?
        .to_std_string_escaped()
        .to_ascii_lowercase();
    let allowed = !requested.is_empty()
        && (current == requested
            || (current.ends_with(&requested)
                && current[..current.len() - requested.len()].ends_with('.')
                && requested.contains('.')));
    if !allowed {
        return Err(crate::dom_exception::error(
            "SecurityError",
            &format!("'{requested}' is not a suffix of '{current}'"),
            context,
        ));
    }
    Ok(JsValue::undefined())
}

// === Node creation ===

fn create_element(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let _t = crate::script_stats::Timed::new(&ctx, "dom:createElement");
    let document_id = this_node_id(this)?;
    let html = ctx
        .doc
        .borrow()
        .get_node(document_id)
        .is_some_and(|node| node.is_html_document());
    let tag = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let tag = if html { tag.to_ascii_lowercase() } else { tag };
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        let mut mutr = doc.mutate();
        let name = if html {
            qual_name(&tag)
        } else {
            qual_name_ns(&tag, "")
        };
        let id = mutr.create_element(name, Vec::new());
        mutr.adopt_node(id, document_id);
        id
    };
    Ok(node_wrapper(&ctx, node_id, context).into())
}

fn create_element_ns(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let ns_value = &args.first().cloned().unwrap_or_default();
    let ns = if ns_value.is_null_or_undefined() {
        String::new()
    } else {
        to_rust_string(ns_value, context)?
    };
    let tag = to_rust_string(args.get(1).unwrap_or(&JsValue::undefined()), context)?;
    let (prefix, local) = match tag.split_once(':') {
        Some((prefix, local)) => (Some(markup5ever::Prefix::from(prefix)), local),
        None => (None, tag.as_str()),
    };
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        let mut mutr = doc.mutate();
        let name = blitz_dom::QualName::new(
            prefix,
            blitz_dom::Namespace::from(ns.as_str()),
            blitz_dom::LocalName::from(local),
        );
        let id = mutr.create_element(name, Vec::new());
        mutr.adopt_node(id, document_id);
        id
    };
    Ok(node_wrapper(&ctx, node_id, context).into())
}

/// Clone a node for insertion into this document.
///
/// Import clones first, then uses native adoption so ownership, ID indexes,
/// and custom element reactions remain consistent across document boundaries.
fn import_node(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let node = args.first().cloned().unwrap_or_else(JsValue::undefined);
    let source_id = this_node_id(&node)?;
    if ctx.doc.borrow().get_node(source_id).is_some_and(|node| {
        matches!(
            node.data,
            blitz_dom::node::NodeData::Document(_) | blitz_dom::node::NodeData::ShadowRoot(_)
        )
    }) {
        return Err(super::doma::dom_error(
            "NotSupportedError",
            "Cannot import this node",
            context,
        ));
    }
    let deep = args.get(1).cloned().unwrap_or_else(JsValue::undefined);
    let cloned = super::node::clone_node(&node, &[deep], context)?;
    let id = this_node_id(&cloned)?;
    ctx.doc.borrow_mut().mutate().adopt_node(id, document_id);
    Ok(node_wrapper(&ctx, id, context).into())
}

fn create_text_node(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let _t = crate::script_stats::Timed::new(&ctx, "dom:createTextNode");
    let document_id = this_node_id(this)?;
    let text = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        let mut mutr = doc.mutate();
        let id = mutr.create_text_node(&text);
        mutr.adopt_node(id, document_id);
        id
    };
    Ok(node_wrapper(&ctx, node_id, context).into())
}

/// `new Text("...")`, the constructor form of `document.createTextNode`.
///
/// Rarely called directly, but frameworks reference the global to test node
/// types, and a missing global is a `ReferenceError` at module scope: the whole
/// bundle dies before it renders, which looks exactly like a blank page rather
/// than like a missing API.
/// The prototype has to be attached, not just the callable. `register_global_callable`
/// alone produces a function with no `prototype` property, and `class X extends
/// Text` then fails with "superclass prototype must be an object or null",
/// which is how pathscale.com's bundle died after `Text` itself existed.
pub(crate) fn register_text_constructor(proto: &JsObject, context: &mut Context) {
    context
        .register_global_callable(
            boa_engine::js_string!("Text"),
            1,
            boa_engine::NativeFunction::from_fn_ptr(text_constructor),
        )
        .expect("failed to register Text constructor");
    let global = context.global_object().clone();
    let constructor = global
        .get(boa_engine::js_string!("Text"), context)
        .expect("Text constructor missing")
        .as_object()
        .expect("Text is not an object");
    constructor
        .set(
            boa_engine::js_string!("prototype"),
            proto.clone(),
            true,
            context,
        )
        .expect("failed to set Text prototype");
}

fn text_constructor(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    // An omitted argument makes an empty text node, per the DOM spec, rather
    // than the string "undefined".
    let text = match args.first() {
        Some(value) if !value.is_undefined() => to_rust_string(value, context)?,
        _ => String::new(),
    };
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        doc.mutate().create_text_node(&text)
    };
    Ok(node_wrapper(&ctx, node_id, context).into())
}

fn create_comment(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let text = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        let mut mutr = doc.mutate();
        let id = mutr.create_comment_node(&text);
        mutr.adopt_node(id, document_id);
        id
    };
    Ok(node_wrapper(&ctx, node_id, context).into())
}

/// `document.createDocumentFragment()`.
///
/// jQuery calls this during initialisation:
///
/// ```js
/// xe = C.createDocumentFragment().appendChild(C.createElement("div"))
/// ```
///
/// Without it the call threw `TypeError: not a callable function` and the
/// library died before defining `jQuery` and every page depending on it lost
/// its scripting. Eight sites in a hundred-site corpus failed that way, and
/// they reported it as `jQuery is not defined`: a missing global that was never
/// missing.
fn create_document_fragment(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        let mut mutr = doc.mutate();
        let id = mutr.create_document_fragment();
        mutr.adopt_node(id, document_id);
        id
    };
    Ok(node_wrapper(&ctx, node_id, context).into())
}

// === Lookup ===

fn get_element_by_id(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let id = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let node_id = ctx.doc.borrow().get_element_by_id_in(document_id, &id);
    Ok(node_or_null(&ctx, node_id, context))
}

fn query_selector(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let selector = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let node_id = ctx
        .doc
        .borrow()
        .query_selector_in(document_id, &selector)
        .map_err(|_| super::element::invalid_selector(&selector, context))?;
    Ok(node_or_null(&ctx, node_id, context))
}

fn query_selector_all(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let document_id = this_node_id(this)?;
    let selector = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let matches: Vec<NodeId> = ctx
        .doc
        .borrow()
        .query_selector_all_in(document_id, &selector)
        .map(|matches| matches.into_iter().collect())
        .map_err(|_| super::element::invalid_selector(&selector, context))?;
    let wrappers: Vec<JsValue> = matches
        .into_iter()
        .map(|match_id| node_wrapper(&ctx, match_id, context).into())
        .collect();
    Ok(JsArray::from_iter(wrappers, context).into())
}

/// `document.implementation`.
///
/// `createHTMLDocument` and `createDocument`. `hasFeature` was deprecated to a
/// constant `true` long ago and is not here; a stub that answers plausibly would be
/// worse than the absent property, which at least fails where the caller can see it.
fn implementation(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = this_node_id(this)?;
    let object = ObjectInitializer::new(context)
        .function(
            NativeFunction::from_fn_ptr(create_html_document),
            js_string!("createHTMLDocument"),
            1,
        )
        .function(
            NativeFunction::from_fn_ptr(create_xml_document),
            js_string!("createDocument"),
            2,
        )
        .build();
    Ok(object.into())
}

/// The text of this document's `<title>`, or the empty string.
fn title(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    let text = find_tag_within(&ctx, this_id, local_name!("title"))
        .and_then(|title_id| {
            let doc = ctx.doc.borrow();
            let title = doc.get_node(title_id)?;
            Some(
                title
                    .children
                    .iter()
                    .filter_map(|child_id| doc.get_node(*child_id))
                    .filter_map(|child| child.text_data().map(|text| text.content.clone()))
                    .collect::<String>(),
            )
        })
        .unwrap_or_default();
    Ok(JsString::from(text.as_str()).into())
}

const SVG_NS: &str = "http://www.w3.org/2000/svg";

/// Setting `document.title` replaces the text of the title element. In an SVG document that is the
/// root's first `<svg:title>` child, inserted as its first child when missing; otherwise the first
/// `<title>`, appended to `<head>` when missing (nothing happens without a `<head>`). Goes through
/// the script-visible methods so mutation observers and restyles see an ordinary DOM change.
fn set_title(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let value = args
        .first()
        .cloned()
        .unwrap_or_default()
        .to_string(context)?;
    let ctx = dom_ctx(context)?;
    let this_id = this_node_id(this)?;
    let Some(document) = this.as_object() else {
        return Ok(JsValue::undefined());
    };
    let root = document.get(js_string!("documentElement"), context)?;
    let Some(root) = root.as_object() else {
        return Ok(JsValue::undefined());
    };
    let root_id = this_node_id(&root.clone().into())?;
    let root_is_svg = {
        let doc = ctx.doc.borrow();
        doc.get_node(root_id)
            .and_then(|node| node.element_data())
            .is_some_and(|element| &*element.name.ns == SVG_NS)
    };
    let existing = if root_is_svg {
        let doc = ctx.doc.borrow();
        doc.get_node(root_id).and_then(|node| {
            node.children.iter().copied().find(|id| {
                doc.get_node(*id)
                    .and_then(|child| child.element_data())
                    .is_some_and(|element| {
                        element.name.local == local_name!("title") && &*element.name.ns == SVG_NS
                    })
            })
        })
    } else {
        find_tag_within(&ctx, this_id, local_name!("title"))
    };
    let element = match existing {
        Some(id) => node_wrapper(&ctx, id, context),
        None if root_is_svg => {
            let created = call(
                &document,
                js_string!("createElementNS"),
                &[js_string!(SVG_NS).into(), js_string!("title").into()],
                context,
            )?;
            let first = root.get(js_string!("firstChild"), context)?;
            call(
                &root,
                js_string!("insertBefore"),
                &[created.clone(), first],
                context,
            )?;
            created.as_object().ok_or_else(|| {
                boa_engine::JsNativeError::typ().with_message("createElementNS returned no element")
            })?
        }
        None => {
            let head = document.get(js_string!("head"), context)?;
            let Some(head) = head.as_object() else {
                return Ok(JsValue::undefined());
            };
            let created = call(
                &document,
                js_string!("createElement"),
                &[js_string!("title").into()],
                context,
            )?;
            call(
                &head,
                js_string!("appendChild"),
                &[created.clone()],
                context,
            )?;
            created.as_object().ok_or_else(|| {
                boa_engine::JsNativeError::typ().with_message("createElement returned no element")
            })?
        }
    };
    element.set(js_string!("textContent"), value, true, context)?;
    Ok(JsValue::undefined())
}

fn call(
    object: &JsObject,
    name: JsString,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let method = object.get(name, context)?;
    let method = method.as_callable().ok_or_else(|| {
        boa_engine::JsNativeError::typ().with_message("document.title: missing DOM method")
    })?;
    method.call(&object.clone().into(), args, context)
}

/// `document.implementation.createDocument(namespace, qualifiedName, doctype)`.
///
/// The content type follows the namespace (XHTML, SVG, or generic XML). A non-empty
/// qualified name becomes the document element, made as `createElementNS` makes one.
/// There are no DocumentType nodes, so a doctype other than null is a TypeError.
fn create_xml_document(
    _this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let namespace = args.first().cloned().unwrap_or_default();
    let qualified = match args.get(1) {
        None => {
            return Err(boa_engine::JsNativeError::typ()
                .with_message("createDocument: qualifiedName is required")
                .into());
        }
        Some(value) if value.is_null() => String::new(),
        Some(value) => to_rust_string(value, context)?,
    };
    if args
        .get(2)
        .is_some_and(|doctype| !doctype.is_null_or_undefined())
    {
        return Err(boa_engine::JsNativeError::typ()
            .with_message("createDocument: parameter 3 is not of type 'DocumentType'")
            .into());
    }
    let ns = if namespace.is_null_or_undefined() {
        String::new()
    } else {
        to_rust_string(&namespace, context)?
    };
    let content_type = match ns.as_str() {
        "http://www.w3.org/1999/xhtml" => "application/xhtml+xml",
        "http://www.w3.org/2000/svg" => "image/svg+xml",
        _ => "application/xml",
    };
    let document_id = ctx.doc.borrow_mut().mutate().create_document(content_type);
    ctx.state.borrow_mut().detached_nodes.push(document_id);
    let document: JsValue = node_wrapper(&ctx, document_id, context).into();
    if !qualified.is_empty() {
        let element =
            create_element_ns(&document, &[namespace, super::js_str(&qualified)], context)?;
        let element_id = this_node_id(&element)?;
        ctx.doc
            .borrow_mut()
            .mutate()
            .append_children(document_id, &[element_id]);
    }
    Ok(document)
}

/// `document.implementation.createHTMLDocument(title)`.
///
/// The new document is detached, so it never lays out or paints, and it lives
/// in this document's arena rather than a second `BaseDocument`.
fn create_html_document(
    _this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let title = match args.first() {
        // `createHTMLDocument()` with no argument is not the same call as
        // `createHTMLDocument(undefined)`: the first has no title at all, the
        // second stringifies to "undefined". jQuery passes "".
        None => String::new(),
        Some(value) => to_rust_string(value, context)?,
    };
    let node_id = {
        let mut doc = ctx.doc.borrow_mut();
        doc.mutate().create_html_document(&title)
    };
    ctx.state.borrow_mut().detached_nodes.push(node_id);
    Ok(node_wrapper(&ctx, node_id, context).into())
}