Fixes for the Localization package (#26)
This PR contains the work done to Reviewed-on: rock-n-code/loud-amsterdam#26 Co-authored-by: Javier Cicchelli <javier@rock-n-code.com> Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
/// The outcome of reading a String Catalog from its bundle.
|
||||
///
|
||||
/// The package degrades gracefully when a catalog cannot be read — lookups return their keys and the
|
||||
/// language list falls back to the default language — so nothing fails at the call site. This state is
|
||||
/// the signal a server checks once at startup to warn before visitors ever see raw localization keys.
|
||||
public enum CatalogState: Equatable, Sendable {
|
||||
|
||||
/// The catalog was found and decoded; its entries are resolvable.
|
||||
case loaded
|
||||
|
||||
/// No catalog resource exists in the bundle; every lookup returns its key.
|
||||
case missing
|
||||
|
||||
/// The catalog resource exists but is not valid `.xcstrings` JSON; every lookup returns its key.
|
||||
case undecodable
|
||||
|
||||
}
|
||||
@@ -12,6 +12,16 @@ public struct Localize: Sendable {
|
||||
/// The backend that resolves keys against the catalog.
|
||||
private let resolver: any CatalogResolving
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The outcome of reading the bundle's String Catalog.
|
||||
///
|
||||
/// Resolution degrades to returning raw keys rather than failing, so check this once at startup
|
||||
/// and warn when it is not ``CatalogState/loaded``.
|
||||
public var catalogState: CatalogState {
|
||||
resolver.state
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a localizer backed by the String Catalog in the given bundle.
|
||||
@@ -22,7 +32,7 @@ public struct Localize: Sendable {
|
||||
bundle: Bundle,
|
||||
table: String = "Localizable"
|
||||
) {
|
||||
self.init(resolver: StringCatalog(
|
||||
self.init(resolver: StringCatalog.cached(
|
||||
bundle: bundle,
|
||||
table: table
|
||||
))
|
||||
|
||||
@@ -4,7 +4,8 @@ import Foundation
|
||||
///
|
||||
/// Bound to a bundle's catalog languages via ``LanguageList``, an instance is invoked like a
|
||||
/// function — through ``callAsFunction(acceptLanguage:)`` — to resolve a header value to a
|
||||
/// supported language identifier, falling back to the default language.
|
||||
/// supported language identifier, honouring the header's `q` weights as RFC 9110 prescribes and
|
||||
/// falling back to the default language.
|
||||
public struct Negotiate: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
@@ -27,10 +28,12 @@ public struct Negotiate: Sendable {
|
||||
/// Picks the best supported language for the given `Accept-Language` header value.
|
||||
///
|
||||
/// Invoked by calling the instance directly, for example `negotiate(acceptLanguage: header)`.
|
||||
/// The header is split into its language tags (dropping any `q` weights), then each tag is matched
|
||||
/// against the supported languages in order of preference — first by an exact match, then by its
|
||||
/// primary language subtag, so `de-AT` resolves to a supported `de`. When the header is absent or
|
||||
/// matches nothing, the default language is returned.
|
||||
/// The header is parsed into its language ranges, which are ordered by descending `q` weight as
|
||||
/// RFC 9110 prescribes: an entry without a weight counts as 1, entries weighted 0 are
|
||||
/// "not acceptable" and dropped, and equal weights keep the header order. Each tag is then matched
|
||||
/// against the supported languages in turn — first by an exact match, then by its primary language
|
||||
/// subtag, so `de-AT` resolves to a supported `de` — while the `*` wildcard accepts the default
|
||||
/// language. When the header is absent or matches nothing, the default language is returned.
|
||||
/// - Parameter acceptLanguage: the raw `Accept-Language` header value, if any.
|
||||
/// - Returns: the identifier of the supported language to serve.
|
||||
public func callAsFunction(
|
||||
@@ -40,16 +43,20 @@ public struct Negotiate: Sendable {
|
||||
return list.default
|
||||
}
|
||||
|
||||
let tags = tags(from: language)
|
||||
let ranges = ranges(from: language)
|
||||
|
||||
guard !tags.isEmpty else {
|
||||
guard !ranges.isEmpty else {
|
||||
return list.default
|
||||
}
|
||||
|
||||
let supported = list.all
|
||||
|
||||
for tag in tags {
|
||||
if let match = match(tag: tag, in: supported) {
|
||||
for range in ranges {
|
||||
if range.tag == .wildcard {
|
||||
return list.default
|
||||
}
|
||||
|
||||
if let match = match(range.tag, in: supported) {
|
||||
return match
|
||||
}
|
||||
}
|
||||
@@ -65,27 +72,69 @@ private extension Negotiate {
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Extracts the ordered language tags from an `Accept-Language` header value.
|
||||
/// Parses an `Accept-Language` header value into its ``LanguageRange`` list, ordered by preference.
|
||||
///
|
||||
/// Each comma-separated entry is reduced to its language tag by dropping the `;q=` weight, and
|
||||
/// blank entries are removed. The original order is kept, which mirrors descending preference
|
||||
/// closely enough for `preferredLocalizations(from:forPreferences:)` to resolve correctly.
|
||||
/// Each comma-separated entry yields its language tag and `q` weight. The ranges are sorted by
|
||||
/// descending weight, entries weighted 0 are dropped as "not acceptable", and equally weighted
|
||||
/// entries keep the header order.
|
||||
/// - Parameter acceptLanguage: the raw `Accept-Language` header value.
|
||||
/// - Returns: the ordered, weight-stripped language tags.
|
||||
func tags(
|
||||
/// - Returns: the language ranges, most preferred first.
|
||||
func ranges(
|
||||
from acceptLanguage: String
|
||||
) -> [String] {
|
||||
) -> [LanguageRange] {
|
||||
acceptLanguage
|
||||
.split(separator: .Separator.comma)
|
||||
.map { entry in
|
||||
entry
|
||||
.split(separator: .Separator.semicolon)
|
||||
.first
|
||||
.map(String.init)?
|
||||
.trimmingCharacters(in: .whitespaces)
|
||||
?? .empty
|
||||
.compactMap(range(from:))
|
||||
.filter { $0.quality > 0 }
|
||||
.enumerated()
|
||||
.sorted { lhs, rhs in
|
||||
lhs.element.quality == rhs.element.quality
|
||||
? lhs.offset < rhs.offset
|
||||
: lhs.element.quality > rhs.element.quality
|
||||
}
|
||||
.filter { !$0.isEmpty }
|
||||
.map(\.element)
|
||||
}
|
||||
|
||||
/// Parses a single `Accept-Language` header entry into its ``LanguageRange``.
|
||||
///
|
||||
/// The entry's language tag precedes the first `;`; a `q` parameter after it sets the weight.
|
||||
/// A missing or malformed weight counts as 1, the highest preference, matching a tag sent
|
||||
/// without one.
|
||||
/// - Parameter entry: a single comma-separated header entry.
|
||||
/// - Returns: the entry's language range, or `nil` when it has no language tag.
|
||||
func range(
|
||||
from entry: Substring
|
||||
) -> LanguageRange? {
|
||||
let parts = entry.split(separator: .Separator.semicolon)
|
||||
let tag = parts.first
|
||||
.map(String.init)?
|
||||
.trimmingCharacters(in: .whitespaces)
|
||||
?? .empty
|
||||
|
||||
guard !tag.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let quality = parts
|
||||
.dropFirst()
|
||||
.compactMap { parameter -> Double? in
|
||||
let parameter = parameter
|
||||
.trimmingCharacters(in: .whitespaces)
|
||||
.lowercased()
|
||||
|
||||
guard parameter.hasPrefix(.Prefix.quality) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return Double(parameter.dropFirst(String.Prefix.quality.count))
|
||||
}
|
||||
.first
|
||||
?? 1
|
||||
|
||||
return .init(
|
||||
tag: tag,
|
||||
quality: quality
|
||||
)
|
||||
}
|
||||
|
||||
/// Finds the supported language that best matches a single `Accept-Language` tag.
|
||||
@@ -97,7 +146,7 @@ private extension Negotiate {
|
||||
/// - supported: the supported language identifiers.
|
||||
/// - Returns: the matching supported language, or `nil` when the tag matches none.
|
||||
func match(
|
||||
tag: String,
|
||||
_ tag: String,
|
||||
in supported: [String]
|
||||
) -> String? {
|
||||
let tag = tag.lowercased()
|
||||
@@ -117,10 +166,32 @@ private extension Negotiate {
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Character+Extensions
|
||||
|
||||
private extension Character {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
enum Separator {
|
||||
static let comma: Character = ","
|
||||
static let dash: Character = "-"
|
||||
static let semicolon: Character = ";"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - String+Extensions
|
||||
|
||||
private extension String {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
static let empty: String = ""
|
||||
static let wildcard: String = "*"
|
||||
|
||||
enum Prefix {
|
||||
static let quality = "q="
|
||||
}
|
||||
|
||||
/// The primary language subtag, i.e. everything before the first `-` (`de-AT` becomes `de`).
|
||||
var primarySubtag: String {
|
||||
@@ -130,13 +201,3 @@ private extension String {
|
||||
?? self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension Character {
|
||||
enum Separator {
|
||||
static let comma: Character = ","
|
||||
static let dash: Character = "-"
|
||||
static let semicolon: Character = ";"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,46 +8,47 @@ public struct LanguageList: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The language served when none of the supported languages match a request.
|
||||
///
|
||||
/// Should match the catalog bundle's development localization.
|
||||
public let `default`: String
|
||||
|
||||
/// The backend that reports the available languages.
|
||||
private let resolver: any CatalogResolving
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a language list backed by the given bundle.
|
||||
/// - Parameters:
|
||||
/// - bundle: the bundle whose String Catalog defines the available languages.
|
||||
/// - default: the language served when none of the supported languages match. Defaults to `"en"`.
|
||||
/// - Parameter bundle: the bundle whose String Catalog defines the available languages.
|
||||
public init(
|
||||
bundle: Bundle,
|
||||
`default`: String = "en"
|
||||
bundle: Bundle
|
||||
) {
|
||||
self.init(
|
||||
resolver: StringCatalog(bundle: bundle),
|
||||
default: `default`
|
||||
)
|
||||
self.init(resolver: StringCatalog.cached(bundle: bundle))
|
||||
}
|
||||
|
||||
/// Creates a language list backed by the given resolver.
|
||||
///
|
||||
/// The seam for tests and alternative backends; the public API derives languages from a bundled catalog.
|
||||
/// - Parameters:
|
||||
/// - resolver: the backend that reports the available languages.
|
||||
/// - default: the language served when none of the supported languages match.
|
||||
/// - Parameter resolver: the backend that reports the available languages.
|
||||
init(
|
||||
resolver: any CatalogResolving,
|
||||
`default`: String = "en"
|
||||
resolver: any CatalogResolving
|
||||
) {
|
||||
self.resolver = resolver
|
||||
self.`default` = `default`
|
||||
}
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The outcome of reading the bundle's String Catalog.
|
||||
///
|
||||
/// The list degrades to the default language rather than failing, so check this once at startup
|
||||
/// and warn when it is not ``CatalogState/loaded``.
|
||||
public var catalogState: CatalogState {
|
||||
resolver.state
|
||||
}
|
||||
|
||||
/// The language served when none of the supported languages match a request.
|
||||
///
|
||||
/// Always the catalog's source (development) language, so the default cannot drift from the
|
||||
/// bundle the list is bound to.
|
||||
public var `default`: String {
|
||||
resolver.sourceLanguage
|
||||
}
|
||||
|
||||
/// Every language the bundle's String Catalog provides a localization for.
|
||||
///
|
||||
/// The `Base` internationalization is excluded, as it is a development placeholder rather than a real language.
|
||||
|
||||
Reference in New Issue
Block a user