Skip to content

Truly independent web browser

38.1 KB
Raw Blame
/*
 * Copyright (c) 2020, Andreas Kling <[email protected]>
 * Copyright (c) 2023, Aliaksandr Kalenik <[email protected]>
 * Copyright (c) 2023, Sam Atkins <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/ByteBuffer.h>
#include <AK/Debug.h>
#include <AK/FlyString.h>
#include <AK/LexicalPath.h>
#include <AK/NeverDestroyed.h>
#include <AK/Utf16FlyString.h>
#include <LibCore/Promise.h>
#include <LibCore/Resource.h>
#include <LibGC/Heap.h>
#include <LibGfx/ImageFormats/ImageDecoder.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibTextCodec/Decoder.h>
#include <LibURL/URL.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/DOM/CustomEvent.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentLoading.h>
#include <LibWeb/DOM/IDLEventListener.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
#include <LibWeb/Fetch/Response.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/HTMLHeadElement.h>
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/HTMLLinkElement.h>
#include <LibWeb/HTML/HTMLPreElement.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/NavigationParams.h>
#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Parser/IncrementalDocumentParser.h>
#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/SharedResourceRequest.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Loader/GeneratedPagesLoader.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/XML/XMLDocumentBuilder.h>
#include <LibWebCommon/MimeSniff/Resource.h>
#include <LibXML/Parser/Parser.h>

namespace Web {

static void add_pdf_viewer_ready_listener(DOM::Document& document, GC::Ref<Fetch::Infrastructure::ResponseView> response)
{
    auto& realm = document.relevant_settings_object().realm();
    auto js_response = Fetch::Response::create(response, Fetch::Headers::Guard::Response);

    auto listener_function = JS::NativeFunction::create(
        realm, GC::create_function(GC::Heap::the(), GC::captures(document, js_response), [](DOM::Document& document, GC::Ref<Fetch::Response>& js_response, JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {
            auto& realm = document.relevant_settings_object().realm();
            auto detail = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { js_response });
            document.dispatch_event(*DOM::create_custom_event(realm, "ladybirdpdf"_utf16_fly_string, detail));
            return JS::js_undefined();
        }),
        0, Utf16FlyString {}, &realm);
    auto callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*listener_function, realm);
    document.add_event_listener_without_options("ladybirdviewerready"_utf16_fly_string, *DOM::IDLEventListener::create(*callback));
}

// Replaces a document's content with a simple error message.
static void convert_to_xml_error_document(DOM::Document& document, Utf16String error_string)
{
    auto html_element = MUST(DOM::create_element(document, HTML::TagNames::html, Namespace::HTML));
    auto body_element = MUST(DOM::create_element(document, HTML::TagNames::body, Namespace::HTML));
    MUST(html_element->append_child(body_element));
    MUST(body_element->append_child(DOM::Text::create(document, move(error_string))));
    document.remove_all_children();
    MUST(document.append_child(html_element));

    if (document.ready_for_post_load_tasks())
        return;

    // NB: The XML parser stops parsing at an error the way it does at the end of its input, so the end steps it started
    //     may still be running. They completely finish loading the document, and doing it here too would fire a second
    //     load event at the document's container.
    if (document.has_html_parser_end_state())
        return;

    if (!document.is_completely_loaded())
        document.completely_finish_loading();

    document.set_ready_for_post_load_tasks(true);
}

// https://www.rfc-editor.org/rfc/rfc7303#section-3.2
static StringView determine_xml_encoding(ReadonlyBytes data, Optional<StringView> content_encoding)
{
    // NB: A BOM takes precedence over the transport charset, followed by the XML declaration. Return canonical
    //     encoding labels so that these views do not refer to the temporary sniffing results.
    if (auto bom_encoding = HTML::run_bom_sniff(data); bom_encoding.has_value())
        return TextCodec::get_standardized_encoding(*bom_encoding).value();
    if (content_encoding.has_value()) {
        if (auto encoding = TextCodec::get_standardized_encoding(*content_encoding); encoding.has_value())
            return *encoding;
    }
    if (auto xml_encoding = HTML::get_an_xml_encoding(data); xml_encoding.has_value())
        return TextCodec::get_standardized_encoding(*xml_encoding).value();

    // https://www.w3.org/TR/xml/#charencoding
    // [...] it is a fatal error [...] for an entity which begins with neither a Byte Order Mark nor an encoding
    // declaration to use an encoding other than UTF-8.
    return "UTF-8"sv;
}

bool build_xml_document(DOM::Document& document, ByteBuffer const& data, Optional<StringView> content_encoding, XMLScriptingSupport scripting_support)
{
    auto decoder = TextCodec::decoder_for(determine_xml_encoding(data, content_encoding));
    VERIFY(decoder.has_value());
    // Well-formed XML documents contain only properly encoded characters
    auto source_or_error = TextCodec::decode_to_utf8(data, *decoder, TextCodec::ErrorMode::Fatal);
    if (source_or_error.is_error()) {
        convert_to_xml_error_document(document, "XML Document contains improperly-encoded characters"_utf16);
        return false;
    }
    auto source = source_or_error.release_value();
    XML::Parser parser(source, { .preserve_comments = true, .resolve_named_html_entity = resolve_named_html_entity });
    XMLDocumentBuilder builder { document, scripting_support };
    auto result = parser.parse_with_listener(builder);
    return !result.is_error() && !builder.has_error();
}

// https://html.spec.whatwg.org/multipage/document-lifecycle.html#navigate-html
static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_html_document(HTML::NavigationParams const& navigation_params)
{
    // To load an HTML document, given navigation params navigationParams:

    // 1. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.
    auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_utf16_fly_string, navigation_params));

    // 2. If document's URL is about:blank, then populate with html/head/body given document.
    // FIXME: The additional check for a non-empty body fixes issues with loading javascript urls in iframes, which
    //        default to an "about:blank" url. Is this a spec bug?
    if (document->url().to_string() == "about:blank"_string
        && navigation_params.response->body_length().value_or(0) == 0) {
        TRY(document->populate_with_html_head_and_body());
        if (navigation_params.navigable && navigation_params.navigable->is_top_level_traversable())
            document->set_supported_color_schemes({ "light"_utf16_fly_string, "dark"_utf16_fly_string });
        HTML::HTMLParser::the_end(document, HTML::HTMLParser::parserless_completion_token(document));
    }

    // AD-HOC: For about:srcdoc, the body bytes are always immediately available in the response source (the srcdoc
    //         string was inlined when the navigation params were created). Bypass the async body-reading pipeline
    //         and set up a deferred parser directly, so the document is parsed as soon as scripts may run for it.
    else if (auto source = navigation_params.response->body_source();
        source.has_value() && document->url() == URL::about_srcdoc()) {
        auto mime_type = Fetch::Infrastructure::extract_mime_type(navigation_params.response->header_list());
        auto url = navigation_params.response->url().value();
        auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, source->bytes(), mime_type);
        document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), GC::captures(parser, url), [](auto& parser, auto& url) {
            parser->run(url);
        }));
    }

    // 3. Otherwise, create an HTML parser whose allow declarative shadow roots is true and associate it with document.
    //
    //    Each task that the networking task source places on the task queue while fetching runs must then fill the
    //    parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate
    //    processing of the input stream.
    //    The first task that the networking task source places on the task queue while fetching runs must process link
    //    headers given document, navigationParams's response, and "media", after the task has been processed by the
    //    HTML parser.
    //    Before any script execution occurs, the user agent must wait for scripts may run for the newly-created
    //    document to be true for document.
    //    When no more bytes are available, the user agent must queue a global task on the networking task source given
    //    document's relevant global object to have the parser to process the implied EOF character, which eventually
    //    causes a load event to be fired.
    else {
        auto container_document = navigation_params.navigable ? navigation_params.navigable->container_document() : nullptr;
        auto parser = HTML::IncrementalDocumentParser::create(document, *navigation_params.response, container_document);
        parser->set_allow_declarative_shadow_roots(HTML::HTMLParser::AllowDeclarativeShadowRoots::Yes);
        parser->start();
    }

    // 4. Return document.
    return document;
}

// https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-xml
static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::NavigationParams const& navigation_params, MimeSniff::MimeType type)
{
    // When faced with displaying an XML file inline, provided navigation params navigationParams and a string type, user agents
    // must follow the requirements defined in XML and Namespaces in XML, XML Media Types, DOM, and other relevant specifications
    // to create and initialize a Document object document, given "xml", type, and navigationParams, and return that Document.
    // They must also create a corresponding XML parser. [XML] [XMLNS] [RFC7303] [DOM]
    //
    // Note: At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.
    //
    // The first task that the networking task source places on the task queue while fetching runs must process link headers
    // given document, navigationParams's response, and "media", after the task has been processed by the XML parser.
    //
    // The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this
    // specification, are the ones that must be used when determining the character encoding according to the rules given in the
    // above specifications. Once the character encoding is established, the document's character encoding must be set to that
    // character encoding.
    //
    // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be
    // true for the newly-created Document.
    //
    // Once parsing is complete, the user agent must set document's during-loading navigation ID for WebDriver BiDi to null.
    //
    // Note: For HTML documents this is reset when parsing is complete, after firing the load event.
    //
    // Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating
    // the Document.

    // FIXME: Actually follow the spec! This is just the ad-hoc code we had before, modified somewhat.

    auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::XML, Utf16FlyString::from_utf8(type.essence()), navigation_params));

    Optional<String> content_encoding;
    if (auto maybe_encoding = type.parameters().get("charset"sv); maybe_encoding.has_value())
        content_encoding = *maybe_encoding;

    auto process_body = GC::create_function(GC::Heap::the(), GC::captures(document, navigation_params.response->url().value(), navigation_params.response->header_list(), move(content_encoding)), [](auto& document, auto& url, auto& response_header_list, auto& content_encoding, ByteBuffer data) {
        auto encoding = determine_xml_encoding(data, content_encoding.has_value() ? Optional<StringView> { content_encoding->bytes_as_string_view() } : OptionalNone {});

        // Once the character encoding is established, the document's character encoding must be set to that character encoding.
        document->set_encoding(Utf16String::from_utf8(encoding));

        // Well-formed XML documents contain only properly encoded characters
        auto source = TextCodec::decode_to_utf8(data, *TextCodec::decoder_for(encoding), TextCodec::ErrorMode::Fatal);
        if (source.is_error()) {
            // FIXME: Insert error message into the document.
            dbgln("Failed to decode XML document: {}", source.error());
            convert_to_xml_error_document(document, Utf16String::formatted("Failed to decode XML document: {}", source.error()));
            return;
        }
        auto run_xml_parser = GC::create_function(GC::Heap::the(), GC::captures(document, url, response_header_list, source.release_value()), [](auto& document, auto& url, auto& response_header_list, auto& source_string) {
            XML::Parser parser(source_string, { .preserve_cdata = true, .preserve_comments = true, .resolve_named_html_entity = resolve_named_html_entity });
            XMLDocumentBuilder builder { *document };
            auto result = parser.parse_with_listener(builder);
            if (result.is_error()) {
                // FIXME: Insert error message into the document.
                dbgln("Failed to parse XML document: {}", result.error());
                convert_to_xml_error_document(document, Utf16String::formatted("Failed to parse XML document: {}", result.error()));
            } else if (builder.has_error()) {
                dbgln("Failed to parse XML document: not namespace-well-formed");
                convert_to_xml_error_document(document, "Failed to parse XML document: not namespace-well-formed"_utf16);
            }
            HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);
        });
        if (document->ready_to_run_scripts()) {
            run_xml_parser->function()();
        } else {
            document->set_deferred_parser_start(run_xml_parser);
        }
    });

    auto process_body_error = GC::create_function(GC::Heap::the(), [](JS::Value) {
        dbgln("FIXME: Load html page with an error if read of body failed.");
    });

    auto& realm = document->relevant_settings_object().realm();
    navigation_params.response->body()->fully_read(realm, process_body, process_body_error, GC::Ref { realm.global_object() });

    return document;
}

// https://html.spec.whatwg.org/multipage/document-lifecycle.html#navigate-text
static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_text_document(HTML::NavigationParams const& navigation_params, MimeSniff::MimeType type)
{
    // To load a text document, given a navigation params navigationParams and a string type:

    // 1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.
    auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, Utf16FlyString::from_utf8(type.essence()), navigation_params));

    // 2. Set document's parser cannot change the mode flag to true.
    document->set_parser_cannot_change_the_mode(true);

    // 3. Set document's mode to "no-quirks".
    document->set_quirks_mode(DOM::QuirksMode::No);

    // 4. Create an HTML parser and associate it with the document. Act as if the tokenizer had emitted a start tag token
    //    with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser's tokenizer
    //    to the PLAINTEXT state. Each task that the networking task source places on the task queue while fetching runs must
    //    then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate
    //    processing of the input stream.
    //    document's encoding must be set to the character encoding used to decode the document during parsing.
    //    The first task that the networking task source places on the task queue while fetching runs must process link
    //    headers given document, navigationParams's response, and "media", after the task has been processed by the HTML parser.
    //    Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be
    //    true for document.
    //    When no more bytes are available, the user agent must queue a global task on the networking task source given
    //    document's relevant global object to have the parser to process the implied EOF character, which eventually causes a
    //    load event to be fired.
    // FIXME: Parse as we receive the document data, instead of waiting for the whole document to be fetched first.
    auto container_document = navigation_params.navigable ? navigation_params.navigable->container_document() : nullptr;
    auto process_body = GC::create_function(GC::Heap::the(), GC::captures(document, container_document, navigation_params.response->url().value(), navigation_params.response->header_list(), type), [](auto& document, auto& container_document, auto& url, auto& response_header_list, auto& mime, ByteBuffer data) {
        // The rules for how to convert the bytes of the plain text document into actual characters, and the rules for
        // actually rendering the text to the user, are defined by the specifications for the computed MIME type of the
        // resource (i.e., type).
        // NB: JSON text is UTF-8 [RFC8259], whatever a BOM or the charset parameter say.
        ByteString encoding;
        Utf16String decoded;
        if (mime.is_json()) {
            encoding = "UTF-8"sv;
            decoded = TextCodec::utf8_decode_to_utf16(data).release_value_but_fixme_should_propagate_errors();
        } else {
            encoding = HTML::run_encoding_sniffing_algorithm(document, data, mime, container_document).encoding;
            dbgln_if(HTML_PARSER_DEBUG, "The encoding sniffing algorithm returned encoding '{}'", encoding);
            auto decoder = TextCodec::decoder_for(encoding);
            VERIFY(decoder.has_value());
            decoded = TextCodec::decode_to_utf16(data, *decoder).release_value_but_fixme_should_propagate_errors();
        }

        auto run_text_parser = GC::create_function(GC::Heap::the(), GC::captures(document, move(decoded), url, response_header_list, move(encoding)), [](auto& document, auto& decoded, auto& url, auto& response_header_list, auto& encoding) {
            auto parser = HTML::HTMLParser::create_with_open_input_stream(document);
            parser->tokenizer().update_insertion_point();

            // NB: The meta element goes to the head, which step 5 below allows, so the text follows the user's color
            //     scheme.
            parser->tokenizer().insert_input_at_insertion_point(u"<meta name=\"color-scheme\" content=\"light dark\"><pre>\n"sv);
            parser->run();

            // AD-HOC: The spec acts as if the tokenizer had emitted a bare "pre" start tag. We give the pre element a
            //         style that wraps long lines, so a line of text never runs off the side of the page. The
            //         Content-Security-Policy of the response must not block that style, so set it directly rather than
            //         through a style attribute.
            if (auto* pre = document->body() ? document->body()->template first_child_of_type<HTML::HTMLPreElement>() : nullptr) {
                auto style = CSS::CSSStyleProperties::create_element_inline_style({ *pre });
                style->set_declarations_from_text(u"word-wrap: break-word; white-space: pre-wrap;"sv);
                pre->set_inline_style(style);
            }

            parser->tokenizer().switch_to(HTML::HTMLTokenizer::State::PLAINTEXT);
            parser->tokenizer().insert_input_at_insertion_point(decoded);
            parser->tokenizer().insert_eof();
            parser->run(url);

            document->set_encoding(Utf16String::from_ascii_without_validation(encoding.bytes()));
            HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);

            // 5. User agents may add content to the head element of document, e.g., linking to a style sheet, providing
            //    script, or giving the document a title.
            // NB: The head holds only the color-scheme meta element added above, so the document text consists only of
            //     the response body.
        });
        if (document->ready_to_run_scripts()) {
            run_text_parser->function()();
        } else {
            document->set_deferred_parser_start(run_text_parser);
        }
    });

    auto process_body_error = GC::create_function(GC::Heap::the(), [](JS::Value) {
        dbgln("FIXME: Load html page with an error if read of body failed.");
    });

    auto& realm = document->relevant_settings_object().realm();
    navigation_params.response->body()->fully_read(realm, process_body, process_body_error, GC::Ref { realm.global_object() });

    // 6. Return document.
    return document;
}

// https://html.spec.whatwg.org/multipage/document-lifecycle.html#navigate-media
static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::NavigationParams const& navigation_params, MimeSniff::MimeType type)
{
    // To load a media document, given navigationParams and a string type:

    // 1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.
    auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, Utf16FlyString::from_utf8(type.essence()), navigation_params));

    // 2. Set document's mode to "no-quirks".
    document->set_quirks_mode(DOM::QuirksMode::No);

    // 3. Populate with html/head/body given document.
    TRY(document->populate_with_html_head_and_body());

    // 4. Append an element host element for the media, as described below, to the body element.
    // 5. Set the appropriate attribute of the element host element, as described below, to the address of the image,
    //    video, or audio resource.
    // 6. User agents may add content to the head element of document, or attributes to host element, e.g., to link
    //    to a style sheet, to provide a script, to give the document a title, or to make the media autoplay.
    auto insert_title = [](auto& document, auto const& document_url) -> WebIDL::ExceptionOr<void> {
        auto title_basename = LexicalPath::basename(document_url.to_byte_string());
        auto title = utf16_string_from_url_ascii(title_basename.view());

        auto title_element = TRY(DOM::create_element(document, HTML::TagNames::title, Namespace::HTML));
        TRY(document->head()->append_child(title_element));

        auto title_text = DOM::Text::create(document, move(title));
        TRY(title_element->append_child(*title_text));
        return {};
    };

    // NB: The Content-Security-Policy of the response applies to document, but must not block the user agent's own
    //     styles. So set these declarations directly, not through a style element or attribute.
    auto set_host_element_style = [](DOM::Element& element, Utf16View declarations) {
        auto style = CSS::CSSStyleProperties::create_element_inline_style({ element });
        style->set_declarations_from_text(declarations);
        element.set_inline_style(style);
    };
    set_host_element_style(*document->document_element(), u"background-color: #222;"sv);
    auto host_element_style = u"position: absolute; inset: 0; max-width: 100vw; max-height: 100vh; margin: auto;"sv;

    auto url_string = document->url().to_string();
    auto url_utf16 = utf16_string_from_url_ascii(url_string);
    GC::Ptr<HTML::HTMLImageElement> image_element;
    if (type.is_image()) {
        auto img_element = TRY(DOM::create_element(document, HTML::TagNames::img, Namespace::HTML));
        image_element = as<HTML::HTMLImageElement>(*img_element);
        // Auto margins center an image that fits and keep overflow reachable from the top-left corner.
        set_host_element_style(*document->body(), u"display: flex; min-height: 100vh; margin: 0;"sv);
        set_host_element_style(img_element, u"flex: none; max-width: 100vw; max-height: 100vh; margin: auto; background-color: hsl(0, 0%, 90%);"sv);
        img_element->set_attribute_value(HTML::AttributeNames::src, url_utf16);
        TRY(document->body()->append_child(img_element));
        TRY(insert_title(document, url_string));

    } else if (type.type() == "video"sv) {
        auto video_element = TRY(DOM::create_element(document, HTML::TagNames::video, Namespace::HTML));
        set_host_element_style(video_element, host_element_style);
        video_element->set_attribute_value(HTML::AttributeNames::src, url_utf16);
        video_element->set_attribute_value(HTML::AttributeNames::autoplay, Utf16String {});
        video_element->set_attribute_value(HTML::AttributeNames::controls, Utf16String {});
        TRY(document->body()->append_child(video_element));
        TRY(insert_title(document, url_string));

    } else if (type.type() == "audio"sv) {
        auto audio_element = TRY(DOM::create_element(document, HTML::TagNames::audio, Namespace::HTML));
        set_host_element_style(audio_element, host_element_style);
        audio_element->set_attribute_value(HTML::AttributeNames::src, url_utf16);
        audio_element->set_attribute_value(HTML::AttributeNames::autoplay, Utf16String {});
        audio_element->set_attribute_value(HTML::AttributeNames::controls, Utf16String {});
        TRY(document->body()->append_child(audio_element));
        TRY(insert_title(document, url_string));

    } else {
        // FIXME: According to https://mimesniff.spec.whatwg.org/#audio-or-video-mime-type we might have to deal with
        //        "application/ogg" and figure out whether it's audio or video.
        VERIFY_NOT_REACHED();
    }

    auto& realm = document->relevant_settings_object().realm();

    // 7. Process link headers given document, navigationParams's response, and "media".
    // AD-HOC: document has no navigable until it is activated, so media queries would be evaluated against an empty
    //         viewport. Process the link headers in a networking task instead, which runs once document is fully active
    //         and before the task that step 8 queues when the body has been read.
    HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(document, navigation_params.response->header_list(), navigation_params.response->url().value()), [](auto& document, auto& response_header_list, auto& url) {
        HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);
    }));

    // 8. Act as if the user agent had stopped parsing document.
    // FIXME: We should not need to force the media file to load before saying that parsing has completed!
    //        However, if we don't, then we get stuck in HTMLParser::the_end() waiting for the media file to load, which
    //        never happens.
    auto stop_parsing = GC::create_function(GC::Heap::the(), GC::captures(document), [](auto& document) { HTML::HTMLParser::the_end(document, nullptr); });
    if (image_element) {
        // INTEROP: All major engines present the image from the response that was navigated to rather than fetching it
        //          again. A second fetch would be subject to the Content-Security-Policy of that same response.
        image_element->set_resource_from_navigation_response(HTML::SharedResourceRequest::create_from_image_response_body(document, document->url(), *navigation_params.response->body(), false, stop_parsing));
    } else {
        navigation_params.response->body()->fully_read(
            realm,
            GC::create_function(GC::Heap::the(), GC::captures(stop_parsing), [](auto& stop_parsing, ByteBuffer) { stop_parsing->function()(); }),
            GC::create_function(GC::Heap::the(), [](JS::Value) { }),
            GC::Ref { realm.global_object() });
    }

    // 9. Return document.
    return document;

    // The element host element to create for the media is the element given in the table below in the second cell of
    // the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell
    // in that same row.
    // Type of media | Element for the media | Appropriate attribute
    // -------------------------------------------------------------
    // Image         | img                   | src
    // Video         | video                 | src
    // Audio         | audio                 | src

    // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to
    // be true for the Document.
}

// Renders the PDF using the bundled pdf.js viewer at an internal resource:// URL.
static GC::Ref<DOM::Document> load_pdf_document(HTML::NavigationParams const& navigation_params)
{
    VERIFY(navigation_params.response->url().has_value());
    auto pdf_url = navigation_params.response->url().value();

    static NeverDestroyed<ByteBuffer> viewer_bytes { MUST(Core::Resource::load_from_uri("resource://ladybird/pdfjs/web/viewer.html"sv))->clone_data() };

    auto document = MUST(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_utf16_fly_string, navigation_params));
    // The viewer is the user agent's own page, which brings its own CSP. The PDF response's policies are for the PDF,
    // and would stop the viewer — a base-uri or script-src directive alone refuses its resources. So the viewer gets a
    // new policy container, which keeps only the insecure requests policy inherited from the container document.
    auto policy_container = HTML::PolicyContainer::create();
    if (navigation_params.navigable->parent()) {
        auto container_state = navigation_params.navigable->container_state();
        policy_container->inherit_insecure_requests_policy(container_state.document_insecure_requests_policy, container_state.document_upgrade_insecure_navigations_set);
    }
    document->set_policy_container(policy_container);

    // The sandboxing flags of the PDF response's CSP would stop the viewer's scripts too, so the viewer keeps only the
    // sandboxing flags that don't come from the response.
    document->set_active_sandboxing_flag_set(navigation_params.final_sandboxing_flag_set & HTML::determine_the_creation_sandboxing_flags(*document->browsing_context(), *navigation_params.navigable));

    add_pdf_viewer_ready_listener(document, GC::Ref(*navigation_params.response));

    Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(document, pdf_url), [](auto& document, auto& pdf_url) {
        auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, *viewer_bytes);
        if (document->ready_to_run_scripts()) {
            parser->run(pdf_url);
        } else {
            document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), GC::captures(parser, pdf_url), [](auto& parser, auto& pdf_url) {
                parser->run(pdf_url);
            }));
        }
    }));

    return document;
}

bool can_load_document_with_type(MimeSniff::MimeType const& type)
{
    if (type.is_html())
        return true;
    if (type.is_xml())
        return true;
    if (type.is_javascript()
        || type.is_json()
        || type.essence() == "text/css"_string
        || type.essence() == "text/plain"_string
        || type.essence() == "text/vtt"_string) {
        return true;
    }
    if (type.essence() == "multipart/x-mixed-replace"_string)
        return true;
    if (type.is_image() || type.is_audio_or_video())
        return true;
    if (type.essence() == "application/pdf"_string || type.essence() == "text/pdf"_string)
        return true;
    if (type.essence() == "text/markdown"sv)
        return true;
    return false;
}

// https://html.spec.whatwg.org/multipage/browsing-the-web.html#loading-a-document
// AD-HOC: This returns the document to create in place of the Document, which is created once navigationParams's
//         navigable's active document is unloaded.
GC::Ptr<HTML::DocumentToCreate> load_document(GC::Ref<HTML::NavigationParams> navigation_params, ReadonlyBytes sniff_bytes)
{
    // To load a document given navigation params navigationParams, source snapshot params sourceSnapshotParams,
    // and origin initiatorOrigin, perform the following steps. They return a Document or null.

    // 1. Let type be the computed type of navigationParams's response.
    auto supplied_type = Fetch::Infrastructure::extract_mime_type(navigation_params->response->header_list());
    auto type = MimeSniff::Resource::sniff(
        sniff_bytes,
        MimeSniff::SniffingConfiguration {
            .sniffing_context = MimeSniff::SniffingContext::Browsing,
            .supplied_type = move(supplied_type) });

    VERIFY(navigation_params->response->body());

    // 2. If the user agent has been configured to process resources of the given type using some mechanism other than
    //    rendering the content in a navigable, then skip this step.
    //    Otherwise, if the type is one of the following types:

    // -> an HTML MIME type
    if (type.is_html()) {
        // Return the result of loading an HTML document, given navigationParams.
        return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), [](HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {
            return load_html_document(navigation_params).release_value_but_fixme_should_propagate_errors();
        }));
    }

    // -> an XML MIME type that is not an explicitly supported XML MIME type
    //    FIXME: that is not an explicitly supported XML MIME type
    if (type.is_xml()) {
        // Return the result of loading an XML document given navigationParams and type.
        return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(type), [](auto& type, HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {
            return load_xml_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();
        }));
    }

    // -> a JavaScript MIME type
    // -> a JSON MIME type that is not an explicitly supported JSON MIME type
    // -> "text/css"
    // -> "text/plain"
    // -> "text/vtt"
    if (type.is_javascript()
        || type.is_json()
        || type.essence() == "text/css"_string
        || type.essence() == "text/plain"_string
        || type.essence() == "text/vtt"_string) {
        // Return the result of loading a text document given navigationParams and type.
        return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(type), [](auto& type, HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {
            return load_text_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();
        }));
    }

    // -> "multipart/x-mixed-replace"
    if (type.essence() == "multipart/x-mixed-replace"_string) {
        // FIXME: Return the result of loading a multipart/x-mixed-replace document, given navigationParams,
        //        sourceSnapshotParams, and initiatorOrigin.
    }

    // -> a supported image, video, or audio type
    if (type.is_image()
        || type.is_audio_or_video()) {
        // Return the result of loading a media document given navigationParams and type.
        return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(type), [](auto& type, HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {
            return load_media_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();
        }));
    }

    // -> "application/pdf"
    // -> "text/pdf"
    if (type.essence() == "application/pdf"_string
        || type.essence() == "text/pdf"_string) {
        // AD-HOC: The PDF viewer runs with an origin of its own.
        return HTML::DocumentToCreate::create(
            navigation_params, GC::create_function(GC::Heap::the(), [](HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {
                return load_pdf_document(navigation_params);
            }),
            URL::Origin("resource"_string, String {}, {}));
    }

    // Otherwise, proceed onward.

    // FIXME: 3. If, given type, the new resource is to be handled by displaying some sort of inline content, e.g., a
    //    native rendering of the content or an error message because the specified type is not supported, then
    //    return the result of creating a document for inline content that doesn't have a DOM given navigationParams's
    //    navigable, navigationParams's id, navigationParams's navigation timing type, and navigationParams's user involvement.

    // FIXME: 4. Otherwise, the document's type is such that the resource will not affect navigationParams's navigable,
    //        e.g., because the resource is to be handed to an external application or because it is an unknown type
    //        that will be processed by handle as a download. Hand-off to external software given navigationParams's
    //        response, navigationParams's navigable, navigationParams's final sandboxing flag set,
    //        sourceSnapshotParams's has transient activation, and initiatorOrigin.

    // 5. Return null.
    return nullptr;
}

}