SPB Git

Repository Public

Models.swift 32.8 KB 664 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Core/Sources/SPSearchKit/Models.swift10// Description      : Codable models of the public search API, tolerant of11//                    missing or unknown fields.12// Module           : SPSearchKit13// Repository       : https://git.spboucher.ai/sp-search-ios14// Project Website  : https://search.spboucher.ai15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192/// Page type published by the API (`kind`): a deterministic heuristic, an indication rather than a certainty.93public enum PageKind: String, Sendable, CaseIterable, Hashable {94    case encyclopedia, documentation, news, article, blog, forum, shop, government, university, organisation, home, page9596    /// An unknown or missing value is shown as a plain page.97    public init(apiValue: String?) { self = apiValue.flatMap { PageKind(rawValue: $0.lowercased()) } ?? .page }98}99100/// Resolution level of the index for a page (AIRE): how much of its text is kept.101public enum ResolutionTier: Int, Sendable, Hashable {102    case unknown = 0, sparse = 1, standard = 2, premium = 3103    public init(apiValue: Int?) { self = apiValue.flatMap { ResolutionTier(rawValue: $0) } ?? .unknown }104}105106/// Which shape of the API a payload has. V2 texts are plain text whose highlight offsets must not be disturbed;107/// V1 texts may carry HTML entities and are decoded.108public enum APIVersion: Int, Sendable { case v1 = 1, v2 = 2 }109110extension CodingUserInfoKey {111    public static let apiVersion = CodingUserInfoKey(rawValue: "spsearch.apiVersion")!112}113114extension Decoder {115    var apiVersion: APIVersion { userInfo[.apiVersion] as? APIVersion ?? .v1 }116}117118/// Last technical check of the address by the crawler. It says nothing about whether the content is true.119public struct Validation: Decodable, Sendable, Hashable {120    public enum State: String, Sendable { case ok, changed, redirected, unreachable, unknown }121    public let state: State122    public let validatedAt: Date?123    public let httpStatus: Int?124125    enum CodingKeys: String, CodingKey { case state, validatedAt = "validated_at", httpStatus = "http_status" }126    public init(from decoder: Decoder) throws {127        let c = try decoder.container(keyedBy: CodingKeys.self)128        state = c.lenient(String.self, .state).flatMap(State.init(rawValue:)) ?? .unknown129        validatedAt = c.epoch(.validatedAt)130        httpStatus = c.lenient(Int.self, .httpStatus)131    }132    public init(state: State, validatedAt: Date? = nil, httpStatus: Int? = nil) {133        self.state = state; self.validatedAt = validatedAt; self.httpStatus = httpStatus134    }135}136137/// Another page of the same site, under the first result of a navigational search.138public struct Sitelink: Decodable, Sendable, Hashable, Identifiable {139    public let title: String140    public let url: String141    public var id: String { url }142    public var link: URL? { SearchResult.webLink(url) }143144    enum CodingKeys: String, CodingKey { case title, url }145    public init(from decoder: Decoder) throws {146        let c = try decoder.container(keyedBy: CodingKeys.self)147        url = try c.decode(String.self, forKey: .url)148        let t = (c.lenient(String.self, .title) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)149        title = t.isEmpty ? url : t150    }151    public init(title: String, url: String) { self.title = title; self.url = url }152}153154public struct SearchResult: Decodable, Identifiable, Sendable, Hashable {155    public let id: String156    /// Plain, untrusted text. Shown as text, never interpreted.157    public let title: String158    public let url: String159    public let domain: String160    /// Plain, untrusted text.161    public let snippet: String162    public let language: String?163    /// Last time the crawler verified the page. Never a publication date.164    public let checkedAt: Date?165    /// Publication date the engine could verify; often absent.166    public let publishedAt: Date?167    /// Indexed body words; 0 = unknown.168    public let words: Int169    public let kind: PageKind170    /// 0…1 percentile of the domain in the engine's own link graph; 0 = not scored yet.171    public let authority: Double172    public let tier: ResolutionTier173    /// "query" = passage chosen for this query; "static" = the page's description; "none" = the page forbids snippets.174    public let snippetSource: String?175    // V2176    /// Short address to show ("ulaval.ca"); nil when the server gave none.177    public let displayURL: String?178    public let siteName: String?179    /// Path of the site icon on the engine's own server (never the third-party site).180    public let faviconPath: String?181    /// True when the marks come from the server (V2): `highlights` is then the whole truth, even when empty.182    public let serverHighlights: Bool183    /// `[start, end)` in Unicode code points of `snippet`.184    public let highlights: [Range<Int>]185    /// `[start, end)` in Unicode code points of `title`.186    public let titleHighlights: [Range<Int>]187    public let validation: Validation?188    public let sitelinks: [Sitelink]189    /// Other candidates of the same site left out for diversity.190    public let moreFromSite: Int191192    /// The engine calls a domain a reference site from this percentile up.193    public static let referenceAuthority = 0.8194    public var isReferenceSite: Bool { authority >= Self.referenceAuthority }195    /// Reading time at 230 words a minute, at least one minute; nil when the length is unknown.196    public var readingMinutes: Int? { words > 0 ? max(1, Int((Double(words) / 230).rounded())) : nil }197    /// Only http and https addresses are opened.198    public var link: URL? { Self.webLink(url) }199200    public static func webLink(_ url: String) -> URL? {201        guard let u = URL(string: url), let s = u.scheme?.lowercased(), s == "http" || s == "https", u.host != nil else { return nil }202        return u203    }204205    enum CodingKeys: String, CodingKey {206        case id, title, url, domain, snippet, language, words, kind, authority, tier, favicon, highlights, validation, sitelinks207        case checkedAt = "checked_at", publishedAt = "published_at", snippetSource = "snippet_source"208        case displayURL = "display_url", siteName = "site_name", titleHighlights = "title_highlights", moreFromSite = "more_from_site"209    }210211    public init(from decoder: Decoder) throws {212        let c = try decoder.container(keyedBy: CodingKeys.self)213        let v2 = decoder.apiVersion == .v2214        url = try c.decode(String.self, forKey: .url)215        id = c.lenient(String.self, .id) ?? url216        let host = URL(string: url)?.host ?? ""217        domain = c.lenient(String.self, .domain) ?? host218        let rawTitle = c.lenient(String.self, .title) ?? ""219        let rawSnippet = c.lenient(String.self, .snippet) ?? ""220        if v2 {221            // Offsets of the marks count code points of the text as sent: it is kept untouched.222            title = rawTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? (host.isEmpty ? url : host) : rawTitle223            snippet = rawSnippet224        } else {225            let t = HTMLEntities.decode(rawTitle).trimmingCharacters(in: .whitespacesAndNewlines)226            title = t.isEmpty ? (host.isEmpty ? url : host) : t227            snippet = HTMLEntities.decode(rawSnippet).trimmingCharacters(in: .whitespacesAndNewlines)228        }229        language = c.lenient(String.self, .language).flatMap { $0.isEmpty ? nil : $0 }230        checkedAt = c.epoch(.checkedAt)231        publishedAt = c.epoch(.publishedAt)232        words = max(0, c.lenient(Int.self, .words) ?? 0)233        kind = PageKind(apiValue: c.lenient(String.self, .kind))234        authority = min(1, max(0, c.lenient(Double.self, .authority) ?? 0))235        tier = ResolutionTier(apiValue: c.lenient(Int.self, .tier))236        snippetSource = c.lenient(String.self, .snippetSource)237        displayURL = c.lenient(String.self, .displayURL).flatMap { $0.isEmpty ? nil : $0 }238        siteName = c.lenient(String.self, .siteName).flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }239        faviconPath = c.lenient(String.self, .favicon).flatMap { $0.isEmpty ? nil : $0 }240        serverHighlights = v2241        highlights = Self.ranges(c.lenient([Lossy<[Int]>].self, .highlights)?.compactMap(\.value))242        titleHighlights = Self.ranges(c.lenient([Lossy<[Int]>].self, .titleHighlights)?.compactMap(\.value))243        validation = c.lenient(Validation.self, .validation)244        sitelinks = Array((c.lenient([Lossy<Sitelink>].self, .sitelinks) ?? []).compactMap(\.value).filter { $0.link != nil }.prefix(4))245        moreFromSite = max(0, c.lenient(Int.self, .moreFromSite) ?? 0)246    }247248    /// Pairs that are not a forward interval are dropped.249    static func ranges(_ pairs: [[Int]]?) -> [Range<Int>] {250        (pairs ?? []).compactMap { $0.count == 2 && $0[0] >= 0 && $0[1] > $0[0] ? $0[0]..<$0[1] : nil }251    }252253    public init(id: String, title: String, url: String, domain: String, snippet: String = "", language: String? = nil,254                checkedAt: Date? = nil, publishedAt: Date? = nil, words: Int = 0, kind: PageKind = .page,255                authority: Double = 0, tier: ResolutionTier = .unknown, snippetSource: String? = nil,256                displayURL: String? = nil, siteName: String? = nil, faviconPath: String? = nil, serverHighlights: Bool = false,257                highlights: [Range<Int>] = [], titleHighlights: [Range<Int>] = [], validation: Validation? = nil,258                sitelinks: [Sitelink] = [], moreFromSite: Int = 0) {259        self.id = id; self.title = title; self.url = url; self.domain = domain; self.snippet = snippet; self.language = language260        self.checkedAt = checkedAt; self.publishedAt = publishedAt; self.words = words; self.kind = kind261        self.authority = authority; self.tier = tier; self.snippetSource = snippetSource262        self.displayURL = displayURL; self.siteName = siteName; self.faviconPath = faviconPath263        self.serverHighlights = serverHighlights; self.highlights = highlights; self.titleHighlights = titleHighlights264        self.validation = validation; self.sitelinks = sitelinks; self.moreFromSite = moreFromSite265    }266}267268public struct ResultTotal: Decodable, Sendable, Hashable {269    public enum Relation: String, Sendable { case exact = "eq", atLeast = "gte", estimate }270    public let value: Int271    public let relation: Relation272273    enum CodingKeys: String, CodingKey { case value, relation }274    public init(from decoder: Decoder) throws {275        let c = try decoder.container(keyedBy: CodingKeys.self)276        value = max(0, c.lenient(Int.self, .value) ?? 0)277        // An unknown relation is the weakest claim.278        relation = c.lenient(String.self, .relation).flatMap(Relation.init(rawValue:)) ?? .estimate279    }280    public init(value: Int, relation: Relation) { self.value = value; self.relation = relation }281}282283public struct Coverage: Decodable, Sendable, Hashable {284    public let documents: Int285    public let shardsOK: Int286    public let shardsTotal: Int287288    enum CodingKeys: String, CodingKey { case documents, shardsOK = "shards_ok", shardsTotal = "shards_total" }289    public init(from decoder: Decoder) throws {290        let c = try decoder.container(keyedBy: CodingKeys.self)291        documents = c.lenient(Int.self, .documents) ?? 0292        shardsOK = c.lenient(Int.self, .shardsOK) ?? 0293        shardsTotal = c.lenient(Int.self, .shardsTotal) ?? 0294    }295    public init(documents: Int = 0, shardsOK: Int = 0, shardsTotal: Int = 0) { self.documents = documents; self.shardsOK = shardsOK; self.shardsTotal = shardsTotal }296}297298public struct Facet: Decodable, Sendable, Hashable, Identifiable {299    public let value: String300    public let count: Int301    enum CodingKeys: String, CodingKey { case value, count }302    public init(from decoder: Decoder) throws {303        let c = try decoder.container(keyedBy: CodingKeys.self)304        value = try c.decode(String.self, forKey: .value)305        count = c.lenient(Int.self, .count) ?? 0306    }307    public var id: String { value }308    public init(value: String, count: Int) { self.value = value; self.count = count }309}310311/// Counts over the best ranked candidates of the query (at most `candidates`), not over the whole index.312public struct Facets: Decodable, Sendable, Hashable {313    public let domains: [Facet]314    public let languages: [Facet]315    public let kinds: [Facet]316    public let candidates: Int317318    enum CodingKeys: String, CodingKey { case domains, languages, kinds, candidates }319    public init(from decoder: Decoder) throws {320        let c = try decoder.container(keyedBy: CodingKeys.self)321        domains = (c.lenient([Lossy<Facet>].self, .domains) ?? []).compactMap(\.value)322        languages = (c.lenient([Lossy<Facet>].self, .languages) ?? []).compactMap(\.value)323        kinds = (c.lenient([Lossy<Facet>].self, .kinds) ?? []).compactMap(\.value)324        candidates = c.lenient(Int.self, .candidates) ?? 0325    }326    public init(domains: [Facet] = [], languages: [Facet] = [], kinds: [Facet] = [], candidates: Int = 0) {327        self.domains = domains; self.languages = languages; self.kinds = kinds; self.candidates = candidates328    }329}330331/// Region the server reports it applied to a search.332public struct AppliedRegion: Decodable, Sendable, Hashable {333    public enum Source: String, Sendable { case choice, browser, off, none }334    public let value: String?335    public let source: Source336337    enum CodingKeys: String, CodingKey { case value, source }338    public init(from decoder: Decoder) throws {339        let c = try decoder.container(keyedBy: CodingKeys.self)340        value = c.lenient(String.self, .value).flatMap { $0.isEmpty ? nil : $0 }341        source = c.lenient(String.self, .source).flatMap(Source.init(rawValue:)) ?? .none342    }343    public init(value: String?, source: Source) { self.value = value; self.source = source }344}345346/// Notice attached to a response; an unknown code is kept and shown as such.347public enum SearchNotice: Sendable, Hashable {348    case phraseUnsupported, phraseUnverified, relaxedToAnyTerm, depthLimit, partialShards, cursorExpired349    case degradedMetadata, semanticUnavailable350    case unknown(String)351352    public init(code: String) {353        switch code {354        case "phrase_unsupported": self = .phraseUnsupported355        case "phrase_unverified": self = .phraseUnverified356        case "relaxed_to_any_term": self = .relaxedToAnyTerm357        case "depth_limit": self = .depthLimit358        case "partial_shards": self = .partialShards359        case "cursor_expired": self = .cursorExpired360        case "degraded_metadata": self = .degradedMetadata361        case "semantic_unavailable": self = .semanticUnavailable362        default: self = .unknown(code)363        }364    }365}366367/// What the server understood of the query (V2).368public struct QueryInfo: Decodable, Sendable, Hashable {369    /// `applied`: the search ran on `suggestion` instead of `original`. Not applied with a suggestion: a mere proposal.370    public struct Correction: Decodable, Sendable, Hashable {371        public let applied: Bool372        public let original: String373        public let suggestion: String374375        enum CodingKeys: String, CodingKey { case applied, original, suggestion }376        public init(from decoder: Decoder) throws {377            let c = try decoder.container(keyedBy: CodingKeys.self)378            applied = c.lenient(Bool.self, .applied) ?? false379            original = c.lenient(String.self, .original) ?? ""380            suggestion = c.lenient(String.self, .suggestion) ?? ""381        }382        public init(applied: Bool, original: String, suggestion: String) {383            self.applied = applied; self.original = original; self.suggestion = suggestion384        }385    }386387    public let raw: String388    public let effective: String389    /// Detected language of the query, or nil ("und").390    public let language: String?391    /// `navigational`, `informational`, … an open set computed by rules.392    public let intent: String?393    public let correction: Correction?394    public let terms: [String]395396    public var isNavigational: Bool { intent == "navigational" }397398    enum CodingKeys: String, CodingKey { case raw, effective, language, intent, correction, terms }399    public init(from decoder: Decoder) throws {400        let c = try decoder.container(keyedBy: CodingKeys.self)401        raw = c.lenient(String.self, .raw) ?? ""402        effective = c.lenient(String.self, .effective) ?? raw403        language = c.lenient(String.self, .language).flatMap { $0.isEmpty || $0 == "und" ? nil : $0 }404        intent = c.lenient(String.self, .intent).flatMap { $0.isEmpty ? nil : $0 }405        // A correction without a suggestion, or one that suggests the query itself, proposes nothing.406        correction = c.lenient(Correction.self, .correction).flatMap { $0.suggestion.isEmpty || $0.suggestion == $0.original ? nil : $0 }407        terms = c.lenient([String].self, .terms) ?? []408    }409    public init(raw: String, effective: String? = nil, language: String? = nil, intent: String? = nil, correction: Correction? = nil, terms: [String] = []) {410        self.raw = raw; self.effective = effective ?? raw; self.language = language; self.intent = intent411        self.correction = correction; self.terms = terms412    }413}414415public struct SearchResponse: Decodable, Sendable {416    public let requestID: String417    public let results: [SearchResult]418    public let nextCursor: String?419    public let total: ResultTotal420    public let coverage: Coverage421    public let partial: Bool422    public let notices: [SearchNotice]423    public let indexVersion: Int424    public let elapsedMS: Int425    public let facets: Facets426    public let region: AppliedRegion?427    // V2428    public let ranker: String?429    public let query: QueryInfo?430    /// Related searches drawn from the index, never from anyone's history.431    public let related: [String]432433    enum CodingKeys: String, CodingKey {434        case results, total, coverage, partial, notices, facets, region, ranker, query, related, timing435        case requestID = "request_id", nextCursor = "next_cursor", indexVersion = "index_version", elapsedMS = "elapsed_ms"436    }437    private struct Timing: Decodable { let total_ms: Double? }438439    public init(from decoder: Decoder) throws {440        let c = try decoder.container(keyedBy: CodingKeys.self)441        requestID = c.lenient(String.self, .requestID) ?? ""442        // A malformed result is dropped; it does not make the whole page unreadable.443        results = (c.lenient([Lossy<SearchResult>].self, .results) ?? []).compactMap(\.value)444        nextCursor = c.lenient(String.self, .nextCursor).flatMap { $0.isEmpty ? nil : $0 }445        total = c.lenient(ResultTotal.self, .total) ?? ResultTotal(value: results.count, relation: .atLeast)446        coverage = c.lenient(Coverage.self, .coverage) ?? Coverage()447        partial = c.lenient(Bool.self, .partial) ?? false448        notices = (c.lenient([String].self, .notices) ?? []).map(SearchNotice.init(code:))449        indexVersion = c.lenient(Int.self, .indexVersion) ?? 0450        elapsedMS = c.lenient(Timing.self, .timing)?.total_ms.map { Int($0.rounded()) } ?? c.lenient(Int.self, .elapsedMS) ?? 0451        facets = c.lenient(Facets.self, .facets) ?? Facets()452        region = c.lenient(AppliedRegion.self, .region)453        ranker = c.lenient(String.self, .ranker)454        query = c.lenient(QueryInfo.self, .query)455        related = (c.lenient([String].self, .related) ?? []).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }456    }457458    public init(requestID: String = "", results: [SearchResult], nextCursor: String? = nil, total: ResultTotal? = nil,459                coverage: Coverage = Coverage(), partial: Bool = false, notices: [SearchNotice] = [], indexVersion: Int = 0,460                elapsedMS: Int = 0, facets: Facets = Facets(), region: AppliedRegion? = nil, ranker: String? = nil,461                query: QueryInfo? = nil, related: [String] = []) {462        self.requestID = requestID; self.results = results; self.nextCursor = nextCursor463        self.total = total ?? ResultTotal(value: results.count, relation: .exact)464        self.coverage = coverage; self.partial = partial; self.notices = notices; self.indexVersion = indexVersion465        self.elapsedMS = elapsedMS; self.facets = facets; self.region = region466        self.ranker = ranker; self.query = query; self.related = related467    }468}469470/// One line of `/v2/autocomplete`.471public struct Suggestion: Decodable, Sendable, Hashable, Identifiable {472    /// An unknown type is offered as a plain completion.473    public enum Kind: String, Sendable { case completion, site, correction }474    public let text: String475    public let kind: Kind476    /// For a site: its address and its name.477    public let url: String?478    public let title: String?479    public var id: String { "\(kind.rawValue):\(text)" }480    public var link: URL? { url.flatMap(SearchResult.webLink) }481482    enum CodingKeys: String, CodingKey { case text, type, url, title }483    public init(from decoder: Decoder) throws {484        // The V1 list is made of bare strings.485        if let s = try? decoder.singleValueContainer().decode(String.self) {486            text = s.trimmingCharacters(in: .whitespaces); kind = .completion; url = nil; title = nil487            return488        }489        let c = try decoder.container(keyedBy: CodingKeys.self)490        text = (c.lenient(String.self, .text) ?? "").trimmingCharacters(in: .whitespaces)491        kind = c.lenient(String.self, .type).flatMap(Kind.init(rawValue:)) ?? .completion492        url = c.lenient(String.self, .url).flatMap { $0.isEmpty ? nil : $0 }493        title = c.lenient(String.self, .title).flatMap { $0.isEmpty ? nil : $0 }494    }495    public init(text: String, kind: Kind = .completion, url: String? = nil, title: String? = nil) {496        self.text = text; self.kind = kind; self.url = url; self.title = title497    }498}499500struct AutocompleteResponse: Decodable {501    let suggestions: [Suggestion]502    enum CodingKeys: String, CodingKey { case suggestions }503    init(from decoder: Decoder) throws {504        let c = try decoder.container(keyedBy: CodingKeys.self)505        suggestions = Array((c.lenient([Lossy<Suggestion>].self, .suggestions) ?? []).compactMap(\.value).filter { !$0.text.isEmpty }.prefix(8))506    }507}508509/// `/v2/filters`: what the index really lets one filter on. The interface shows nothing that is not listed here.510public struct FilterCatalog: Decodable, Sendable, Hashable {511    public struct Vertical: Decodable, Sendable, Hashable, Identifiable {512        public let id: String513        public let documents: Int514        enum CodingKeys: String, CodingKey { case id, documents }515        public init(from decoder: Decoder) throws {516            let c = try decoder.container(keyedBy: CodingKeys.self)517            id = try c.decode(String.self, forKey: .id)518            documents = c.lenient(Int.self, .documents) ?? 0519        }520        public init(id: String, documents: Int = 0) { self.id = id; self.documents = documents }521    }522    public struct Language: Decodable, Sendable, Hashable, Identifiable {523        public let value: String524        public let documents: Int525        public var id: String { value }526        enum CodingKeys: String, CodingKey { case value, documents }527        public init(from decoder: Decoder) throws {528            let c = try decoder.container(keyedBy: CodingKeys.self)529            value = try c.decode(String.self, forKey: .value)530            documents = c.lenient(Int.self, .documents) ?? 0531        }532        public init(value: String, documents: Int = 0) { self.value = value; self.documents = documents }533    }534535    public let verticals: [Vertical]536    public let languages: [Language]537    public let kinds: [String]538    public let regions: [String]539    public let fresh: [String]540541    /// What is offered before the server answered, and on a V1 server: the Web, nothing else.542    public static let minimal = FilterCatalog(verticals: [Vertical(id: "web")], languages: [], kinds: [],543                                              regions: ["ca", "ca-qc", "fr", "ch", "be", "us", "gb"], fresh: [])544545    enum CodingKeys: String, CodingKey { case verticals, languages, kinds, regions, fresh }546    public init(from decoder: Decoder) throws {547        let c = try decoder.container(keyedBy: CodingKeys.self)548        let v = (c.lenient([Lossy<Vertical>].self, .verticals) ?? []).compactMap(\.value).filter { !$0.id.isEmpty }549        verticals = v.isEmpty ? [Vertical(id: "web")] : v550        languages = (c.lenient([Lossy<Language>].self, .languages) ?? []).compactMap(\.value).filter { !$0.value.isEmpty }551        kinds = (c.lenient([String].self, .kinds) ?? []).filter { !$0.isEmpty }552        regions = (c.lenient([String].self, .regions) ?? []).filter { !$0.isEmpty }553        fresh = (c.lenient([String].self, .fresh) ?? []).filter { !$0.isEmpty }554    }555    public init(verticals: [Vertical], languages: [Language] = [], kinds: [String] = [], regions: [String] = [], fresh: [String] = []) {556        self.verticals = verticals; self.languages = languages; self.kinds = kinds; self.regions = regions; self.fresh = fresh557    }558}559560/// `/v2/status`: public state of the services and of the index.561public struct EngineStatus: Decodable, Sendable, Hashable {562    public enum Level: String, Sendable { case ok, degraded, down, off, unknown }563    public let level: Level564    public let ranker: String?565    public let documents: Int566    public let domains: Int567    public let indexVersion: Int568    public let updatedAt: Date?569    public let medianAgeSeconds: Int?570    public let validated24h: Int?571    /// Service name → state, as published.572    public let services: [String: Level]573574    enum CodingKeys: String, CodingKey { case status, ranker, index, services }575    enum IndexKeys: String, CodingKey { case documents, domains, version, updatedAt = "updated_at", medianAge = "median_age_s", validated = "validated_24h" }576    public init(from decoder: Decoder) throws {577        let c = try decoder.container(keyedBy: CodingKeys.self)578        level = c.lenient(String.self, .status).flatMap(Level.init(rawValue:)) ?? .unknown579        ranker = c.lenient(String.self, .ranker)580        let i = try? c.nestedContainer(keyedBy: IndexKeys.self, forKey: .index)581        documents = i?.lenient(Int.self, .documents) ?? 0582        domains = i?.lenient(Int.self, .domains) ?? 0583        indexVersion = i?.lenient(Int.self, .version) ?? 0584        updatedAt = i?.epoch(.updatedAt)585        medianAgeSeconds = i?.lenient(Int.self, .medianAge)586        validated24h = i?.lenient(Int.self, .validated)587        services = (c.lenient([String: String].self, .services) ?? [:]).mapValues { Level(rawValue: $0) ?? .unknown }588    }589    public init(level: Level = .unknown, ranker: String? = nil, documents: Int, domains: Int, indexVersion: Int = 0, updatedAt: Date? = nil,590                medianAgeSeconds: Int? = nil, validated24h: Int? = nil, services: [String: Level] = [:]) {591        self.level = level; self.ranker = ranker; self.documents = documents; self.domains = domains; self.indexVersion = indexVersion592        self.updatedAt = updatedAt; self.medianAgeSeconds = medianAgeSeconds; self.validated24h = validated24h; self.services = services593    }594    /// A V1 server publishes figures only: the state of its services is unknown.595    public init(stats: IndexStats) {596        self.init(level: .unknown, documents: stats.documents, domains: stats.domains, indexVersion: stats.indexVersion, updatedAt: stats.updatedAt)597    }598}599600public struct IndexStats: Decodable, Sendable, Hashable {601    public struct LanguageCount: Decodable, Sendable, Hashable {602        public let language: String603        public let documents: Int604    }605    public let documents: Int606    public let domains: Int607    public let languages: [LanguageCount]608    public let indexBytes: Int64609    public let bytesPerDoc: Int610    public let updatedAt: Date?611    public let indexVersion: Int612613    enum CodingKeys: String, CodingKey {614        case documents, domains, languages615        case indexBytes = "index_bytes", bytesPerDoc = "bytes_per_doc", updatedAt = "updated_at", indexVersion = "index_version"616    }617    public init(from decoder: Decoder) throws {618        let c = try decoder.container(keyedBy: CodingKeys.self)619        documents = c.lenient(Int.self, .documents) ?? 0620        domains = c.lenient(Int.self, .domains) ?? 0621        languages = c.lenient([LanguageCount].self, .languages) ?? []622        indexBytes = c.lenient(Int64.self, .indexBytes) ?? 0623        bytesPerDoc = c.lenient(Int.self, .bytesPerDoc) ?? 0624        updatedAt = c.epoch(.updatedAt)625        indexVersion = c.lenient(Int.self, .indexVersion) ?? 0626    }627    public init(documents: Int, domains: Int, languages: [LanguageCount] = [], indexBytes: Int64 = 0, bytesPerDoc: Int = 0, updatedAt: Date? = nil, indexVersion: Int = 0) {628        self.documents = documents; self.domains = domains; self.languages = languages; self.indexBytes = indexBytes629        self.bytesPerDoc = bytesPerDoc; self.updatedAt = updatedAt; self.indexVersion = indexVersion630    }631}632633struct SuggestResponse: Decodable {634    let suggestions: [String]635    enum CodingKeys: String, CodingKey { case suggestions }636    init(from decoder: Decoder) throws {637        let c = try decoder.container(keyedBy: CodingKeys.self)638        suggestions = c.lenient([String].self, .suggestions) ?? []639    }640}641642struct APIErrorBody: Decodable {643    struct Detail: Decodable { let code: String?; let message: String? }644    let error: Detail?645    let request_id: String?646}647648/// Element of an array that may fail to decode without failing the array.649struct Lossy<T: Decodable>: Decodable {650    let value: T?651    init(from decoder: Decoder) throws { value = try? T(from: decoder) }652}653654extension KeyedDecodingContainer {655    /// A missing key, a null or a value of the wrong type all read as nil.656    func lenient<T: Decodable>(_ type: T.Type, _ key: Key) -> T? { (try? decodeIfPresent(type, forKey: key)) ?? nil }657658    /// Unix seconds (integer or decimal); zero and negatives mean "unknown".659    func epoch(_ key: Key) -> Date? {660        guard let s = lenient(Double.self, key), s > 0 else { return nil }661        return Date(timeIntervalSince1970: s)662    }663}664
Files main
Menu

Theme