Repository navigation
Expand file tree
/
Copy pathUserAgent.swift
More file actions
48 lines (40 loc) · 1.6 KB
/
Copy pathUserAgent.swift
File metadata and controls
48 lines (40 loc) · 1.6 KB
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
import Foundation
/// Identifies which Coder Desktop process is making a request.
public enum CoderComponent: String, Sendable {
case app = "coder-desktop"
case helper = "coder-desktop-core"
}
/// Go's `GOARCH` spelling, so a single pattern matches the CLI, the vpn-daemon and Desktop client.
enum GoArch: String, Sendable {
case arm64
case amd64
}
enum UserAgentDefaults {
static let goos = "darwin"
static let unknownVersion = "0.0.0"
#if arch(arm64)
static let arch: GoArch = .arm64
#elseif arch(x86_64)
static let arch: GoArch = .amd64
#endif
static var version: String {
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? unknownVersion
}
}
/// Formats a `User-Agent` as `<token>/<version> (<goos>/<goarch>)`.
public func userAgent(component: CoderComponent) -> String {
userAgent(component: component, version: UserAgentDefaults.version, arch: UserAgentDefaults.arch)
}
func userAgent(component: CoderComponent, version: String, arch: GoArch) -> String {
"\(component.rawValue)/\(version) (\(UserAgentDefaults.goos)/\(arch.rawValue))"
}
public extension URLRequest {
/// Sets the Coder `User-Agent`, unless `headers` already carries one.
mutating func setCoderUserAgent(_ component: CoderComponent, unlessIn headers: [HTTPHeader]) {
let callerSuppliedUA = headers.contains {
$0.name.caseInsensitiveCompare(Headers.userAgent) == .orderedSame
}
guard !callerSuppliedUA else { return }
setValue(userAgent(component: component), forHTTPHeaderField: Headers.userAgent)
}
}