foundation_core 0.0.6

Central crate for all foundation crates for the ewe-platform project
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
//! Comprehensive URI/URL parsing and manipulation module.
//!
//! WHY: HTTP operations require robust URL parsing with proper validation,
//! normalization, and component extraction. A solid URI implementation is
//! fundamental to reliable HTTP client operations.
//!
//! WHAT: Provides RFC 3986 compliant URI parsing with support for:
//! - Scheme (http, https, and extensible for others)
//! - Authority (userinfo, host, port)
//! - Path (with normalization)
//! - Query parameters
//! - Fragment
//!
//! HOW: Inspired by hyperium/http, uses zero-copy parsing where possible
//! and proper validation at each component level.

mod authority;
mod errors;
mod path;
mod query;
mod scheme;

pub use authority::*;
pub use errors::*;
pub use path::*;
pub use query::*;
pub use scheme::*;

use std::fmt;

/// A parsed URI with all components.
///
/// WHY: URIs are the fundamental addressing mechanism for HTTP. This type
/// provides a validated, structured representation that can be used for
/// HTTP requests, redirects, and URL manipulation.
///
/// WHAT: Represents a URI with optional components following RFC 3986:
/// `scheme:[//authority]path[?query][#fragment]`
///
/// HOW: Components are stored as owned strings after validation. The URI
/// can be constructed via parsing or building individual parts.
///
/// # Examples
///
/// ```
/// use foundation_core::url::Uri;
///
/// // Parse from string
/// let uri = Uri::parse("https://user:pass@example.com:8080/path?key=value#section").unwrap();
/// assert_eq!(uri.scheme().as_str(), "https");
/// assert_eq!(uri.host_str().unwrap(), "example.com");
/// assert_eq!(uri.port().unwrap(), 8080);
/// assert_eq!(uri.path(), "/path");
/// assert_eq!(uri.query().unwrap(), "key=value");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Uri {
    /// URI scheme (http, https, etc.)
    pub scheme: Scheme,
    /// Optional authority (userinfo@host:port)
    pub authority: Option<Authority>,
    /// Path and query components
    pub path_and_query: PathAndQuery,
    /// Optional fragment (after #)
    pub fragment: Option<String>,
}

impl Uri {
    /// Parses a URI from a string.
    ///
    /// This parser accepts two shapes of input:
    /// 1. Absolute URIs with a scheme (e.g. "<http://example.com/path>")
    /// 2. Path-only inputs that start with '/' (e.g. "/path?query") — these are
    ///    treated as a path + query with a default scheme of `http` and no authority.
    ///
    /// Rationale: server-side code and many internal tests construct requests
    /// using path-only URLs ("/"). Treating leading-slash inputs as a valid,
    /// path-only URI simplifies callers and keeps `Uri::parse` useful in both
    /// contexts while still rejecting ambiguous inputs like "example.com/path"
    /// that lack a scheme and a leading slash.
    ///
    /// # Arguments
    ///
    /// * `uri` - The URI string to parse
    ///
    /// # Errors
    ///
    /// Returns `InvalidUri` if:
    /// - URI format is invalid for absolute URIs
    /// - For path-only form, path parsing fails
    pub fn parse(uri: &str) -> Result<Self, InvalidUri> {
        // Accept path-only URIs (starting with '/'). These are common for server
        // side request representations and tests that pass only the path.
        if uri.starts_with('/') {
            let path_and_query = PathAndQuery::parse(uri)?;
            return Ok(Uri {
                scheme: Scheme::HTTP,
                authority: None,
                path_and_query,
                fragment: None,
            });
        }

        // Otherwise require an explicit scheme as before.
        // URI format: scheme:[//authority]path[?query][#fragment]

        // 1. Parse scheme (required)
        let (scheme, rest) = Scheme::parse_from_uri(uri)?;

        // 2. Check for authority (starts with //)
        let (authority, rest) = if let Some(after_slashes) = rest.strip_prefix("//") {
            Authority::parse_with_remainder(after_slashes)?
        } else {
            (None, rest)
        };

        // 3. Split off fragment first (after #)
        let (rest, fragment) = if let Some(hash_pos) = rest.find('#') {
            let frag = &rest[hash_pos + 1..];
            let fragment = if frag.is_empty() {
                None
            } else {
                Some(frag.to_string())
            };
            (&rest[..hash_pos], fragment)
        } else {
            (rest, None)
        };

        // 4. Parse path and query
        let path_and_query = PathAndQuery::parse(rest)?;

        Ok(Uri {
            scheme,
            authority,
            path_and_query,
            fragment,
        })
    }

    /// Returns the scheme component.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("https://example.com").unwrap();
    /// assert_eq!(uri.scheme().as_str(), "https");
    /// ```
    #[must_use]
    pub fn scheme(&self) -> &Scheme {
        &self.scheme
    }

    /// Returns the host component as a string if present.
    ///
    /// WHY: The host is needed for DNS resolution and connection establishment.
    ///
    /// WHAT: Returns the host as a string. For IP addresses, this allocates
    /// since they need to be formatted.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("http://example.com").unwrap();
    /// assert_eq!(uri.host_str(), Some("example.com".to_string()));
    /// ```
    #[must_use]
    pub fn host_str(&self) -> Option<String> {
        self.authority.as_ref().map(|a| match a.host() {
            Host::RegName(name) => name.clone(),
            Host::Ipv4(addr) => addr.to_string(),
            Host::Ipv6(addr) => addr.to_string(), // Without brackets
        })
    }

    /// Returns a reference to the Host enum if present.
    ///
    /// WHY: Allows pattern matching on the host type without allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::{Uri, Host};
    ///
    /// let uri = Uri::parse("http://192.168.1.1").unwrap();
    /// match uri.host_enum() {
    ///     Some(Host::Ipv4(addr)) => println!("IPv4: {}", addr),
    ///     Some(Host::Ipv6(addr)) => println!("IPv6: {}", addr),
    ///     Some(Host::RegName(name)) => println!("Domain: {}", name),
    ///     None => println!("No host"),
    /// }
    /// ```
    #[must_use]
    pub fn host_enum(&self) -> Option<&Host> {
        self.authority.as_ref().map(authority::Authority::host)
    }

    /// Returns the port component if present.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("http://example.com:8080").unwrap();
    /// assert_eq!(uri.port(), Some(8080));
    /// ```
    #[must_use]
    pub fn port(&self) -> Option<u16> {
        self.authority.as_ref().and_then(authority::Authority::port)
    }

    /// Returns the port or the default port for the scheme.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("http://example.com").unwrap();
    /// assert_eq!(uri.port_or_default(), 80);
    ///
    /// let uri = Uri::parse("https://example.com:8443").unwrap();
    /// assert_eq!(uri.port_or_default(), 8443);
    /// ```
    #[must_use]
    pub fn port_or_default(&self) -> u16 {
        self.port().unwrap_or_else(|| self.scheme.default_port())
    }

    /// Returns the path component.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("http://example.com/path").unwrap();
    /// assert_eq!(uri.path(), "/path");
    /// ```
    #[must_use]
    pub fn path(&self) -> &str {
        self.path_and_query.path()
    }

    /// Returns the query component if present.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("http://example.com?key=value").unwrap();
    /// assert_eq!(uri.query().unwrap(), "key=value");
    /// ```
    #[must_use]
    pub fn query(&self) -> Option<String> {
        self.path_and_query.query()
    }

    /// Returns a reference to the structured query parameters.
    #[must_use]
    pub fn query_params(&self) -> &Query {
        self.path_and_query.query_params()
    }

    /// Returns a mutable reference to the structured query parameters.
    #[must_use]
    pub fn query_params_mut(&mut self) -> &mut Query {
        self.path_and_query.query_params_mut()
    }

    /// Returns a new `Uri` with the given structured query params.
    #[must_use]
    pub fn with_query_params(&self, query: Query) -> Self {
        let path_and_query = PathAndQuery {
            path: self.path_and_query.path().to_string(),
            query,
        };
        Uri {
            scheme: self.scheme.clone(),
            authority: self.authority.clone(),
            path_and_query,
            fragment: self.fragment.clone(),
        }
    }

    /// Appends a query parameter (allowing duplicate keys).
    ///
    /// WHY: Callers building requests need to add query params incrementally
    /// without re-parsing the whole query string.
    ///
    /// WHAT: Pushes `(key, value)` onto the structured query.
    ///
    /// HOW: Delegates to [`Query::append`].
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn append_query(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.path_and_query.query.append(key, value);
    }

    /// Sets a query parameter, removing any prior values for the same key.
    ///
    /// WHY: Some params are single-valued and later assignments must replace
    /// earlier ones.
    ///
    /// WHAT: Drops existing pairs matching `key`, then appends the new pair.
    ///
    /// HOW: [`Query::retain`] to filter, then [`Query::append`].
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn set_query(&mut self, key: impl Into<String>, value: impl Into<String>) {
        let k = key.into();
        self.path_and_query.query.retain(|existing, _| existing != k);
        self.path_and_query.query.append(k, value);
    }

    /// Removes all query params for the given key.
    ///
    /// WHY: Callers may need to strip a parameter (e.g. pagination cursor)
    /// before reissuing a request.
    ///
    /// WHAT: Drops every pair whose key equals `key`.
    ///
    /// HOW: Delegates to [`Query::retain`].
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn remove_query(&mut self, key: &str) {
        self.path_and_query.query.retain(|k, _| k != key);
    }

    /// Returns the fragment component if present.
    ///
    /// # Examples
    ///
    /// ```
    /// use foundation_core::url::Uri;
    ///
    /// let uri = Uri::parse("http://example.com#section").unwrap();
    /// assert_eq!(uri.fragment().unwrap(), "section");
    /// ```
    #[must_use]
    pub fn fragment(&self) -> Option<&str> {
        self.fragment.as_deref()
    }

    /// Returns the authority component if present.
    #[must_use]
    pub fn authority(&self) -> Option<&Authority> {
        self.authority.as_ref()
    }

    /// Returns the path and query component.
    #[must_use]
    pub fn path_and_query(&self) -> &PathAndQuery {
        &self.path_and_query
    }

    // ── Builder methods ─────────────────────────────────────────────

    /// Returns a new `Uri` with the given query string (without leading '?').
    #[must_use]
    pub fn with_query(&self, query: impl Into<String>) -> Self {
        let query_str = query.into();
        let parsed = Query::parse(&query_str).unwrap_or_default();
        let path_and_query = PathAndQuery {
            path: self.path_and_query.path().to_string(),
            query: parsed,
        };
        Uri {
            scheme: self.scheme.clone(),
            authority: self.authority.clone(),
            path_and_query,
            fragment: self.fragment.clone(),
        }
    }

    /// Returns a new `Uri` with the given path.
    #[must_use]
    pub fn with_path(&self, path: impl Into<String>) -> Self {
        let new_path = path.into();
        let path_and_query = PathAndQuery {
            path: if new_path.starts_with('/') {
                new_path
            } else {
                format!("/{new_path}")
            },
            query: self.path_and_query.query.clone(),
        };
        Uri {
            scheme: self.scheme.clone(),
            authority: self.authority.clone(),
            path_and_query,
            fragment: self.fragment.clone(),
        }
    }

    /// Returns a new `Uri` with the given authority.
    #[must_use]
    pub fn with_authority(&self, authority: impl Into<Option<Authority>>) -> Self {
        Uri {
            scheme: self.scheme.clone(),
            authority: authority.into(),
            path_and_query: self.path_and_query.clone(),
            fragment: self.fragment.clone(),
        }
    }

    /// Returns a new `Uri` with the given scheme.
    #[must_use]
    pub fn with_scheme(&self, scheme: Scheme) -> Self {
        Uri {
            scheme,
            authority: self.authority.clone(),
            path_and_query: self.path_and_query.clone(),
            fragment: self.fragment.clone(),
        }
    }
}

/// Builder for constructing URIs from scratch.
///
/// # Examples
///
/// ```
/// use foundation_core::url::{UriBuilder, Scheme};
///
/// let uri = UriBuilder::new()
///     .scheme(Scheme::HTTPS)
///     .authority_str("auth.example.com").unwrap()
///     .path("/oauth/authorize")
///     .query_str("response_type=code&client_id=abc")
///     .build().unwrap();
///
/// assert!(uri.to_string().contains("https://auth.example.com"));
/// assert!(uri.to_string().contains("response_type=code"));
/// ```
#[derive(Clone, Debug, Default)]
pub struct UriBuilder {
    scheme: Option<Scheme>,
    authority: Option<Authority>,
    path: String,
    query: Option<String>,
    fragment: Option<String>,
}

impl UriBuilder {
    /// Creates a new empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the scheme.
    #[must_use]
    pub fn scheme(mut self, scheme: Scheme) -> Self {
        self.scheme = Some(scheme);
        self
    }

    /// Sets the authority from an [`Authority`] value.
    #[must_use]
    pub fn authority(mut self, authority: Authority) -> Self {
        self.authority = Some(authority);
        self
    }

    /// Parses and sets the authority from a string (e.g. "example.com:8080").
    ///
    /// # Errors
    ///
    /// Returns an error string if the authority cannot be parsed.
    pub fn authority_str(mut self, s: impl Into<String>) -> Result<Self, String> {
        let s = s.into();
        let authority = Authority::parse(&s).map_err(|e| e.to_string())?;
        self.authority = Some(authority);
        Ok(self)
    }

    /// Sets the path. Ensures it starts with '/'.
    #[must_use]
    pub fn path(mut self, path: impl Into<String>) -> Self {
        let p = path.into();
        self.path = if p.starts_with('/') { p } else { format!("/{p}") };
        self
    }

    /// Sets the query string (without leading '?').
    #[must_use]
    pub fn query_str(mut self, query: impl Into<String>) -> Self {
        let q = query.into();
        self.query = if q.is_empty() { None } else { Some(q) };
        self
    }

    /// Sets the query from a [`Query`] builder.
    #[must_use]
    pub fn query(mut self, query: Query) -> Self {
        let q = query.to_string();
        self.query = if q.is_empty() { None } else { Some(q) };
        self
    }

    /// Sets the fragment (without leading '#').
    #[must_use]
    pub fn fragment(mut self, fragment: impl Into<String>) -> Self {
        let f = fragment.into();
        self.fragment = if f.is_empty() { None } else { Some(f) };
        self
    }

    /// Builds the final [`Uri`].
    ///
    /// # Errors
    ///
    /// Returns an error if no scheme was set (scheme is required).
    pub fn build(self) -> Result<Uri, InvalidUri> {
        let scheme = self.scheme.ok_or_else(|| {
            InvalidUri::new("cannot build Uri without a scheme — call .scheme() first")
        })?;
        let path_and_query = PathAndQuery {
            path: if self.path.is_empty() {
                "/".to_string()
            } else if self.path.starts_with('/') {
                self.path
            } else {
                format!("/{}", self.path)
            },
            query: self
                .query
                .as_deref()
                .map(Query::parse)
                .transpose()
                .unwrap_or_default()
                .unwrap_or_default(),
        };
        Ok(Uri {
            scheme,
            authority: self.authority,
            path_and_query,
            fragment: self.fragment,
        })
    }
}

#[allow(clippy::from_over_into)]
impl Into<String> for Uri {
    fn into(self) -> String {
        format!("{self:}")
    }
}

// impl Uri {
//     pub fn to_string(&self) -> String {
//         format!("{self:}")
//     }
// }

impl fmt::Display for Uri {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // scheme:
        write!(f, "{}:", self.scheme)?;

        // //authority
        if let Some(auth) = &self.authority {
            write!(f, "//{auth}")?;
        }

        // path?query
        write!(f, "{}", self.path_and_query)?;

        // #fragment
        if let Some(frag) = &self.fragment {
            write!(f, "#{frag}")?;
        }

        Ok(())
    }
}