url

    Portable WHATWG URL parsing and normalization ported from Ada

    url
    whatwg
    simd
    ada
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    58 minutes ago
    Downloads
    2

    #URL

    Portable WHATWG URL parsing and form query parameters, ported from Ada.

    ///|
    test {
    let url = @url.parse("HTTPS://Example.COM:443/a/../b?q=hello world")
    assert_eq(url.href(), "https://example.com/b?q=hello%20world")
    assert_eq(url.join("../next").href(), "https://example.com/next")
    }

    ///|
    test {
    let params = @url.SearchParams::parse("a=hello+world&a=second")
    assert_eq(params.get_all("a"), ["hello world", "second"])
    params.set("a", "one & two")
    assert_eq(params.to_string(), "a=one+%26+two")
    }

    ParseError

    pub(all) suberror ParseError {
    InvalidUrl(String)
    } derive(Eq,
    Debug
    )

    Reports a URL that cannot be parsed according to the WHATWG URL Standard.

    The message identifies the failed component. Recoverable validation issues, such as omitted slashes or a percent sign without two hex digits in a path, are normalized rather than raised. A failed parse does not modify its base.

    SearchParams

    type SearchParams

    An ordered, mutable list of decoded form-urlencoded query pairs.

    Duplicate names and insertion order are preserved. Parsing uses UTF-8 replacement for malformed bytes and decodes plus as space. Assignments share mutable state; copy() creates independent state. Instances obtained from a URL are detached, as in Ada; apply them with Url::set_search_params().

    SearchParams::append

    fn SearchParams::append(self : SearchParams, name : StringView, value : StringView) -> Unit

    Appends one decoded pair at the end, preserving existing pairs. Names and values use USVString replacement; encoding happens at serialization.

    SearchParams::copy

    Copies the ordered list so later changes affect only their receiver. Immutable name/value strings may be shared safely.

    SearchParams::delete

    fn SearchParams::delete(self : SearchParams, name : StringView, value? : StringView) -> Unit

    Removes every matching name, optionally restricted to an exact decoded value. Retained pairs keep their order; removing an absent pair has no effect.

    SearchParams::entries

    fn SearchParams::entries(self : SearchParams) -> Iter[(String, String)]

    Iterates an independent snapshot of decoded pairs in the current order. Later changes to the parameter list do not change this iterator's snapshot.

    SearchParams::from_pairs

    fn SearchParams::from_pairs(pairs : ArrayView[(String, String)]) -> SearchParams

    Creates a parameter list from decoded pairs, preserving duplicates and order. Copies the list and replaces unpaired UTF-16 surrogates in names and values.

    SearchParams::get

    fn SearchParams::get(self : SearchParams, name : StringView) -> String?

    Returns the first matching decoded value or None, preserving Some("").

    SearchParams::get_all

    fn SearchParams::get_all(self : SearchParams, name : StringView) -> Array[String]

    Returns all matching decoded values in insertion order as an independent array.

    SearchParams::has

    fn SearchParams::has(self : SearchParams, name : StringView, value? : StringView) -> Bool

    Reports whether a name is present, optionally matching an exact decoded value. Empty names/values are valid and comparisons are case sensitive.

    SearchParams::keys

    fn SearchParams::keys(self : SearchParams) -> Iter[String]

    Iterates an independent snapshot of names, including duplicates.

    SearchParams::new

    Creates an empty ordered parameter list without parsing a query.

    SearchParams::parse

    fn SearchParams::parse(input : StringView) -> SearchParams

    Parses a query or form body, accepting one optional leading question mark. Empty ampersand-separated fields are skipped. Missing equals signs produce empty values; invalid percent escapes remain literal. Parsing never raises.

    SearchParams::reset

    fn SearchParams::reset(self : SearchParams, input : StringView) -> Unit

    Replaces all pairs by parsing a query with the same rules as parse().

    SearchParams::set

    fn SearchParams::set(self : SearchParams, name : StringView, value : StringView) -> Unit

    Replaces the first matching name's value and removes later matching pairs. If the name is absent, appends it. Other pairs retain their order.

    SearchParams::size

    fn SearchParams::size(self : SearchParams) -> Int

    Returns the number of pairs, including repeated names and empty values.

    SearchParams::sort

    fn SearchParams::sort(self : SearchParams) -> Unit

    Sorts by name in ascending UTF-16 code-unit order, stably for duplicate names. Values do not contribute to the ordering and remain paired with their names.

    SearchParams::to_string

    fn SearchParams::to_string(self : SearchParams) -> String

    Serializes as application/x-www-form-urlencoded without a leading question mark. Spaces become plus; all bytes except ASCII alphanumerics and *-._ are escaped. Each pair contains an equals sign, and duplicate names retain their order.

    SearchParams::values

    fn SearchParams::values(self : SearchParams) -> Iter[String]

    Iterates an independent snapshot of values, including empty strings.

    Url

    type Url

    A parsed WHATWG URL backed by one immutable serialized string and component offsets.

    Getter views avoid component-string allocation. MoonBit's garbage collector keeps an earlier view alive across setters, so a view remains a snapshot of the previous value. Unlike Ada's C++ string views, it never becomes dangling. Assigning a Url shares mutable setter state; use copy() for an independent URL. Parsing and failed setters do not mutate a base or partially change state.
    impl Eq for Url
    impl Show for Url

    Url::copy

    fn Url::copy(self : Url) -> Url

    Creates an independently mutable URL with the same value. Immutable backing strings may be shared safely; a later setter affects only its receiver. This operation does not parse, normalize, or copy input bytes.

    Url::fragment

    fn Url::fragment(self : Url) -> StringView?

    Returns the fragment without its delimiter, preserving Some("") for an empty fragment.

    Url::has_opaque_path

    fn Url::has_opaque_path(self : Url) -> Bool

    Reports whether the URL has an opaque path, such as mailto or data URLs. Opaque paths cannot resolve ordinary relative references or accept path setters.

    Url::hash

    fn Url::hash(self : Url) -> StringView

    Returns the fragment with a leading hash, or empty for absent/empty fragments. Use fragment() to distinguish absence from a present empty fragment.

    Url::host

    fn Url::host(self : Url) -> StringView

    Returns the host including a non-default port, or an empty view when absent. IPv6 hosts retain brackets and domains are already in ASCII/Punycode form.

    Url::hostname

    fn Url::hostname(self : Url) -> StringView

    Returns the canonical hostname without a port, keeping IPv6 brackets. Both absent hosts and the empty host of a file URL yield an empty view.

    Url::href

    fn Url::href(self : Url) -> String

    Returns the complete canonical URL without allocating another string. Includes empty query and fragment delimiters when they were present.

    Url::is_special

    fn Url::is_special(self : Url) -> Bool

    Reports whether the scheme is http, https, ws, wss, ftp, or file.

    Url::join

    fn Url::join(self : Url, input : StringView) -> Url raise ParseError

    Resolves input against this URL without modifying the base. Raises ParseError on invalid input or an ordinary relative reference against an opaque base. The new URL has independent mutable state.

    Url::origin

    fn Url::origin(self : Url) -> String

    Returns the serialized tuple origin or "null" for an opaque origin. Credentials, path, query, and fragment do not contribute. File URLs have opaque origins; blob URLs inherit valid inner HTTP/HTTPS URL origins.

    Url::password

    fn Url::password(self : Url) -> StringView

    Returns the percent-encoded password without its leading colon or trailing at sign. An absent password is an empty view; no decoding or allocation occurs.

    Url::pathname

    fn Url::pathname(self : Url) -> StringView

    Returns the canonical path, preserving encoded slashes and normalizing dot segments. Hierarchical paths include their leading slash; opaque paths do not add one.

    Url::port

    fn Url::port(self : Url) -> StringView

    Returns decimal port digits without the colon, or empty for omitted/default ports.

    Url::protocol

    fn Url::protocol(self : Url) -> StringView

    Returns the lowercase ASCII scheme with its trailing colon as a view.

    Url::query

    fn Url::query(self : Url) -> StringView?

    Returns the query without its delimiter, preserving Some("") for an empty query.

    Url::search

    fn Url::search(self : Url) -> StringView

    Returns the query with a leading question mark, or empty for absent/empty queries. Use query() to distinguish an absent query from a present empty query.

    Url::search_params

    fn Url::search_params(self : Url) -> SearchParams

    Returns a detached, independently mutable decoded copy of this URL's query. Changing these parameters does not change the URL until set_search_params().

    Url::set_hash

    fn Url::set_hash(self : Url, input : StringView) -> Unit

    Replaces the fragment, accepting an optional leading hash. Empty input removes the fragment; "#" preserves a present empty fragment. Uses the fragment encode set and does not modify the query.

    Url::set_host

    fn Url::set_host(self : Url, input : StringView) -> Bool

    Changes the hostname and an optional port using WHATWG host parsing. Stops at path/query/fragment delimiters, ignores tabs/newlines, and normalizes domains/IP literals. An omitted or empty port preserves the existing port. Invalid port suffixes preserve the old port after a valid hostname change. Returns false without changing the URL for invalid hosts or opaque paths.

    Url::set_hostname

    fn Url::set_hostname(self : Url, input : StringView) -> Bool

    Changes only the hostname and preserves the existing port. Uses the same normalization as set_host but rejects a port suffix. File localhost becomes an empty host; an invalid input leaves the URL unchanged.

    Url::set_href

    fn Url::set_href(self : Url, input : StringView) -> Bool

    Replaces the complete URL atomically, returning false when input cannot parse. Input is parsed as an absolute URL without a base. All earlier getter views remain safe snapshots, and a failure leaves every component unchanged.

    Url::set_password

    fn Url::set_password(self : Url, input : StringView) -> Bool

    Replaces the password with WHATWG userinfo percent encoding. Returns false for file URLs, opaque paths, or absent/empty hosts. Empty input removes the password and its colon without changing the username.

    Url::set_pathname

    fn Url::set_pathname(self : Url, input : StringView) -> Bool

    Changes a hierarchical path with dot-segment normalization and percent encoding. Question marks and hashes are path data, not query/fragment delimiters. Special schemes treat backslashes as slashes; file drive roots are protected. Returns false for opaque paths without changing the URL.

    Url::set_port

    fn Url::set_port(self : Url, input : StringView) -> Bool

    Changes a decimal port or clears it with empty input. A trailing nondigit terminates a digit prefix as in the WHATWG setter. Out-of-range values, missing initial digits, and URLs that cannot hold a port return false atomically. Default ports are normalized to absence.

    Url::set_protocol

    fn Url::set_protocol(self : Url, input : StringView) -> Bool

    Changes the scheme, lowercasing ASCII and accepting an optional colon suffix. Returns false for invalid schemes, special/non-special transitions, or file transitions prohibited by credentials, a port, or an empty file host. A port equal to the new scheme's default is removed. Failure is atomic.
    fn Url::set_search(self : Url, input : StringView) -> Unit

    Replaces the query, accepting an optional leading question mark. Empty input removes the query; "?" preserves a present empty query. Uses the special-query encode set for special schemes and does not modify the fragment.

    Url::set_search_params

    fn Url::set_search_params(self : Url, params : SearchParams) -> Unit

    Replaces the URL query with the list's form-urlencoded serialization. An empty list removes the query. The list remains independent of the URL.

    Url::set_username

    fn Url::set_username(self : Url, input : StringView) -> Bool

    Replaces the username with WHATWG userinfo percent encoding. Returns false for file URLs, opaque paths, or absent/empty hosts. The input is not percent-decoded: existing percent signs remain literal escapes.

    Url::to_string

    fn Url::to_string(self : Url) -> String

    Returns the canonical URL as an ordinary String without extra allocation.

    Url::username

    fn Url::username(self : Url) -> StringView

    Returns the percent-encoded username without the credentials delimiter. An absent username is an empty view; no decoding or allocation occurs.

    can_parse

    fn can_parse(input : StringView, base? : Url, simd? : Bool) -> Bool

    Reports whether input parses successfully with the supplied optional base. This is a validation convenience and currently performs full normalization. The base is not mutated, and all ParseError failures become false.

    domain_to_ascii

    fn domain_to_ascii(input : StringView) -> String raise ParseError

    Converts a domain to ASCII using the WHATWG nontransitional UTS #46 rules. Percent escapes are decoded before UTF-8/IDNA processing. Hyphen and DNS length restrictions are disabled; Bidi and joiner checks are enabled. Empty input returns an empty string; disallowed/malformed domains raise ParseError. The URL parser separately rejects an empty special host. This operation does not interpret numeric domains as IPv4 or accept bracketed IPv6 hosts.

    domain_to_unicode

    fn domain_to_unicode(input : StringView) -> String raise ParseError

    Converts a valid ASCII/Punycode or Unicode domain to its Unicode form. Uses the same UTS #46 flags as domain_to_ascii and raises ParseError on invalid labels. The result is for display; a parsed URL keeps its ASCII host.

    parse

    fn parse(input : StringView, base? : Url, simd? : Bool) -> Url raise ParseError

    Parses and normalizes a WHATWG URL, optionally resolving it against base.

    Input is a MoonBit UTF-16 string view and is converted to UTF-8 using scalar replacement for unpaired surrogates. Leading/trailing C0 space and embedded tabs/newlines follow WHATWG preprocessing. Hosts, ports, dot segments, and percent encoding are normalized; invalid hosts, ports, or missing bases raise ParseError. The base is never modified. simd=true requests checked vector character scans on native/Wasm with identical scalar fallbacks elsewhere.

    test {
    let url = @url.parse("HTTPS://Example.COM:443/a/../b?q=hello world")
    assert_eq(url.href(), "https://example.com/b?q=hello%20world")
    let next = @url.parse("../c", base=url)
    assert_eq(next.href(), "https://example.com/c")
    }

    try_parse

    fn try_parse(input : StringView, base? : Url, simd? : Bool) -> Url?

    Returns a normalized URL or None when parsing fails, without changing base. Uses the same preprocessing and backend selection as parse; no validation diagnostics escape. Empty input requires a non-opaque base URL.

    verify_dns_length

    fn verify_dns_length(domain : StringView) -> Bool

    Checks an ASCII domain against DNS label and total-length limits. Requires nonempty labels of at most 63 bytes and at most 253 bytes overall, excluding one optional trailing root dot. This is an explicit extra check: ordinary WHATWG URL parsing intentionally does not impose DNS length limits. Non-ASCII domains and empty labels return false; convert with domain_to_ascii first.