<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::document_loader::LoadType;
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use crate::dom::bindings::codegen::Bindings::HTMLScriptElementBinding;
use crate::dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::document::Document;
use crate::dom::element::{
    cors_setting_for_element, reflect_cross_origin_attribute, set_cross_origin_attribute,
};
use crate::dom::element::{AttributeMutation, Element, ElementCreator};
use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::{document_from_node, window_from_node};
use crate::dom::node::{BindContext, ChildrenMutation, CloneChildrenFlag, Node};
use crate::dom::performanceresourcetiming::InitiatorType;
use crate::dom::virtualmethods::VirtualMethods;
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use dom_struct::dom_struct;
use encoding_rs::Encoding;
use html5ever::{LocalName, Prefix};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::jsval::UndefinedValue;
use net_traits::request::{
    CorsSettings, CredentialsMode, Destination, Referrer, RequestBuilder, RequestMode,
};
use net_traits::{FetchMetadata, FetchResponseListener, Metadata, NetworkError};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use style::str::{StaticStringVec, HTML_SPACE_CHARACTERS};
use uuid::Uuid;

#[dom_struct]
pub struct HTMLScriptElement {
    htmlelement: HTMLElement,

    /// <https://html.spec.whatwg.org/multipage/#already-started>
    already_started: Cell<bool>,

    /// <https://html.spec.whatwg.org/multipage/#parser-inserted>
    parser_inserted: Cell<bool>,

    /// <https://html.spec.whatwg.org/multipage/#non-blocking>
    ///
    /// (currently unused)
    non_blocking: Cell<bool>,

    /// Document of the parser that created this element
    parser_document: Dom<Document>,

    /// Track line line_number
    line_number: u64,
}

impl HTMLScriptElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
        creator: ElementCreator,
    ) -> HTMLScriptElement {
        HTMLScriptElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
            already_started: Cell::new(false),
            parser_inserted: Cell::new(creator.is_parser_created()),
            non_blocking: Cell::new(!creator.is_parser_created()),
            parser_document: Dom::from_ref(document),
            line_number: creator.return_line_number(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
        creator: ElementCreator,
    ) -> DomRoot<HTMLScriptElement> {
        Node::reflect_node(
            Box::new(HTMLScriptElement::new_inherited(
                local_name, prefix, document, creator,
            )),
            document,
            HTMLScriptElementBinding::Wrap,
        )
    }
}

/// Supported script types as defined by
/// <https://html.spec.whatwg.org/multipage/#javascript-mime-type>.
static SCRIPT_JS_MIMES: StaticStringVec = &[
    "application/ecmascript",
    "application/javascript",
    "application/x-ecmascript",
    "application/x-javascript",
    "text/ecmascript",
    "text/javascript",
    "text/javascript1.0",
    "text/javascript1.1",
    "text/javascript1.2",
    "text/javascript1.3",
    "text/javascript1.4",
    "text/javascript1.5",
    "text/jscript",
    "text/livescript",
    "text/x-ecmascript",
    "text/x-javascript",
];

pub enum ScriptType {
    Classic,
    Module,
}

#[derive(JSTraceable, MallocSizeOf)]
pub struct ScriptOrigin {
    text: DOMString,
    url: ServoUrl,
    external: bool,
}

impl ScriptOrigin {
    fn internal(text: DOMString, url: ServoUrl) -> ScriptOrigin {
        ScriptOrigin {
            text: text,
            url: url,
            external: false,
        }
    }

    fn external(text: DOMString, url: ServoUrl) -> ScriptOrigin {
        ScriptOrigin {
            text: text,
            url: url,
            external: true,
        }
    }
}

pub type ScriptResult = Result<ScriptOrigin, NetworkError>;

/// The context required for asynchronously loading an external script source.
struct ClassicContext {
    /// The element that initiated the request.
    elem: Trusted<HTMLScriptElement>,
    /// The kind of external script.
    kind: ExternalScriptKind,
    /// The (fallback) character encoding argument to the "fetch a classic
    /// script" algorithm.
    character_encoding: &'static Encoding,
    /// The response body received to date.
    data: Vec<u8>,
    /// The response metadata received to date.
    metadata: Option<Metadata>,
    /// The initial URL requested.
    url: ServoUrl,
    /// Indicates whether the request failed, and why
    status: Result<(), NetworkError>,
    /// Timing object for this resource
    resource_timing: ResourceFetchTiming,
}

impl FetchResponseListener for ClassicContext {
    fn process_request_body(&mut self) {} // TODO(KiChjang): Perhaps add custom steps to perform fetch here?

    fn process_request_eof(&mut self) {} // TODO(KiChjang): Perhaps add custom steps to perform fetch here?

    fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
        self.metadata = metadata.ok().map(|meta| match meta {
            FetchMetadata::Unfiltered(m) => m,
            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
        });

        let status_code = self
            .metadata
            .as_ref()
            .and_then(|m| match m.status {
                Some((c, _)) => Some(c),
                _ => None,
            })
            .unwrap_or(0);

        self.status = match status_code {
            0 => Err(NetworkError::Internal(
                "No http status code received".to_owned(),
            )),
            200..=299 => Ok(()), // HTTP ok status codes
            _ => Err(NetworkError::Internal(format!(
                "HTTP error code {}",
                status_code
            ))),
        };
    }

    fn process_response_chunk(&mut self, mut chunk: Vec<u8>) {
        if self.status.is_ok() {
            self.data.append(&mut chunk);
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
    /// step 4-9
    fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) {
        // Step 5.
        let load = response.and(self.status.clone()).map(|_| {
            let metadata = self.metadata.take().unwrap();

            // Step 6.
            let encoding = metadata
                .charset
                .and_then(|encoding| Encoding::for_label(encoding.as_bytes()))
                .unwrap_or(self.character_encoding);

            // Step 7.
            let (source_text, _, _) = encoding.decode(&self.data);
            ScriptOrigin::external(DOMString::from(source_text), metadata.final_url)
        });

        // Step 9.
        // https://html.spec.whatwg.org/multipage/#prepare-a-script
        // Step 18.6 (When the chosen algorithm asynchronously completes).
        let elem = self.elem.root();
        let document = document_from_node(&*elem);

        match self.kind {
            ExternalScriptKind::Asap => document.asap_script_loaded(&elem, load),
            ExternalScriptKind::AsapInOrder => document.asap_in_order_script_loaded(&elem, load),
            ExternalScriptKind::Deferred => document.deferred_script_loaded(&elem, load),
            ExternalScriptKind::ParsingBlocking => {
                document.pending_parsing_blocking_script_loaded(&elem, load)
            },
        }

        document.finish_load(LoadType::Script(self.url.clone()));
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        network_listener::submit_timing(self)
    }
}

impl ResourceTimingListener for ClassicContext {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        let initiator_type = InitiatorType::LocalName(
            self.elem
                .root()
                .upcast::<Element>()
                .local_name()
                .to_string(),
        );
        (initiator_type, self.url.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        (document_from_node(&*self.elem.root()).global())
    }
}

impl PreInvoke for ClassicContext {}

/// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
fn fetch_a_classic_script(
    script: &HTMLScriptElement,
    kind: ExternalScriptKind,
    url: ServoUrl,
    cors_setting: Option<CorsSettings>,
    integrity_metadata: String,
    character_encoding: &'static Encoding,
) {
    let doc = document_from_node(script);

    // Step 1, 2.
    let request = RequestBuilder::new(url.clone())
        .destination(Destination::Script)
        // https://html.spec.whatwg.org/multipage/#create-a-potential-cors-request
        // Step 1
        .mode(match cors_setting {
            Some(_) => RequestMode::CorsMode,
            None => RequestMode::NoCors,
        })
        // https://html.spec.whatwg.org/multipage/#create-a-potential-cors-request
        // Step 3-4
        .credentials_mode(match cors_setting {
            Some(CorsSettings::Anonymous) => CredentialsMode::CredentialsSameOrigin,
            _ => CredentialsMode::Include,
        })
        .origin(doc.origin().immutable().clone())
        .pipeline_id(Some(script.global().pipeline_id()))
        .referrer(Some(Referrer::ReferrerUrl(doc.url())))
        .referrer_policy(doc.get_referrer_policy())
        .integrity_metadata(integrity_metadata);

    // TODO: Step 3, Add custom steps to perform fetch

    let context = Arc::new(Mutex::new(ClassicContext {
        elem: Trusted::new(script),
        kind: kind,
        character_encoding: character_encoding,
        data: vec![],
        metadata: None,
        url: url.clone(),
        status: Ok(()),
        resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
    }));

    let (action_sender, action_receiver) = ipc::channel().unwrap();
    let (task_source, canceller) = doc
        .window()
        .task_manager()
        .networking_task_source_with_canceller();
    let listener = NetworkListener {
        context,
        task_source,
        canceller: Some(canceller),
    };

    ROUTER.add_route(
        action_receiver.to_opaque(),
        Box::new(move |message| {
            listener.notify_fetch(message.to().unwrap());
        }),
    );
    doc.fetch_async(LoadType::Script(url), request, action_sender);
}

impl HTMLScriptElement {
    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script>
    pub fn prepare(&self) {
        // Step 1.
        if self.already_started.get() {
            return;
        }

        // Step 2.
        let was_parser_inserted = self.parser_inserted.get();
        self.parser_inserted.set(false);

        // Step 3.
        let element = self.upcast::<Element>();
        let r#async = element.has_attribute(&local_name!("async"));
        // Note: confusingly, this is done if the element does *not* have an "async" attribute.
        if was_parser_inserted && !r#async {
            self.non_blocking.set(true);
        }

        // Step 4-5.
        let text = self.Text();
        if text.is_empty() && !element.has_attribute(&local_name!("src")) {
            return;
        }

        // Step 6.
        if !self.upcast::<Node>().is_connected() {
            return;
        }

        let _script_type = if let Some(ty) = self.get_script_type() {
            ty
        } else {
            // Step 7.
            return;
        };

        // Step 8.
        if was_parser_inserted {
            self.parser_inserted.set(true);
            self.non_blocking.set(false);
        }

        // Step 9.
        self.already_started.set(true);

        // Step 10.
        let doc = document_from_node(self);
        if self.parser_inserted.get() && &*self.parser_document != &*doc {
            return;
        }

        // Step 11.
        if !doc.is_scripting_enabled() {
            return;
        }

        // TODO: Step 12: nomodule content attribute

        // TODO(#4577): Step 13: CSP.

        // Step 14.
        let for_attribute = element.get_attribute(&ns!(), &local_name!("for"));
        let event_attribute = element.get_attribute(&ns!(), &local_name!("event"));
        match (for_attribute, event_attribute) {
            (Some(ref for_attribute), Some(ref event_attribute)) => {
                let for_value = for_attribute.value().to_ascii_lowercase();
                let for_value = for_value.trim_matches(HTML_SPACE_CHARACTERS);
                if for_value != "window" {
                    return;
                }

                let event_value = event_attribute.value().to_ascii_lowercase();
                let event_value = event_value.trim_matches(HTML_SPACE_CHARACTERS);
                if event_value != "onload" && event_value != "onload()" {
                    return;
                }
            },
            (_, _) => (),
        }

        // Step 15.
        let encoding = element
            .get_attribute(&ns!(), &local_name!("charset"))
            .and_then(|charset| Encoding::for_label(charset.value().as_bytes()))
            .unwrap_or_else(|| doc.encoding());

        // Step 16.
        let cors_setting = cors_setting_for_element(element);

        // TODO: Step 17: Module script credentials mode.

        // TODO: Step 18: Nonce.

        // Step 19: Integrity metadata.
        let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity"));
        let integrity_val = im_attribute.as_ref().map(|a| a.value());
        let integrity_metadata = match integrity_val {
            Some(ref value) => &***value,
            None => "",
        };

        // TODO: Step 20: referrer policy

        // TODO: Step 21: parser state.

        // TODO: Step 22: Fetch options

        // TODO: Step 23: environment settings object.

        let base_url = doc.base_url();
        if let Some(src) = element.get_attribute(&ns!(), &local_name!("src")) {
            // Step 24.

            // Step 24.1.
            let src = src.value();

            // Step 24.2.
            if src.is_empty() {
                self.queue_error_event();
                return;
            }

            // Step 24.3: The "from an external file"" flag is stored in ScriptOrigin.

            // Step 24.4-24.5.
            let url = match base_url.join(&src) {
                Ok(url) => url,
                Err(_) => {
                    warn!("error parsing URL for script {}", &**src);
                    self.queue_error_event();
                    return;
                },
            };

            // Preparation for step 26.
            let kind = if element.has_attribute(&local_name!("defer")) &&
                was_parser_inserted &&
                !r#async
            {
                // Step 26.a: classic, has src, has defer, was parser-inserted, is not async.
                ExternalScriptKind::Deferred
            } else if was_parser_inserted && !r#async {
                // Step 26.c: classic, has src, was parser-inserted, is not async.
                ExternalScriptKind::ParsingBlocking
            } else if !r#async && !self.non_blocking.get() {
                // Step 26.d: classic, has src, is not async, is not non-blocking.
                ExternalScriptKind::AsapInOrder
            } else {
                // Step 26.f: classic, has src.
                ExternalScriptKind::Asap
            };

            // Step 24.6.
            fetch_a_classic_script(
                self,
                kind,
                url,
                cors_setting,
                integrity_metadata.to_owned(),
                encoding,
            );

            // Step 23.
            match kind {
                ExternalScriptKind::Deferred => doc.add_deferred_script(self),
                ExternalScriptKind::ParsingBlocking => {
                    doc.set_pending_parsing_blocking_script(self, None)
                },
                ExternalScriptKind::AsapInOrder => doc.push_asap_in_order_script(self),
                ExternalScriptKind::Asap => doc.add_asap_script(self),
            }
        } else {
            // Step 25.
            assert!(!text.is_empty());
            // Step 25-1.
            let result = Ok(ScriptOrigin::internal(text, base_url));

            // TODO: Step 25-2.

            // Step 26.
            if was_parser_inserted &&
                doc.get_current_parser()<commit_msg>Add `type_` for script origin to distinguish module or classic<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::document_loader::LoadType;
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use crate::dom::bindings::codegen::Bindings::HTMLScriptElementBinding;
use crate::dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::document::Document;
use crate::dom::element::{
    cors_setting_for_element, reflect_cross_origin_attribute, set_cross_origin_attribute,
};
use crate::dom::element::{AttributeMutation, Element, ElementCreator};
use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::{document_from_node, window_from_node};
use crate::dom::node::{BindContext, ChildrenMutation, CloneChildrenFlag, Node};
use crate::dom::performanceresourcetiming::InitiatorType;
use crate::dom::virtualmethods::VirtualMethods;
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use dom_struct::dom_struct;
use encoding_rs::Encoding;
use html5ever::{LocalName, Prefix};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::jsval::UndefinedValue;
use net_traits::request::{
    CorsSettings, CredentialsMode, Destination, Referrer, RequestBuilder, RequestMode,
};
use net_traits::{FetchMetadata, FetchResponseListener, Metadata, NetworkError};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use style::str::{StaticStringVec, HTML_SPACE_CHARACTERS};
use uuid::Uuid;

#[dom_struct]
pub struct HTMLScriptElement {
    htmlelement: HTMLElement,

    /// <https://html.spec.whatwg.org/multipage/#already-started>
    already_started: Cell<bool>,

    /// <https://html.spec.whatwg.org/multipage/#parser-inserted>
    parser_inserted: Cell<bool>,

    /// <https://html.spec.whatwg.org/multipage/#non-blocking>
    ///
    /// (currently unused)
    non_blocking: Cell<bool>,

    /// Document of the parser that created this element
    parser_document: Dom<Document>,

    /// Track line line_number
    line_number: u64,
}

impl HTMLScriptElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
        creator: ElementCreator,
    ) -> HTMLScriptElement {
        HTMLScriptElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
            already_started: Cell::new(false),
            parser_inserted: Cell::new(creator.is_parser_created()),
            non_blocking: Cell::new(!creator.is_parser_created()),
            parser_document: Dom::from_ref(document),
            line_number: creator.return_line_number(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
        creator: ElementCreator,
    ) -> DomRoot<HTMLScriptElement> {
        Node::reflect_node(
            Box::new(HTMLScriptElement::new_inherited(
                local_name, prefix, document, creator,
            )),
            document,
            HTMLScriptElementBinding::Wrap,
        )
    }
}

/// Supported script types as defined by
/// <https://html.spec.whatwg.org/multipage/#javascript-mime-type>.
static SCRIPT_JS_MIMES: StaticStringVec = &[
    "application/ecmascript",
    "application/javascript",
    "application/x-ecmascript",
    "application/x-javascript",
    "text/ecmascript",
    "text/javascript",
    "text/javascript1.0",
    "text/javascript1.1",
    "text/javascript1.2",
    "text/javascript1.3",
    "text/javascript1.4",
    "text/javascript1.5",
    "text/jscript",
    "text/livescript",
    "text/x-ecmascript",
    "text/x-javascript",
];

#[derive(JSTraceable, MallocSizeOf)]
pub enum ScriptType {
    Classic,
    Module,
}

#[derive(JSTraceable, MallocSizeOf)]
pub struct ScriptOrigin {
    text: DOMString,
    url: ServoUrl,
    external: bool,
    type_: ScriptType,
}

impl ScriptOrigin {
    fn internal(text: DOMString, url: ServoUrl, type_: ScriptType) -> ScriptOrigin {
        ScriptOrigin {
            text: text,
            url: url,
            external: false,
            type_,
        }
    }

    fn external(text: DOMString, url: ServoUrl, type_: ScriptType) -> ScriptOrigin {
        ScriptOrigin {
            text: text,
            url: url,
            external: true,
            type_,
        }
    }
}

pub type ScriptResult = Result<ScriptOrigin, NetworkError>;

/// The context required for asynchronously loading an external script source.
struct ClassicContext {
    /// The element that initiated the request.
    elem: Trusted<HTMLScriptElement>,
    /// The kind of external script.
    kind: ExternalScriptKind,
    /// The (fallback) character encoding argument to the "fetch a classic
    /// script" algorithm.
    character_encoding: &'static Encoding,
    /// The response body received to date.
    data: Vec<u8>,
    /// The response metadata received to date.
    metadata: Option<Metadata>,
    /// The initial URL requested.
    url: ServoUrl,
    /// Indicates whether the request failed, and why
    status: Result<(), NetworkError>,
    /// Timing object for this resource
    resource_timing: ResourceFetchTiming,
}

impl FetchResponseListener for ClassicContext {
    fn process_request_body(&mut self) {} // TODO(KiChjang): Perhaps add custom steps to perform fetch here?

    fn process_request_eof(&mut self) {} // TODO(KiChjang): Perhaps add custom steps to perform fetch here?

    fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
        self.metadata = metadata.ok().map(|meta| match meta {
            FetchMetadata::Unfiltered(m) => m,
            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
        });

        let status_code = self
            .metadata
            .as_ref()
            .and_then(|m| match m.status {
                Some((c, _)) => Some(c),
                _ => None,
            })
            .unwrap_or(0);

        self.status = match status_code {
            0 => Err(NetworkError::Internal(
                "No http status code received".to_owned(),
            )),
            200..=299 => Ok(()), // HTTP ok status codes
            _ => Err(NetworkError::Internal(format!(
                "HTTP error code {}",
                status_code
            ))),
        };
    }

    fn process_response_chunk(&mut self, mut chunk: Vec<u8>) {
        if self.status.is_ok() {
            self.data.append(&mut chunk);
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
    /// step 4-9
    fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) {
        // Step 5.
        let load = response.and(self.status.clone()).map(|_| {
            let metadata = self.metadata.take().unwrap();

            // Step 6.
            let encoding = metadata
                .charset
                .and_then(|encoding| Encoding::for_label(encoding.as_bytes()))
                .unwrap_or(self.character_encoding);

            // Step 7.
            let (source_text, _, _) = encoding.decode(&self.data);
            ScriptOrigin::external(
                DOMString::from(source_text),
                metadata.final_url,
                ScriptType::Classic,
            )
        });

        // Step 9.
        // https://html.spec.whatwg.org/multipage/#prepare-a-script
        // Step 18.6 (When the chosen algorithm asynchronously completes).
        let elem = self.elem.root();
        let document = document_from_node(&*elem);

        match self.kind {
            ExternalScriptKind::Asap => document.asap_script_loaded(&elem, load),
            ExternalScriptKind::AsapInOrder => document.asap_in_order_script_loaded(&elem, load),
            ExternalScriptKind::Deferred => document.deferred_script_loaded(&elem, load),
            ExternalScriptKind::ParsingBlocking => {
                document.pending_parsing_blocking_script_loaded(&elem, load)
            },
        }

        document.finish_load(LoadType::Script(self.url.clone()));
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        network_listener::submit_timing(self)
    }
}

impl ResourceTimingListener for ClassicContext {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        let initiator_type = InitiatorType::LocalName(
            self.elem
                .root()
                .upcast::<Element>()
                .local_name()
                .to_string(),
        );
        (initiator_type, self.url.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        (document_from_node(&*self.elem.root()).global())
    }
}

impl PreInvoke for ClassicContext {}

/// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
fn fetch_a_classic_script(
    script: &HTMLScriptElement,
    kind: ExternalScriptKind,
    url: ServoUrl,
    cors_setting: Option<CorsSettings>,
    integrity_metadata: String,
    character_encoding: &'static Encoding,
) {
    let doc = document_from_node(script);

    // Step 1, 2.
    let request = RequestBuilder::new(url.clone())
        .destination(Destination::Script)
        // https://html.spec.whatwg.org/multipage/#create-a-potential-cors-request
        // Step 1
        .mode(match cors_setting {
            Some(_) => RequestMode::CorsMode,
            None => RequestMode::NoCors,
        })
        // https://html.spec.whatwg.org/multipage/#create-a-potential-cors-request
        // Step 3-4
        .credentials_mode(match cors_setting {
            Some(CorsSettings::Anonymous) => CredentialsMode::CredentialsSameOrigin,
            _ => CredentialsMode::Include,
        })
        .origin(doc.origin().immutable().clone())
        .pipeline_id(Some(script.global().pipeline_id()))
        .referrer(Some(Referrer::ReferrerUrl(doc.url())))
        .referrer_policy(doc.get_referrer_policy())
        .integrity_metadata(integrity_metadata);

    // TODO: Step 3, Add custom steps to perform fetch

    let context = Arc::new(Mutex::new(ClassicContext {
        elem: Trusted::new(script),
        kind: kind,
        character_encoding: character_encoding,
        data: vec![],
        metadata: None,
        url: url.clone(),
        status: Ok(()),
        resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
    }));

    let (action_sender, action_receiver) = ipc::channel().unwrap();
    let (task_source, canceller) = doc
        .window()
        .task_manager()
        .networking_task_source_with_canceller();
    let listener = NetworkListener {
        context,
        task_source,
        canceller: Some(canceller),
    };

    ROUTER.add_route(
        action_receiver.to_opaque(),
        Box::new(move |message| {
            listener.notify_fetch(message.to().unwrap());
        }),
    );
    doc.fetch_async(LoadType::Script(url), request, action_sender);
}

impl HTMLScriptElement {
    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script>
    pub fn prepare(&self) {
        // Step 1.
        if self.already_started.get() {
            return;
        }

        // Step 2.
        let was_parser_inserted = self.parser_inserted.get();
        self.parser_inserted.set(false);

        // Step 3.
        let element = self.upcast::<Element>();
        let r#async = element.has_attribute(&local_name!("async"));
        // Note: confusingly, this is done if the element does *not* have an "async" attribute.
        if was_parser_inserted && !r#async {
            self.non_blocking.set(true);
        }

        // Step 4-5.
        let text = self.Text();
        if text.is_empty() && !element.has_attribute(&local_name!("src")) {
            return;
        }

        // Step 6.
        if !self.upcast::<Node>().is_connected() {
            return;
        }

        let _script_type = if let Some(ty) = self.get_script_type() {
            ty
        } else {
            // Step 7.
            return;
        };

        // Step 8.
        if was_parser_inserted {
            self.parser_inserted.set(true);
            self.non_blocking.set(false);
        }

        // Step 9.
        self.already_started.set(true);

        // Step 10.
        let doc = document_from_node(self);
        if self.parser_inserted.get() && &*self.parser_document != &*doc {
            return;
        }

        // Step 11.
        if !doc.is_scripting_enabled() {
            return;
        }

        // TODO: Step 12: nomodule content attribute

        // TODO(#4577): Step 13: CSP.

        // Step 14.
        let for_attribute = element.get_attribute(&ns!(), &local_name!("for"));
        let event_attribute = element.get_attribute(&ns!(), &local_name!("event"));
        match (for_attribute, event_attribute) {
            (Some(ref for_attribute), Some(ref event_attribute)) => {
                let for_value = for_attribute.value().to_ascii_lowercase();
                let for_value = for_value.trim_matches(HTML_SPACE_CHARACTERS);
                if for_value != "window" {
                    return;
                }

                let event_value = event_attribute.value().to_ascii_lowercase();
                let event_value = event_value.trim_matches(HTML_SPACE_CHARACTERS);
                if event_value != "onload" && event_value != "onload()" {
                    return;
                }
            },
            (_, _) => (),
        }

        // Step 15.
        let encoding = element
            .get_attribute(&ns!(), &local_name!("charset"))
            .and_then(|charset| Encoding::for_label(charset.value().as_bytes()))
            .unwrap_or_else(|| doc.encoding());

        // Step 16.
        let cors_setting = cors_setting_for_element(element);

        // TODO: Step 17: Module script credentials mode.

        // TODO: Step 18: Nonce.

        // Step 19: Integrity metadata.
        let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity"));
        let integrity_val = im_attribute.as_ref().map(|a| a.value());
        let integrity_metadata = match integrity_val {
            Some(ref value) => &***value,
            None => "",
        };

        // TODO: Step 20: referrer policy

        // TODO: Step 21: parser state.

        // TODO: Step 22: Fetch options

        // TODO: Step 23: environment settings object.

        let base_url = doc.base_url();
        if let Some(src) = element.get_attribute(&ns!(), &local_name!("src")) {
            // Step 24.

            // Step 24.1.
            let src = src.value();

            // Step 24.2.
            if src.is_empty() {
                self.queue_error_event();
                return;
            }

            // Step 24.3: The "from an external file"" flag is stored in ScriptOrigin.

            // Step 24.4-24.5.
            let url = match base_url.join(&src) {
                Ok(url) => url,
                Err(_) => {
                    warn!("error parsing URL for script {}", &**src);
                    self.queue_error_event();
                    return;
                },
            };

            // Preparation for step 26.
            let kind = if element.has_attribute(&local_name!("defer")) &&
                was_parser_inserted &&
                !r#async
            {
                // Step 26.a: classic, has src, has defer, was parser-inserted, is not async.
                ExternalScriptKind::Deferred
            } else if was_parser_inserted && !r#async {
                // Step 26.c: classic, has src, was parser-inserted, is not async.
                ExternalScriptKind::ParsingBlocking
            } else if !r#async && !self.non_blocking.get() {
                // Step 26.d: classic, has src, is not async, is not non-blocking.
                ExternalScriptKind::AsapInOrder
            } else {
                // Step 26.f: classic, has src.
                ExternalScriptKind::Asap
            };

            // Step 24.6.
            fetch_a_classic_script(
                self,
                kind,
                url,
                cors_setting,
                integrity_metadata.to_owned(),
                encoding,
            );

            // Step 23.
            match kind {
                ExternalScriptKind::Deferred => doc.add_deferred_script(self),
                ExternalScriptKind::ParsingBlocking => {
                    doc.set_pending_parsing_blocking_script(self, None)
                },
                ExternalScriptKind::AsapInOrder => doc.push_asap_in_order_script(self),
                ExternalScriptKind::Asap => doc.add_asap_script(self),
            }
        } else {
            // Step 25.
            assert!(!text.is_empty());
            // Step 25-1.
            let result = Ok(ScriptOrigin::internal(text, base_url, ScriptType::Classic));

            // TODO: Step 25-2.

            // Step 26.
            if was_parser_inserted &&
                doc.get_current_parser()
{'fraction_non_alphanumeric': 0.12650434588812123, 'fraction_numerical': 0.00707599732560731, 'mean_word_length': 2.2409714698447094, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 123, 'https://': 22, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5313588', 'n_tokens_mistral': 10692, 'n_tokens_neox': 10254, 'n_words': 2101}