Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions Sources/CLI/support/AppleSupportService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import Foundation

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

#if DEBUG
protocol AppleSupportService: Sendable {
func fetchArticles(category: String?) async throws -> SupportArticlesCatalog
func fetchHelp() async throws -> SupportHelpCatalog
func fetchGuideContents(named name: String) async throws -> SupportGuideContents
func fetchGlossary(query: String?) async throws -> SupportGlossary
func fetchGlossaryEntry(term: String) async throws -> SupportGlossaryEntry
func fetchTerms(category: String?) async throws -> SupportTermsCatalog
func fetchTermsEntry(named name: String) async throws -> SupportTermsEntry
func fetchArticle(path: String) async throws -> SupportArticle
}
extension DefaultAppleSupportService: AppleSupportService {}
typealias DefaultAppleSupportServiceDependencies = AppleSupportClient
#else
typealias AppleSupportService = DefaultAppleSupportService<DefaultAppleSupportClient<URLSession>>
typealias DefaultAppleSupportServiceDependencies = DefaultAppleSupportClient<URLSession>
#endif

final class DefaultAppleSupportService<Dependencies: DefaultAppleSupportServiceDependencies>: Sendable {
private let dependencies: Dependencies

init(dependencies: Dependencies) {
self.dependencies = dependencies
}

func fetchArticles(category: String?) async throws -> SupportArticlesCatalog {
var catalog = try await parser(path: "support/articles").articles()
if let category {
guard catalog.categories.contains(where: { $0.id == category }) else {
throw SupportServiceError.notFound(kind: "article category", name: category)
}
catalog.categories = catalog.categories.filter { $0.id == category }
}
return catalog
}

func fetchHelp() async throws -> SupportHelpCatalog {
try await parser(path: "help").help()
}

func fetchGuideContents(named name: String) async throws -> SupportGuideContents {
guard !name.isEmpty,
name.unicodeScalars.allSatisfy({
CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789-").contains($0)
})
else { throw SupportServiceError.invalidGuideName }
return try await parser(path: "help/" + name).contents()
}

func fetchGlossary(query: String?) async throws -> SupportGlossary {
var glossary = try await parser(path: "help/glossary").glossary()
if let query {
glossary.entries = glossary.entries.filter { $0.term.localizedCaseInsensitiveContains(query) }
}
return glossary
}

func fetchGlossaryEntry(term: String) async throws -> SupportGlossaryEntry {
let glossary = try await fetchGlossary(query: nil)
guard let entry = glossary.entries.first(where: { $0.term.caseInsensitiveCompare(term) == .orderedSame }) else {
throw SupportServiceError.notFound(kind: "glossary term", name: term)
}
return entry
}

func fetchTerms(category: String?) async throws -> SupportTermsCatalog {
var catalog = try await parser(path: "support/terms").terms()
if let category {
guard catalog.categories.contains(where: { $0.id == category }) else {
throw SupportServiceError.notFound(kind: "terms category", name: category)
}
catalog.categories = catalog.categories.filter { $0.id == category }
}
return catalog
}

func fetchTermsEntry(named name: String) async throws -> SupportTermsEntry {
let catalog = try await fetchTerms(category: nil)
guard let entry = catalog.categories.flatMap(\.entries).first(where: { $0.id == name }) else {
throw SupportServiceError.notFound(kind: "terms entry", name: name)
}
return entry
}

func fetchArticle(path: String) async throws -> SupportArticle {
try await parser(path: path).article()
}

private func parser(path: String) async throws -> SupportHTMLParser {
let destination = try SupportDestination(path: path)
return try await SupportHTMLParser(document: dependencies.fetchHTML(at: destination))
}
}

enum SupportServiceError: Error, Equatable, LocalizedError {
case invalidGuideName
case notFound(kind: String, name: String)

var errorDescription: String? {
switch self {
case .invalidGuideName: return "Expected a guide identifier such as app-store-connect, not a path or URL."
case .notFound(let kind, let name): return "No Apple support \(kind) found for '\(name)'."
}
}
}
137 changes: 137 additions & 0 deletions Tests/CLITests/support/AppleSupportServiceTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import Foundation
import Logging
import Testing

@testable import CLI

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

@Suite("Apple support service")
struct AppleSupportServiceTests {
@Test("filters article categories using source identifiers")
func filtersCategories() async throws {
// -- Arrange --
let service = try service(
"support/articles",
"""
<main><h1>Articles</h1><p>Support</p>
<section class='section-category' id='membership'><h2>Membership</h2><p>Accounts</p>
<ul class='links'><a href='/support/account/'>Account</a></ul></section>
<section class='section-category' id='development'><h2>Development</h2><p>Tools</p>
<ul class='links'><a href='/support/xcode/'>Xcode</a></ul></section></main>
""")

// -- Act --
let catalog = try await service.fetchArticles(category: "development")

// -- Assert --
#expect(catalog.categories.map(\.id) == ["development"])
await #expect(throws: SupportServiceError.self) {
try await service.fetchArticles(category: "missing")
}
}

@Test("glossary name queries are case insensitive without matching definition text")
func queriesTerms() async throws {
// -- Arrange --
let service = try service("help/glossary", glossaryHTML)

// -- Act --
let list = try await service.fetchGlossary(query: "HOLDER")
let entry = try await service.fetchGlossaryEntry(term: "account holder")
let definitionOnly = try await service.fetchGlossary(query: "membership")

// -- Assert --
#expect(list.entries.map(\.term) == ["Account Holder"])
#expect(entry.term == "Account Holder")
#expect(definitionOnly.entries.isEmpty)
await #expect(throws: SupportServiceError.self) {
try await service.fetchGlossaryEntry(term: "Account")
}
}

@Test("terms entry lookup uses the source identifier and preserves resources")
func looksUpTermsEntry() async throws {
// -- Arrange --
let service = try service(
"support/terms",
"""
<main><h1>Terms</h1><p>Read carefully.</p><section class='section-terms'>
<h2 data-sidenav id='guidelines'>Guidelines</h2>
<h3 data-sidenav id='app-review-guidelines'>App Review Guidelines</h3><p>Review criteria.</p>
<p><a class='list-icon-document' href='/app-store/review/guidelines/'>View guidelines</a></p>
</section></main>
""")

// -- Act --
let entry = try await service.fetchTermsEntry(named: "app-review-guidelines")
let catalog = try await service.fetchTerms(category: "guidelines")

// -- Assert --
#expect(entry.title == "App Review Guidelines")
#expect(
entry.resources[0].link.url.absoluteString == "https://developer.apple.com/app-store/review/guidelines/")
#expect(catalog.categories.map(\.id) == ["guidelines"])
await #expect(throws: SupportServiceError.self) {
try await service.fetchTermsEntry(named: "missing")
}
}

@Test("document view parses only recognized content containers")
func fetchesArticle() async throws {
// -- Arrange --
let service = try service(
"support/fee-waiver",
"""
<main><div class='main-content'><span class='chapter-name'>Membership</span>
<article><h1>Fee waiver</h1><p>Eligible organizations.</p></article></div></main>
""")

// -- Act --
let article = try await service.fetchArticle(path: "support/fee-waiver")

// -- Assert --
#expect(article.title == "Fee waiver")
#expect(article.content == [.paragraph([.text("Eligible organizations.")])])
}

@Test(
"guide identifiers reject paths and cannot escape the guide root",
arguments: [
"../account", "app-store-connect/reference", "https://example.com", "", "app-store-connect?query=x",
])
func rejectsGuideIdentifier(name: String) async throws {
// -- Arrange --
let service = try service("help/glossary", glossaryHTML)

// -- Act --
let fetch = { try await service.fetchGuideContents(named: name) }

// -- Assert --
await #expect(throws: SupportServiceError.invalidGuideName) { try await fetch() }
}

private typealias Service = DefaultAppleSupportService<DefaultAppleSupportClient<HTTPTestTransport>>

private func service(_ path: String, _ html: String) throws -> Service {
let destination = try SupportDestination(path: path)
let response = try #require(
HTTPURLResponse(
url: destination.url, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "text/html"]))
let transport = HTTPTestTransport(responses: [
destination.url: .response(data: Data(html.utf8), response: response)
])
return DefaultAppleSupportService(
dependencies: DefaultAppleSupportClient(
logger: Logger(label: "test") { _ in SwiftLogNoOpLogHandler() }, dependencies: transport))
}
}

private let glossaryHTML = """
<main><h1>Glossary</h1><p>Definitions.</p><article class='article'>
<h2 class='article-title'>Account Holder</h2><div class='article-text'><p>Manages membership.</p></div></article>
<article class='article'><h2 class='article-title'>Admin</h2><div class='article-text'><p>Manages users.</p>
</div></article></main>
"""
Loading