quickjs_jit_stdlib/llrt/llrt_url/
lib.rs1#![allow(clippy::inherent_to_string)]
6pub mod url_class;
7pub mod url_search_params;
8
9use std::{path::PathBuf, str::FromStr};
10
11use crate::utils::{
12 module::{export_default, ModuleInfo},
13 primordials::{BasePrimordials, Primordial},
14 result::ResultExt,
15};
16use rquickjs::{
17 function::{Constructor, Func},
18 module::{Declarations, Exports, ModuleDef},
19 prelude::Opt,
20 Class, Coerced, Ctx, Exception, Result, Value,
21};
22use url::{quirks, Url};
23
24use self::url_class::{url_to_http_options, URL};
25use self::url_search_params::URLSearchParams;
26
27pub fn is_special_scheme(scheme: &str) -> bool {
29 matches!(scheme, "http" | "https" | "ftp" | "ws" | "wss" | "file")
30}
31
32pub fn domain_to_unicode(domain: &str) -> String {
33 quirks::domain_to_unicode(domain)
34}
35
36pub fn domain_to_ascii(domain: &str) -> String {
37 quirks::domain_to_ascii(domain)
38}
39
40pub fn path_to_file_url<'js>(ctx: Ctx<'js>, path: String, _: Opt<Value>) -> Result<URL<'js>> {
42 let url = Url::from_file_path(&path)
43 .map_err(|_| Exception::throw_type(&ctx, &["Path is not absolute: ", &path].concat()))?;
44
45 URL::from_url(ctx, url)
46}
47
48pub fn file_url_to_path<'js>(ctx: Ctx<'js>, url: Value<'js>) -> Result<String> {
50 let url_string = if let Ok(url) = Class::<URL>::from_value(&url) {
51 url.borrow().to_string()
52 } else {
53 url.get::<Coerced<String>>()?.to_string()
54 };
55
56 let path = url_string.trim_start_matches("file://");
57
58 Ok(PathBuf::from_str(path)
59 .or_throw(&ctx)?
60 .to_string_lossy()
61 .to_string())
62}
63
64pub fn url_format<'js>(url: Class<'js, URL<'js>>, options: Opt<Value<'js>>) -> Result<String> {
65 let url = url.borrow();
66 let mut string = url.protocol();
67 string.push_str("//");
68
69 let mut include_fragment = true;
70 let mut unicode_encode = false;
71 let mut include_auth = true;
72 let mut include_search = true;
73
74 if let Some(options) = options.into_inner() {
76 if let Some(options) = options.as_object() {
77 if let Ok(value) = options.get("unicode") {
78 unicode_encode = value;
79 }
80 if let Ok(value) = options.get("auth") {
81 include_auth = value;
82 }
83 if let Ok(value) = options.get("fragment") {
84 include_fragment = value;
85 }
86 if let Ok(value) = options.get("search") {
87 include_search = value
88 }
89 }
90 }
91
92 if include_auth {
93 let username = url.username();
94 let password = url.password();
95 if !username.is_empty() {
96 string.push_str(&username);
97 if !password.is_empty() {
98 string.push(':');
99 string.push_str(&password);
100 }
101 string.push('@');
102 }
103 }
104
105 if unicode_encode {
106 string.push_str(&domain_to_unicode(&url.host()));
107 } else {
108 string.push_str(&url.host());
109 }
110
111 string.push_str(&url.pathname());
112
113 if include_search {
114 string.push_str(&url.search());
115 }
116
117 if include_fragment {
118 string.push_str(&url.hash());
119 }
120
121 Ok(string)
122}
123
124pub fn convert_trailing_space(url: &mut Url) {
128 if is_special_scheme(url.scheme()) {
129 return;
130 }
131
132 let path = url.path();
133 let has_remaining = url.fragment().is_some() || url.query().is_some();
134
135 #[allow(clippy::manual_strip)]
136 if path.ends_with(' ') && has_remaining {
137 let new_path = [&path[..path.len() - 1], "%20"].concat();
138 url.set_path(&new_path);
139 }
140}
141
142pub fn preserve_file_url_host(source: &str, mut url: Url) -> Url {
161 if url.scheme() != "file" {
162 return url;
163 }
164 if url.host_str().is_some_and(|h| !h.is_empty()) {
165 return url;
166 }
167 let Some(rest) = source.strip_prefix("file://") else {
169 return url;
170 };
171 let Some((host, _)) = rest.split_once('/') else {
172 return url;
173 };
174 if host.is_empty() {
175 return url;
176 }
177 let _ = url.set_host(Some(host));
178 url
179}
180
181pub fn restore_file_url_host(base: &Url, joined: &mut Url) {
187 if base.scheme() != "file" || joined.scheme() != "file" {
188 return;
189 }
190 let Some(base_host) = base.host_str() else {
192 return;
193 };
194 if base_host.is_empty() {
195 return;
196 }
197 if joined.host_str().is_some_and(|h| !h.is_empty()) {
198 return;
199 }
200 let base_path = base.path();
203 let is_drive_letter_first_seg = base_path
204 .as_bytes()
205 .get(1)
206 .is_some_and(|b| b.is_ascii_alphabetic())
207 && base_path.as_bytes().get(2) == Some(&b':')
208 && matches!(base_path.as_bytes().get(3), Some(&b'/') | None);
209 if !is_drive_letter_first_seg {
210 return;
211 }
212 let _ = joined.set_host(Some(base_host));
213}
214
215pub fn normalize_windows_drive_letter(url: &mut Url) {
216 if url.scheme() != "file" {
217 return;
218 }
219 let path = url.path();
220 let bytes = path.as_bytes();
221 if bytes.len() < 4
224 || bytes[0] != b'/'
225 || !bytes[1].is_ascii_alphabetic()
226 || bytes[2] != b'|'
227 || bytes[3] != b'/'
228 {
229 return;
230 }
231 let new_path = ["/", &path[1..2], ":", &path[3..]].concat();
232 url.set_path(&new_path);
233}
234
235pub fn erase_empty_host_path(url: &mut Url) {
240 if is_special_scheme(url.scheme()) {
241 return;
242 }
243 if url.path() != "/" {
244 return;
245 }
246 let serialized = url.as_str();
247 let Some(scheme_end) = serialized.find("://") else {
251 return;
252 };
253 let authority_and_path = &serialized[scheme_end + 3..];
254 if authority_and_path != "/" {
258 return;
259 }
260 let stripped = &serialized[..serialized.len() - 1];
262 if let Ok(reparsed) = Url::parse(stripped) {
263 *url = reparsed;
264 }
265}
266
267pub fn strip_path_sentinel(url: &mut Url) {
268 if is_special_scheme(url.scheme()) {
269 return;
270 }
271 if !url.path().starts_with("//") {
276 return;
277 }
278 let serialized = url.as_str();
279 let Some(auth_start) = serialized.find("://") else {
281 return;
282 };
283 let after_auth = auth_start + 3;
284 let Some(path_start_rel) = serialized[after_auth..].find('/') else {
286 return;
287 };
288 let path_idx = after_auth + path_start_rel;
289 if serialized[path_idx..].starts_with("/./") {
290 let stripped = [&serialized[..path_idx], &serialized[path_idx + 2..]].concat();
291 if let Ok(reparsed) = Url::parse(&stripped) {
292 *url = reparsed;
293 }
294 }
295}
296
297pub fn init(ctx: &Ctx<'_>) -> Result<()> {
298 let globals = ctx.globals();
299
300 Class::<URLSearchParams>::define(&globals)?;
301 Class::<URL>::define(&globals)?;
302
303 Ok(())
304}
305
306pub struct UrlModule;
307
308impl ModuleDef for UrlModule {
309 fn declare(declare: &Declarations) -> Result<()> {
310 declare.declare(stringify!(URL))?;
311 declare.declare(stringify!(URLSearchParams))?;
312 declare.declare("urlToHttpOptions")?;
313 declare.declare("domainToUnicode")?;
314 declare.declare("domainToASCII")?;
315 declare.declare("fileURLToPath")?;
316 declare.declare("pathToFileURL")?;
317 declare.declare("format")?;
318 declare.declare("default")?;
319 Ok(())
320 }
321
322 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
323 let globals = ctx.globals();
324 BasePrimordials::init(ctx)?;
325 let url: Constructor = globals.get(stringify!(URL))?;
326 let url_search_params: Constructor = globals.get(stringify!(URLSearchParams))?;
327
328 export_default(ctx, exports, |default| {
329 default.set(stringify!(URL), url)?;
330 default.set(stringify!(URLSearchParams), url_search_params)?;
331 default.set("urlToHttpOptions", Func::from(url_to_http_options))?;
332 default.set(
333 "domainToUnicode",
334 Func::from(|domain: String| domain_to_unicode(&domain)),
335 )?;
336 default.set(
337 "domainToASCII",
338 Func::from(|domain: String| domain_to_ascii(&domain)),
339 )?;
340 default.set("fileURLToPath", Func::from(file_url_to_path))?;
341 default.set("pathToFileURL", Func::from(path_to_file_url))?;
342 default.set("format", Func::from(url_format))?;
343 Ok(())
344 })?;
345
346 Ok(())
347 }
348}
349
350impl From<UrlModule> for ModuleInfo<UrlModule> {
351 fn from(val: UrlModule) -> Self {
352 ModuleInfo {
353 name: "url",
354 module: val,
355 }
356 }
357}