urlable 0.2.0

A comprehensive URL manipulation library for Rust, providing utilities for parsing, encoding, and manipulating URLs with support for query strings, path manipulation, punycode domains and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
use crate::{
    parse::parse_url,
    query::{parse_query, stringify_query, QueryObject},
};
use lazy_static::lazy_static;
use regex::Regex;

lazy_static! {
    // Matches strict protocol format like "http://" or "https://"
    static ref PROTOCOL_STRICT_REGEX: Regex = Regex::new(r"^[\s\w+.-]{2,}:([/\\]{1,2})").unwrap();
    // Matches relaxed protocol format like "http:" or "https:"
    static ref PROTOCOL_REGEX: Regex = Regex::new(r"^[\s\w+.-]{2,}:(?:/\\{2})?").unwrap();
    // Matches protocol-relative URLs starting with "//"
    static ref PROTOCOL_RELATIVE_REGEX: Regex = Regex::new(r"^([/\\]\s*){2,}[^/\\]").unwrap();
    // Matches potentially dangerous protocols like javascript: or data:
    static ref PROTOCOL_SCRIPT_RE: Regex =
        Regex::new(r"^[\s\0]*(blob|data|javascript|vbscript):$").unwrap();
    // Matches trailing slashes including those before ? or #
    static ref TRAILING_SLASH_RE: Regex = Regex::new(r"\/$|\/\?|\/#").unwrap();
    // Matches leading ./ or /
    static ref JOIN_LEADING_SLASH_RE: Regex = Regex::new(r"^\.?/").unwrap();
}

// Checks if a URL is relative (starts with ./ or ../)
// Example:
// is_relative("./images/logo.png") -> true
// is_relative("../styles/main.css") -> true
// is_relative("/absolute/path") -> false
pub fn is_relative(input_string: &str) -> bool {
    input_string.starts_with("./") || input_string.starts_with("../")
}

#[derive(Default, Clone)]
pub struct HasProtocolOptions {
    pub accept_relative: bool, // Whether to accept protocol-relative URLs (starting with //)
    pub strict: bool,          // Whether to strictly match protocol format
}

// Checks if a URL has a protocol prefix
// Example:
// has_protocol("https://example.com", strict_opts) -> true
// has_protocol("//example.com", relative_opts) -> true
// has_protocol("example.com", default_opts) -> false
pub fn has_protocol(input_string: &str, opts: HasProtocolOptions) -> bool {
    if opts.strict {
        return PROTOCOL_STRICT_REGEX.is_match(input_string);
    }
    PROTOCOL_REGEX.is_match(input_string)
        || (opts.accept_relative && PROTOCOL_RELATIVE_REGEX.is_match(input_string))
}

// Checks if a URL has a trailing slash, optionally respecting query params and fragments
// Example:
// has_trailing_slash("/path/", false) -> true
// has_trailing_slash("/path/?query=1", true) -> true
// has_trailing_slash("/path", false) -> false
pub fn has_trailing_slash(input: &str, respect_query_fragment: bool) -> bool {
    if !respect_query_fragment {
        input.ends_with('/')
    } else {
        TRAILING_SLASH_RE.is_match(input)
    }
}

// Removes trailing slash from URL, handling query params and fragments
// Example:
// without_trailing_slash("/path/", false) -> "/path"
// without_trailing_slash("/path/?query=1", true) -> "/path?query=1"
// without_trailing_slash("/path/#section/", true) -> "/path#section"
pub fn without_trailing_slash(input: &str, respect_query_fragment: bool) -> String {
    if !respect_query_fragment {
        return if has_trailing_slash(input, false) {
            input[..input.len() - 1].to_string()
        } else {
            input.to_string()
        };
    }

    if !has_trailing_slash(input, true) {
        return input.to_string();
    }

    let mut path = input.to_string();
    let mut fragment = String::new();

    if let Some(frag_idx) = input.find('#') {
        fragment = input[frag_idx..].to_string();
        path = input[..frag_idx].to_string();
    }

    let parts: Vec<&str> = path.split('?').collect();
    let clean_path = if parts[0].ends_with('/') {
        &parts[0][..parts[0].len() - 1]
    } else {
        parts[0]
    };

    format!(
        "{}{}{}",
        clean_path,
        if parts.len() > 1 {
            format!("?{}", parts[1..].join("?"))
        } else {
            String::new()
        },
        fragment
    )
}

// Adds trailing slash to URL, handling query params and fragments
// Example:
// with_trailing_slash("/path", false) -> "/path/"
// with_trailing_slash("/path?query=1", true) -> "/path/?query=1"
// with_trailing_slash("/path#section", true) -> "/path/#section"
pub fn with_trailing_slash(input: &str, respect_query_fragment: bool) -> String {
    if !respect_query_fragment {
        if input.ends_with('/') {
            input.to_string()
        } else {
            format!("{}/", input)
        }
    } else {
        if has_trailing_slash(input, true) {
            return input.to_string();
        }

        let mut path = input.to_string();
        let mut fragment = String::new();

        if let Some(frag_idx) = input.find('#') {
            fragment = input[frag_idx..].to_string();
            path = input[..frag_idx].to_string();
            if path.is_empty() {
                return fragment;
            }
        }

        let parts: Vec<&str> = path.split('?').collect();
        format!(
            "{}/{}{}",
            parts[0],
            if parts.len() > 1 {
                format!("?{}", parts[1..].join("?"))
            } else {
                String::new()
            },
            fragment
        )
    }
}

// Checks if URL starts with a forward slash
// Example:
// has_leading_slash("/path") -> true
// has_leading_slash("path") -> false
pub fn has_leading_slash(input: &str) -> bool {
    input.starts_with('/')
}

// Removes leading slash from URL
// Example:
// without_leading_slash("/path") -> "path"
// without_leading_slash("path") -> "path"
pub fn without_leading_slash(input: &str) -> String {
    if has_leading_slash(input) {
        input[1..].to_string()
    } else {
        input.to_string()
    }
}

// Adds leading slash to URL
// Example:
// with_leading_slash("path") -> "/path"
// with_leading_slash("/path") -> "/path"
pub fn with_leading_slash(input: &str) -> String {
    if has_leading_slash(input) {
        input.to_string()
    } else {
        format!("/{}", input)
    }
}

// Normalizes multiple slashes in URL while preserving protocol slashes
// Example:
// clean_double_slashes("http://example.com//path///to////file") -> "http://example.com/path/to/file"
// clean_double_slashes("//path////to/////file") -> "/path/to/file"
pub fn clean_double_slashes(url: &str) -> String {
    // Pre-allocate string capacity to avoid reallocations
    let mut result = String::with_capacity(url.len());
    // Create peekable iterator to look ahead at next chars
    let mut chars = url.chars().peekable();
    // Track if we're right after a colon (for protocol handling)
    let mut after_colon = false;

    while let Some(c) = chars.next() {
        // Handle colon character (potential protocol marker)
        // Example: "http:" -> sets after_colon flag
        if c == ':' {
            result.push(c);
            after_colon = true;
            continue;
        }

        // Handle non-slash characters
        // Example: "example.com" -> copies chars as-is
        if c != '/' {
            result.push(c);
            after_colon = false;
        } else {
            result.push(c);
            if after_colon {
                // Special handling for protocol double slashes
                // Example: "http://" -> preserves both slashes
                while let Some(&next_c) = chars.peek() {
                    if next_c == '/' {
                        result.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }
                after_colon = false;
            } else {
                // Skip consecutive slashes in path
                // Example: "path///to" -> becomes "path/to"
                while let Some(&next_c) = chars.peek() {
                    if next_c == '/' {
                        chars.next();
                    } else {
                        break;
                    }
                }
            }
        }
    }

    result
}

// Prepends base URL to a path if needed
// Example:
// with_base("/path", "/base") -> "/base/path"
// with_base("http://example.com", "/base") -> "http://example.com"
pub fn with_base(input: &str, base: &str) -> String {
    let result = if is_empty_url(base) || has_protocol(input, HasProtocolOptions::default()) {
        return input.to_string();
    } else {
        let base = without_trailing_slash(base, false);
        if input.starts_with(&base) {
            input.to_string()
        } else {
            join_url(&base, input)
        }
    };
    clean_double_slashes(&result)
}

// Removes base URL from a path if present
// Example:
// without_base("/base/path", "/base") -> "/path"
// without_base("/other/path", "/base") -> "/other/path"
pub fn without_base(input: &str, base: &str) -> String {
    if is_empty_url(base) {
        return input.to_string();
    }
    let base = without_trailing_slash(base, false);
    if !input.starts_with(&base) {
        return input.to_string();
    }
    let trimmed = &input[base.len()..];
    if trimmed.starts_with('/') {
        trimmed.to_string()
    } else {
        format!("/{}", trimmed)
    }
}

// Adds or merges query parameters to URL
// Example:
// with_query("http://example.com", {"page": "1"}) -> "http://example.com?page=1"
// with_query("http://example.com?sort=desc", {"page": "1"}) -> "http://example.com?sort=desc&page=1"
pub fn with_query(input: &str, query: &QueryObject) -> String {
    let mut parsed = parse_url(input);
    let current: QueryObject = parse_query(&parsed.search);

    // Preserve existing query params first
    let mut result = QueryObject::new();
    for (key, value) in current.iter() {
        result.insert(key.clone(), value.clone());
    }

    // Then append new query params
    for (key, value) in query.iter() {
        result.insert(key.clone(), value.clone());
    }

    parsed.search = stringify_query(&result);
    parsed.stringify()
}

// Checks if URL is empty or just a slash
// Example:
// is_empty_url("") -> true
// is_empty_url("/") -> true
// is_empty_url("/path") -> false
pub fn is_empty_url(url: &str) -> bool {
    url.is_empty() || url == "/"
}

// Joins base URL with path
// Example:
// join_url("/base", "path") -> "/base/path"
// join_url("", "path") -> "path"
// join_url("/base", "") -> "/base"
pub fn join_url(base: &str, input: &str) -> String {
    let mut url = base.to_string();
    if !is_empty_url(input) {
        if !url.is_empty() {
            let segment = input.trim_start_matches(|c| c == '.' || c == '/');
            url = format!("{}/{}", with_trailing_slash(&url, false), segment);
        } else {
            url = input.to_string();
        }
    }
    url
}

// Joins multiple URL segments handling relative paths
// Example:
// join_relative_url(["/base", "../other", "./path"]) -> "/other/path"
// join_relative_url(["http:", "example.com", "path"]) -> "http://example.com/path"
pub fn join_relative_url(inputs: &[&str]) -> String {
    if inputs.is_empty() {
        return String::new();
    }

    let mut segments: Vec<String> = Vec::new();
    let mut segments_depth = 0;

    for input in inputs.iter().filter(|&&i| !i.is_empty() && i != "/") {
        for (sindex, s) in input.split('/').enumerate() {
            if s.is_empty() || s == "." {
                continue;
            }
            if s == ".." {
                if segments.len() == 1
                    && has_protocol(segments[0].as_str(), HasProtocolOptions::default())
                {
                    continue;
                }
                if !segments.is_empty() {
                    segments.pop();
                    segments_depth -= 1;
                } else {
                    segments_depth -= 1;
                }
                continue;
            }
            if sindex == 1 && segments.last().map_or(false, |last| last.ends_with(':')) {
                if let Some(last) = segments.last_mut() {
                    *last = format!("{}//", last);
                }
                segments.push(s.to_string());
                segments_depth += 1;
                continue;
            }
            segments.push(s.to_string());
            segments_depth += 1;
        }
    }

    let mut url = segments.join("/");

    if segments_depth >= 0 {
        if inputs.first().map_or(false, |&i| i.starts_with('/')) && !url.starts_with('/') {
            url = format!("/{}", url);
        } else if inputs.first().map_or(false, |&i| i.starts_with("./")) && !url.starts_with("./") {
            url = format!("./{}", url);
        }
    } else {
        url = format!("{}{}", "../".repeat(-segments_depth as usize), url);
    }

    if inputs.last().map_or(false, |&i| i.ends_with('/')) && !url.ends_with('/') {
        url.push('/');
    }

    url
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_relative() {
        assert!(is_relative("./foo"));
        assert!(is_relative("../foo"));
        assert!(!is_relative("/foo"));
        assert!(!is_relative("foo"));
        assert!(!is_relative("http://example.com"));
        assert!(is_relative("./"));
        assert!(is_relative("../"));
        assert!(!is_relative("//foo"));
        assert!(!is_relative("https://foo"));
    }

    #[test]
    fn test_has_protocol() {
        let strict_opts = HasProtocolOptions {
            strict: true,
            ..Default::default()
        };
        let relative_opts = HasProtocolOptions {
            accept_relative: true,
            ..Default::default()
        };

        assert!(has_protocol("http://example.com", strict_opts.clone()));
        assert!(has_protocol("https://example.com", strict_opts.clone()));
        assert!(has_protocol("ftp://files.example.com", strict_opts.clone()));
        assert!(!has_protocol("//example.com", strict_opts));
        assert!(has_protocol("//example.com", relative_opts));
        assert!(!has_protocol("example.com", HasProtocolOptions::default()));

        // Additional test cases
        assert!(has_protocol(
            "sftp://example.com",
            HasProtocolOptions::default()
        ));
        assert!(has_protocol(
            "ws://example.com",
            HasProtocolOptions::default()
        ));
        assert!(has_protocol(
            "wss://example.com",
            HasProtocolOptions::default()
        ));
    }

    #[test]
    fn test_trailing_slash() {
        // Basic cases
        assert_eq!(without_trailing_slash("/foo/", false), "/foo");
        assert_eq!(with_trailing_slash("/foo", false), "/foo/");

        // With query parameters
        assert_eq!(
            without_trailing_slash("/foo/?query=1", true),
            "/foo?query=1"
        );
        assert_eq!(with_trailing_slash("/foo?query=1", true), "/foo/?query=1");

        // With fragments
        assert_eq!(without_trailing_slash("/foo/#hash", true), "/foo#hash");
        assert_eq!(with_trailing_slash("/foo#hash", true), "/foo/#hash");

        // Complex cases
        assert_eq!(
            without_trailing_slash("/foo/bar/?query=1#hash", true),
            "/foo/bar?query=1#hash"
        );
        assert_eq!(
            with_trailing_slash("/foo/bar?query=1#hash", true),
            "/foo/bar/?query=1#hash"
        );

        // Additional test cases
        assert_eq!(without_trailing_slash("", false), "");
        assert_eq!(with_trailing_slash("", false), "/");
        assert_eq!(without_trailing_slash("/", false), "");
        assert_eq!(with_trailing_slash("/", false), "/");
        assert_eq!(without_trailing_slash("foo/", false), "foo");
        assert_eq!(with_trailing_slash("foo", false), "foo/");
    }

    #[test]
    fn test_leading_slash() {
        assert_eq!(without_leading_slash("/foo"), "foo");
        assert_eq!(with_leading_slash("foo"), "/foo");
        assert_eq!(without_leading_slash("/foo/bar"), "foo/bar");
        assert_eq!(with_leading_slash("foo/bar"), "/foo/bar");
        assert_eq!(without_leading_slash("foo"), "foo");
        assert_eq!(with_leading_slash("/foo"), "/foo");

        // Additional test cases
        assert_eq!(without_leading_slash(""), "");
        assert_eq!(with_leading_slash(""), "/");
        assert_eq!(without_leading_slash("/"), "");
        assert_eq!(with_leading_slash("/"), "/");
        assert_eq!(without_leading_slash("//foo"), "/foo");
        assert_eq!(with_leading_slash("//foo"), "//foo");
    }

    #[test]
    fn test_clean_double_slashes() {
        assert_eq!(
            clean_double_slashes("http://example.com//foo//bar"),
            "http://example.com/foo/bar"
        );
        assert_eq!(
            clean_double_slashes("https://example.com///foo////bar"),
            "https://example.com/foo/bar"
        );
        assert_eq!(clean_double_slashes("//foo//bar"), "/foo/bar");
        assert_eq!(clean_double_slashes("foo//bar"), "foo/bar");

        // Additional test cases
        assert_eq!(clean_double_slashes(""), "");
        assert_eq!(clean_double_slashes("/"), "/");
        assert_eq!(clean_double_slashes("////"), "/");
        assert_eq!(
            clean_double_slashes("ftp://example.com////foo///bar//"),
            "ftp://example.com/foo/bar/"
        );
    }

    #[test]
    fn test_join_relative_url() {
        assert_eq!(join_relative_url(&["/a", "../b", "./c"]), "/b/c");
        assert_eq!(join_relative_url(&["a", "b", "c"]), "a/b/c");
        assert_eq!(join_relative_url(&["a", "../b", "../c"]), "c");
        assert_eq!(join_relative_url(&["/", "a", "b", "/"]), "/a/b/");
        assert_eq!(join_relative_url(&["./", "a", "../b"]), "./b");
        assert_eq!(join_relative_url(&["a", "b", "..", "c"]), "a/c");

        // Additional test cases
        assert_eq!(join_relative_url(&[]), "");
        assert_eq!(join_relative_url(&["/"]), "/");
        assert_eq!(join_relative_url(&[".", "."]), "");
        assert_eq!(join_relative_url(&["..", ".."]), "../../");
        assert_eq!(join_relative_url(&["a", ".", "b"]), "a/b");
    }

    #[test]
    fn test_with_query() {
        let mut query = QueryObject::new();
        query.insert("foo".to_string(), serde_json::json!("bar"));

        assert_eq!(
            with_query("http://example.com", &query),
            "http://example.com?foo=bar"
        );
        assert_eq!(
            with_query("http://example.com?existing=1", &query),
            "http://example.com?existing=1&foo=bar"
        );

        let mut complex_query = QueryObject::new();
        complex_query.insert("array".to_string(), serde_json::json!(["1", "2"]));
        assert_eq!(
            with_query("http://example.com", &complex_query),
            "http://example.com?array=1&array=2"
        );

        // Additional test cases
        let empty_query = QueryObject::new();
        assert_eq!(
            with_query("http://example.com", &empty_query),
            "http://example.com"
        );

        let mut multiple_query = QueryObject::new();
        multiple_query.insert("a".to_string(), serde_json::json!("1"));
        multiple_query.insert("b".to_string(), serde_json::json!("2"));
        assert_eq!(
            with_query("http://example.com?c=3", &multiple_query),
            "http://example.com?c=3&a=1&b=2"
        );
    }

    #[test]
    fn test_with_base() {
        assert_eq!(with_base("/path", ""), "/path");
        assert_eq!(with_base("/path", "/"), "/path");
        assert_eq!(with_base("/path", "/base"), "/base/path");
        assert_eq!(
            with_base("http://example.com", "/base"),
            "http://example.com"
        );
        assert_eq!(with_base("/base/path", "/base"), "/base/path");
        assert_eq!(with_base("path", "/base/"), "/base/path");
    }

    #[test]
    fn test_without_base() {
        assert_eq!(without_base("/path", ""), "/path");
        assert_eq!(without_base("/path", "/"), "/path");
        assert_eq!(without_base("/base/path", "/base"), "/path");
        assert_eq!(without_base("/other/path", "/base"), "/other/path");
        assert_eq!(without_base("/base", "/base"), "/");
        assert_eq!(without_base("/base/", "/base"), "/");
    }
}