File: URLTemplate.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (188 lines) | stat: -rw-r--r-- 6,673 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if canImport(CollectionsInternal)
internal import CollectionsInternal
#elseif canImport(OrderedCollections)
internal import OrderedCollections
#elseif canImport(_FoundationCollections)
internal import _FoundationCollections
#endif

extension URL {
    /// A template for constructing a URL from variable expansions.
    ///
    /// This is an template that can be expanded into
    /// a ``URL`` by calling ``URL(template:variables:)``.
    ///
    /// Templating has a rich set of options for substituting various parts of URLs. See
    /// [RFC 6570](https://datatracker.ietf.org/doc/html/rfc6570) for
    /// details.
    ///
    /// ### Example 1
    ///
    /// ```swift
    /// let template = URL.Template("http://www.example.com/foo{?query,number}")!
    /// let url = URL(
    ///     template: template,
    ///     variables: [
    ///         .query: "bar baz",
    ///         .number: "234",
    ///     ]
    /// )
    ///
    /// extension URL.Template.VariableName {
    ///     static var query: URL.Template.VariableName { .init("query") }
    ///     static var number: URL.Template.VariableName { .init("number") }
    /// }
    /// ```
    /// The resulting URL will be
    /// ```text
    /// http://www.example.com/foo?query=bar%20baz&number=234
    /// ```
    ///
    /// ### Usage
    ///
    /// Templates provide a description of a URL space and define how URLs can
    /// be constructed given specific variable values. Their intended use is,
    /// for example, to allow a server to communicate to a client how to
    /// construct URLs for particular resources.
    ///
    /// For each specific resource, an API contract is required to clearly
    /// define the variables applicable to that resource and its associated
    /// template. For example, such an API contract might specify that the
    /// variable `query` is mandatory and must be an alphanumeric string
    /// while the variable `number` is optional and must be a positive integer
    /// if provided. The server could then provide the client with a template
    /// such as `http://www.example.com/foo{?query,number}`, which the client
    /// can subsequently use to substitute variables accordingly.
    ///
    /// An API contract is necessary to define which substitutions are valid
    /// within a given URL space. There is no guarantee that every possible
    /// expansion of variable expressions corresponds to an existing resource
    /// URL; indeed, some expansions may not even produce a valid URL. Only
    /// the API specification itself can determine which expansions are
    /// expected to yield valid URLs corresponding to existing resources.
    ///
    /// ### Example 2
    ///
    /// Here’s an example, that illustrates how to define a specific set of variables:
    /// ```swift
    /// struct MyQueryTemplate: Sendable, Hashable {
    ///     var template: URL.Template
    ///
    ///     init?(_ template: String) {
    ///         guard let t = URL.Template(template) else { return nil }
    ///         self.template = t
    ///     }
    /// }
    ///
    /// struct MyQuery: Sendable, Hashable {
    ///     var query: String
    ///     var number: Int?
    ///
    ///     var variables: [URL.Template.VariableName: URL.Template.Value] {
    ///         var result: [URL.Template.VariableName: URL.Template.Value] = [
    ///             .query: .text(query)
    ///         ]
    ///         if let number {
    ///             result[.number] = .text("\(number)")
    ///         }
    ///         return result
    ///     }
    /// }
    ///
    /// extension URL.Template.VariableName {
    ///     static var query: URL.Template.VariableName { .init("query") }
    ///     static var number: URL.Template.VariableName { .init("number") }
    /// }
    ///
    /// extension URL {
    ///     init?(
    ///         template: MyQueryTemplate,
    ///         query: MyQuery
    ///     ) {
    ///         self.init(
    ///             template: template.template,
    ///             variables: query.variables
    ///         )
    ///     }
    /// }
    /// ```
    @available(FoundationPreview 6.2, *)
    public struct Template: Sendable, Hashable {
        var elements: [Element] = []

        enum Element: Sendable, Hashable {
            case literal(String)
            case expression(Expression)
        }
    }
}

// MARK: - Parse

@available(FoundationPreview 6.2, *)
extension URL.Template {
    /// Creates a new template from its text form.
    ///
    /// The template string needs to be a valid RFC 6570 template.
    ///
    /// This will parse the template and return `nil` if the template is invalid.
    public init?(_ template: String) {
        do {
            self.init()

            var remainder = template[...]

            func copyLiteral(upTo end: String.Index) {
                guard remainder.startIndex < end else { return }
                let literal = remainder[remainder.startIndex..<end]
                let escaped = String(literal).normalizedAddingPercentEncoding(
                    withAllowedCharacters: .unreservedReserved
                )
                elements.append(.literal(escaped))
            }

            while let match = remainder.firstMatch(of: URL.Template.Global.shared.uriTemplateRegex) {
                copyLiteral(upTo: match.range.lowerBound)
                let expression = try Expression(String(match.output.1))
                elements.append(.expression(expression))
                remainder = remainder[match.range.upperBound..<remainder.endIndex]
            }
            copyLiteral(upTo: remainder.endIndex)
        } catch {
            return nil
        }
    }
}

// MARK: -

@available(FoundationPreview 6.2, *)
extension URL.Template: CustomStringConvertible {
    public var description: String {
        elements.reduce(into: "") {
            $0.append("\($1)")
        }
    }
}

@available(FoundationPreview 6.2, *)
extension URL.Template.Element: CustomStringConvertible {
    var description: String {
        switch self {
        case .literal(let l): l
        case .expression(let e): "{\(e)}"
        }
    }
}