diff --git a/Sources/CLI/cmd/support/SupportArticlesCommand.swift b/Sources/CLI/cmd/support/SupportArticlesCommand.swift new file mode 100644 index 0000000..73c9fb4 --- /dev/null +++ b/Sources/CLI/cmd/support/SupportArticlesCommand.swift @@ -0,0 +1,21 @@ +import ArgumentParser + +struct SupportArticlesCommand: AsyncParsableCommand, GlobalOptionsProviding { + @OptionGroup var global: GlobalOptions + + static let configuration = CommandConfiguration( + commandName: "articles", abstract: "Discover categorized support resources.", + subcommands: [SupportArticlesListCommand.self]) +} + +struct SupportArticlesListCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "Filter by a source category identifier, such as membership.") + var category: String? + + static let configuration = CommandConfiguration( + commandName: "list", abstract: "List support article categories and their resource links.") + + var request: SupportRequest { .articles(category: category) } +} diff --git a/Sources/CLI/cmd/support/SupportCommand.swift b/Sources/CLI/cmd/support/SupportCommand.swift new file mode 100644 index 0000000..e8c0093 --- /dev/null +++ b/Sources/CLI/cmd/support/SupportCommand.swift @@ -0,0 +1,45 @@ +import ArgumentParser + +struct SupportCommand: AsyncParsableCommand, GlobalOptionsProviding { + @OptionGroup var global: GlobalOptions + + static let configuration = CommandConfiguration( + commandName: "support", + abstract: "Browse Apple support resources and read supported HTML content.", + subcommands: [ + SupportArticlesCommand.self, SupportGuidesCommand.self, SupportGlossaryCommand.self, + SupportTermsCommand.self, SupportViewCommand.self, + ]) +} + +protocol SupportExecutableCommand: AsyncParsableCommand, GlobalOptionsProviding { + var output: OutputOptions { get } + var request: SupportRequest { get } +} + +extension SupportExecutableCommand { + mutating func run() async throws { + try await run(deps: AppleDocs.dependencies) + } + + func run(deps: SupportCommandDependencies) async throws { + deps.telemetry.startCommand( + TelemetryCommandContext( + command: request.commandName, outputJSON: output.json, technology: nil, typeName: nil)) + let runner = SupportCommandRunner( + service: deps.supportService, renderer: deps.supportRenderer(output: output)) + deps.commandOutputWriter.write(try await runner.run(request)) + } +} + +struct SupportViewCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "A supported path relative to developer.apple.com, including help/ or support/.") + var path: String + + static let configuration = CommandConfiguration( + commandName: "view", abstract: "Read a supported HTML document. PDFs and unknown layouts are not parsed.") + + var request: SupportRequest { .article(path: path) } +} diff --git a/Sources/CLI/cmd/support/SupportCommandRunner.swift b/Sources/CLI/cmd/support/SupportCommandRunner.swift new file mode 100644 index 0000000..7956be2 --- /dev/null +++ b/Sources/CLI/cmd/support/SupportCommandRunner.swift @@ -0,0 +1,48 @@ +enum SupportRequest: Sendable { + case articles(category: String?) + case helpCatalog + case contents(name: String) + case glossary(query: String?) + case glossaryEntry(term: String) + case terms(category: String?) + case termsEntry(name: String) + case article(path: String) + + var commandName: String { + switch self { + case .articles: return "support.articles.list" + case .helpCatalog: return "support.guides.list" + case .contents: return "support.guides.contents" + case .glossary: return "support.glossary.list" + case .glossaryEntry: return "support.glossary.view" + case .terms: return "support.terms.list" + case .termsEntry: return "support.terms.view" + case .article: return "support.view" + } + } +} + +struct SupportCommandRunner: Sendable { + private let service: AppleSupportService + private let renderer: SupportRenderer + + init(service: AppleSupportService, renderer: SupportRenderer) { + self.service = service + self.renderer = renderer + } + + func run(_ request: SupportRequest) async throws -> String { + let payload: SupportPayload + switch request { + case .articles(let category): payload = .articles(try await service.fetchArticles(category: category)) + case .helpCatalog: payload = .help(try await service.fetchHelp()) + case .contents(let name): payload = .contents(try await service.fetchGuideContents(named: name)) + case .glossary(let query): payload = .glossary(try await service.fetchGlossary(query: query)) + case .glossaryEntry(let term): payload = .glossaryEntry(try await service.fetchGlossaryEntry(term: term)) + case .terms(let category): payload = .terms(try await service.fetchTerms(category: category)) + case .termsEntry(let name): payload = .termsEntry(try await service.fetchTermsEntry(named: name)) + case .article(let path): payload = .article(try await service.fetchArticle(path: path)) + } + return try renderer.render(payload) + } +} diff --git a/Sources/CLI/cmd/support/SupportGlossaryCommand.swift b/Sources/CLI/cmd/support/SupportGlossaryCommand.swift new file mode 100644 index 0000000..612ab80 --- /dev/null +++ b/Sources/CLI/cmd/support/SupportGlossaryCommand.swift @@ -0,0 +1,33 @@ +import ArgumentParser + +struct SupportGlossaryCommand: AsyncParsableCommand, GlobalOptionsProviding { + @OptionGroup var global: GlobalOptions + + static let configuration = CommandConfiguration( + commandName: "glossary", abstract: "Look up terms used in Apple development and distribution.", + subcommands: [SupportGlossaryListCommand.self, SupportGlossaryViewCommand.self]) +} + +struct SupportGlossaryListCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "Filter term names by a case-insensitive substring, not definition text.") + var query: String? + + static let configuration = CommandConfiguration( + commandName: "list", abstract: "List glossary terms and structured definitions.") + + var request: SupportRequest { .glossary(query: query) } +} + +struct SupportGlossaryViewCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "The exact displayed term, matched case-insensitively.") + var term: String + + static let configuration = CommandConfiguration( + commandName: "view", abstract: "Show one glossary definition.") + + var request: SupportRequest { .glossaryEntry(term: term) } +} diff --git a/Sources/CLI/cmd/support/SupportGuidesCommand.swift b/Sources/CLI/cmd/support/SupportGuidesCommand.swift new file mode 100644 index 0000000..a572f93 --- /dev/null +++ b/Sources/CLI/cmd/support/SupportGuidesCommand.swift @@ -0,0 +1,31 @@ +import ArgumentParser + +struct SupportGuidesCommand: AsyncParsableCommand, GlobalOptionsProviding { + @OptionGroup var global: GlobalOptions + + static let configuration = CommandConfiguration( + commandName: "guides", abstract: "Discover help resources and browse supported guide contents.", + subcommands: [SupportGuidesListCommand.self, SupportGuidesContentsCommand.self]) +} + +struct SupportGuidesListCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + + static let configuration = CommandConfiguration( + commandName: "list", abstract: "List featured help resources, topic groups, and the glossary.") + + var request: SupportRequest { .helpCatalog } +} + +struct SupportGuidesContentsCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "The guide identifier, such as app-store-connect.") + var name: String + + static let configuration = CommandConfiguration( + commandName: "contents", abstract: "Show the embedded table of contents for a supported guide.") + + var request: SupportRequest { .contents(name: name) } +} diff --git a/Sources/CLI/cmd/support/SupportTermsCommand.swift b/Sources/CLI/cmd/support/SupportTermsCommand.swift new file mode 100644 index 0000000..4d2c842 --- /dev/null +++ b/Sources/CLI/cmd/support/SupportTermsCommand.swift @@ -0,0 +1,34 @@ +import ArgumentParser + +struct SupportTermsCommand: AsyncParsableCommand, GlobalOptionsProviding { + @OptionGroup var global: GlobalOptions + + static let configuration = CommandConfiguration( + commandName: "terms", abstract: "Browse the agreements and guidelines catalog.", + subcommands: [SupportTermsListCommand.self, SupportTermsViewCommand.self]) +} + +struct SupportTermsListCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "Filter by a source category identifier, such as guidelines.") + var category: String? + + static let configuration = CommandConfiguration( + commandName: "list", abstract: "List agreements, guidelines, and their available resources.") + + var request: SupportRequest { .terms(category: category) } +} + +struct SupportTermsViewCommand: SupportExecutableCommand { + @OptionGroup var global: GlobalOptions + @OptionGroup var output: OutputOptions + @Option(help: "The terms entry identifier returned by the catalog.") + var name: String + + static let configuration = CommandConfiguration( + commandName: "view", + abstract: "Show a catalog entry and its translations, not the linked legal document.") + + var request: SupportRequest { .termsEntry(name: name) } +} diff --git a/Sources/CLI/main/CLI.swift b/Sources/CLI/main/CLI.swift index 51e20ca..6bb4c49 100644 --- a/Sources/CLI/main/CLI.swift +++ b/Sources/CLI/main/CLI.swift @@ -13,6 +13,7 @@ struct CLI: AsyncParsableCommand, GlobalOptionsProviding { subcommands: [ TypesCommand.self, TechnologiesCommand.self, + SupportCommand.self, CacheCommand.self, AgentCommand.self, ] diff --git a/Sources/CLI/main/Dependencies.swift b/Sources/CLI/main/Dependencies.swift index db418f0..5da12a1 100644 --- a/Sources/CLI/main/Dependencies.swift +++ b/Sources/CLI/main/Dependencies.swift @@ -12,6 +12,7 @@ struct Dependencies: Sendable { let httpCache: URLCache? let httpDataTransport: URLSession let documentationRepository: DefaultAppleDocumentationRepository> + let supportService: DefaultAppleSupportService> init(telemetry: DefaultTelemetry) { self.telemetry = telemetry @@ -33,6 +34,9 @@ struct Dependencies: Sendable { configuration.urlCache = httpCache } httpDataTransport = URLSession(configuration: configuration) + supportService = DefaultAppleSupportService( + dependencies: DefaultAppleSupportClient( + logger: Logger(label: "com.techprimate.apple-docs.support.client"), dependencies: httpDataTransport)) documentationRepository = DefaultAppleDocumentationRepository( logger: Logger(label: "com.techprimate.apple-docs.repository"), dependencies: DefaultAppleDocumentationClient( diff --git a/Sources/CLI/main/SupportDependencies.swift b/Sources/CLI/main/SupportDependencies.swift new file mode 100644 index 0000000..957ced5 --- /dev/null +++ b/Sources/CLI/main/SupportDependencies.swift @@ -0,0 +1,24 @@ +#if DEBUG + protocol AppleSupportServiceProvider { + associatedtype SupportService: AppleSupportService + var supportService: SupportService { get } + } + + protocol SupportRendererProvider { + associatedtype SupportOutputRenderer: SupportRenderer + func supportRenderer(output: OutputOptions) -> SupportOutputRenderer + } + + typealias SupportCommandDependencies = any ( + AppleSupportServiceProvider & SupportRendererProvider & CommandOutputWriterProvider & TelemetryProvider + ) + extension Dependencies: AppleSupportServiceProvider, SupportRendererProvider {} +#else + typealias SupportCommandDependencies = Dependencies +#endif + +extension Dependencies { + func supportRenderer(output: OutputOptions) -> DefaultSupportRenderer { + DefaultSupportRenderer(output: output.format, audience: output.audience) + } +} diff --git a/Sources/CLI/renderer/SupportContentEncoding.swift b/Sources/CLI/renderer/SupportContentEncoding.swift index 0f269b1..caa82a3 100644 --- a/Sources/CLI/renderer/SupportContentEncoding.swift +++ b/Sources/CLI/renderer/SupportContentEncoding.swift @@ -1,7 +1,7 @@ import Foundation extension SupportInline { - private enum CodingKeys: CodingKey { case type, text, content, label, url, alt } + private enum CodingKeys: CodingKey { case type, text, content, label, url, alt, name } func encode(to encoder: any Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -29,6 +29,10 @@ extension SupportInline { try container.encode("link", forKey: .type) try container.encode(label, forKey: .label) try container.encode(url, forKey: .url) + case .anchor(let name, let content): + try container.encode("anchor", forKey: .type) + try container.encode(name, forKey: .name) + try container.encode(content, forKey: .content) case .lineBreak: try container.encode("lineBreak", forKey: .type) } diff --git a/Sources/CLI/renderer/SupportTextRenderer.swift b/Sources/CLI/renderer/SupportTextRenderer.swift index 5b5117e..f592632 100644 --- a/Sources/CLI/renderer/SupportTextRenderer.swift +++ b/Sources/CLI/renderer/SupportTextRenderer.swift @@ -47,7 +47,10 @@ struct SupportTextRenderer { return termsEntry(value, level: 1) case .article(let value): return [ - heading(value.title, level: 1), value.url.absoluteString, plain(value.context ?? ""), + heading(value.title, level: 1), value.url.absoluteString, + plain( + value.breadcrumbs.isEmpty + ? value.context ?? "" : value.breadcrumbs.map(\.title).joined(separator: " > ")), blocks(value.content), ] + (value.related.isEmpty ? [] : [heading("Related", level: 2)] + value.related.map(reference)) @@ -117,6 +120,7 @@ struct SupportTextRenderer { return agent ? markdown.link(inline(label), target: .external(url)) : inline(label) + " (" + url.absoluteString + ")" + case .anchor(_, let content): return inline(content) case .lineBreak: return "\n" } }.joined() diff --git a/Sources/CLI/support/SupportContent.swift b/Sources/CLI/support/SupportContent.swift index 1c44959..38e09ef 100644 --- a/Sources/CLI/support/SupportContent.swift +++ b/Sources/CLI/support/SupportContent.swift @@ -8,6 +8,7 @@ indirect enum SupportInline: Encodable, Equatable, Sendable { case superscript([SupportInline]) case link(label: [SupportInline], url: URL) case image(url: URL, alt: String) + case anchor(name: String, content: [SupportInline]) case lineBreak } @@ -33,10 +34,16 @@ struct SupportTableCell: Encodable, Equatable, Sendable { let rowSpan: Int } +struct SupportBreadcrumb: Encodable, Equatable, Sendable { + let title: String + let url: URL? +} + struct SupportArticle: Encodable, Equatable, Sendable { let url: URL let title: String let context: String? + var breadcrumbs: [SupportBreadcrumb] = [] let content: [SupportContentBlock] let related: [SupportPageLink] let notices: [SupportContentBlock] diff --git a/Sources/CLI/support/SupportHTMLParser+Content.swift b/Sources/CLI/support/SupportHTMLParser+Content.swift index cfc6386..cb7d01d 100644 --- a/Sources/CLI/support/SupportHTMLParser+Content.swift +++ b/Sources/CLI/support/SupportHTMLParser+Content.swift @@ -10,7 +10,7 @@ extension SupportHTMLParser { guard let child = node as? Element, !ignored(child) else { return [] } let content = try inline(in: child) switch child.tagName() { - case "a": return [.link(label: content, url: try resolve(child.attr("href")))] + case "a": return try inlineLink(child, content: content) case "em", "i": return [.emphasis(content)] case "strong", "b": return [.strong(content)] case "sup": return [.superscript(content)] @@ -24,6 +24,14 @@ extension SupportHTMLParser { } } + private func inlineLink(_ element: Element, content: [SupportInline]) throws -> [SupportInline] { + if element.hasAttr("href") { + return [.link(label: content, url: try resolve(element.attr("href")))] + } + let name = try element.hasAttr("id") ? element.attr("id") : element.attr("name") + return name.isEmpty ? content : [.anchor(name: name, content: content)] + } + func blocks(in element: Element) throws -> [SupportContentBlock] { var result: [SupportContentBlock] = [] var pending: [SupportInline] = [] diff --git a/Sources/CLI/support/SupportHTMLParser.swift b/Sources/CLI/support/SupportHTMLParser.swift index 5d41134..5ec0e4f 100644 --- a/Sources/CLI/support/SupportHTMLParser.swift +++ b/Sources/CLI/support/SupportHTMLParser.swift @@ -29,11 +29,22 @@ struct SupportHTMLParser { var layoutError: SupportParsingError { .unsupportedLayout(source.destination.path) } + func canonicalURL() throws -> URL { + guard let canonical = try document.select("link[rel=canonical][href]").first() else { + return source.destination.url + } + let url = try resolve(canonical.attr("href")) + guard let destination = try? SupportDestination(responseURL: url) else { + throw SupportParsingError.invalidLink + } + return destination.url + } + func header(in root: Element? = nil) throws -> SupportPageHeader { let root = try root ?? required("main") let heading = try required("h1", in: root) return SupportPageHeader( - url: source.destination.url, title: try nonemptyText(heading), + url: try canonicalURL(), title: try nonemptyText(heading), introduction: try heading.nextElementSibling()?.tagName() == "p" ? heading.nextElementSibling()?.text() ?? "" : "") } @@ -102,13 +113,25 @@ struct SupportHTMLParser { let content = try blocks(in: article) guard !content.isEmpty else { throw layoutError } return SupportArticle( - url: source.destination.url, title: try nonemptyText(heading), + url: try canonicalURL(), title: try nonemptyText(heading), context: try document.select("main .chapter-name").first()?.text(), + breadcrumbs: try breadcrumbs(), content: content, related: try article.select(".LinkUniversal a[href]").array().map(link), notices: try document.select("footer .footer-sosumi").array().flatMap { try blocks(in: $0) }) } + private func breadcrumbs() throws -> [SupportBreadcrumb] { + guard let container = try document.select("main .header2 p.custom-text").first() else { return [] } + return try container.children().array().filter { + !$0.hasClass("breadcrumb-spacer") + }.map { element in + SupportBreadcrumb( + title: try nonemptyText(element), + url: element.hasAttr("href") ? try resolve(element.attr("href")) : nil) + } + } + func contents() throws -> SupportGuideContents { let root = try required("main nav.sidenav ul.sidenav-list") let entries = try contentsEntries(root) diff --git a/Tests/CLIIntegrationTests/SupportCommandIntegrationTests.swift b/Tests/CLIIntegrationTests/SupportCommandIntegrationTests.swift new file mode 100644 index 0000000..7a52a62 --- /dev/null +++ b/Tests/CLIIntegrationTests/SupportCommandIntegrationTests.swift @@ -0,0 +1,78 @@ +import Foundation +import Testing + +@Suite( + "Support CLI integration", + .enabled( + if: ProcessInfo.processInfo.environment["APPLE_DOCS_EXECUTABLE"] != nil, + "Run with make test-integration INTEGRATION_FILTER=SupportCommandIntegrationTests."), + .serialized +) +struct SupportCommandIntegrationTests { + @Test( + "returns live source catalogs as structured JSON", + arguments: [ + (["support", "articles", "list"], "articlesCatalog"), + (["support", "guides", "list"], "helpCatalog"), + (["support", "guides", "contents", "--name", "app-store-connect"], "guideContents"), + (["support", "glossary", "list", "--query", "account"], "glossary"), + (["support", "glossary", "view", "--term", "Account Holder"], "glossaryEntry"), + (["support", "terms", "list"], "termsCatalog"), + (["support", "terms", "view", "--name", "apple-developer-program-license-agreement"], "termsEntry"), + ]) + func liveCatalogs(arguments: [String], kind: String) throws { + // -- Arrange -- + let arguments = arguments + ["--agent", "--json"] + + // -- Act -- + let output = try runAppleDocs(arguments) + let value = try #require(JSONSerialization.jsonObject(with: Data(output.utf8)) as? [String: Any]) + + // -- Assert -- + #expect(value["kind"] as? String == kind) + #expect(value["navigation"] != nil) + #expect(value.count > 2) + } + + @Test( + "reads live help and support document layouts", + arguments: [ + "help/app-store-connect/update-your-app/overview-of-maintaining-an-app", + "help/app-store-connect/reference/app-information/screenshot-specifications", + "support/fee-waiver", + "support/terms/apple-developer-program-license-agreement", + ]) + func liveDocument(path: String) throws { + // -- Arrange -- + let arguments = ["support", "view", "--path", path, "--json"] + + // -- Act -- + let output = try runAppleDocs(arguments) + let value = try #require(JSONSerialization.jsonObject(with: Data(output.utf8)) as? [String: Any]) + let content = try #require(value["content"] as? [[String: Any]]) + + // -- Assert -- + #expect(value["kind"] as? String == "article") + #expect(!(value["title"] as? String ?? "").isEmpty) + #expect(!content.isEmpty) + #expect(value["navigation"] == nil) + if path.hasPrefix("support/terms/") { + let notices = try #require(value["notices"] as? [[String: Any]]) + #expect(!notices.isEmpty) + } + } + + @Test("renders live agent text with follow-up navigation") + func liveAgentText() throws { + // -- Arrange -- + let arguments = ["support", "articles", "list", "--category", "membership", "--agent"] + + // -- Act -- + let output = try runAppleDocs(arguments) + + // -- Assert -- + #expect(output.hasPrefix("# Articles\n")) + #expect(output.contains("apple-docs support")) + #expect(!output.contains("\u{001B}")) + } +} diff --git a/Tests/CLITests/cmd/support/SupportCommandExecutionTests.swift b/Tests/CLITests/cmd/support/SupportCommandExecutionTests.swift new file mode 100644 index 0000000..6c6b984 --- /dev/null +++ b/Tests/CLITests/cmd/support/SupportCommandExecutionTests.swift @@ -0,0 +1,123 @@ +import Foundation +import Logging +import Testing + +@testable import CLI + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +@Suite("Support command execution") +struct SupportCommandExecutionTests { + @Test("runs all support operations through the real service and renderer", arguments: executionCases) + func executes(arguments: [String], kind: String) async throws { + // -- Arrange -- + let command = try #require(CLI.parseAsRoot(arguments + ["--json", "--agent"]) as? any SupportExecutableCommand) + let deps = try ExecutionDependencies() + + // -- Act -- + try await command.run(deps: deps) + let output = try #require(deps.output.lines.first) + let value = try #require(JSONSerialization.jsonObject(with: Data(output.utf8)) as? [String: Any]) + + // -- Assert -- + #expect(deps.output.lines.count == 1) + #expect(value["kind"] as? String == kind) + #expect(value["navigation"] != nil) + #expect(deps.telemetry.commands.count == 1) + } + + @Test("propagates a missing selection without writing successful output") + func selectionFailure() async throws { + // -- Arrange -- + let command = try #require( + CLI.parseAsRoot([ + "support", "glossary", "view", "--term", "Missing", + ]) as? SupportGlossaryViewCommand) + let deps = try ExecutionDependencies() + + // -- Act -- + let run = { try await command.run(deps: deps) } + + // -- Assert -- + await #expect(throws: SupportServiceError.self) { try await run() } + #expect(deps.output.lines.isEmpty) + } +} + +private let executionCases: [([String], String)] = [ + (["support", "articles", "list", "--category", "membership"], "articlesCatalog"), + (["support", "guides", "list"], "helpCatalog"), + (["support", "guides", "contents", "--name", "app-store-connect"], "guideContents"), + (["support", "glossary", "list", "--query", "account"], "glossary"), + (["support", "glossary", "view", "--term", "Account Holder"], "glossaryEntry"), + (["support", "terms", "list", "--category", "guidelines"], "termsCatalog"), + (["support", "terms", "view", "--name", "app-review-guidelines"], "termsEntry"), + (["support", "view", "--path", "support/fee-waiver"], "article"), +] + +private typealias ExecutionProviders = AppleSupportServiceProvider & SupportRendererProvider + & CommandOutputWriterProvider & TelemetryProvider + +private struct ExecutionDependencies: ExecutionProviders { + let telemetry = RecordingCommandTelemetry() + let output = RecordingCommandOutputWriter() + var commandOutputWriter: RecordingCommandOutputWriter { output } + let supportService: DefaultAppleSupportService> + + init() throws { + var responses: [URL: HTTPTestTransport.Response] = [:] + for (path, html) in executionHTML { + let url = try SupportDestination(path: path).url + let response = try #require( + HTTPURLResponse( + url: url, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "text/html"])) + responses[url] = .response(data: Data(html.utf8), response: response) + } + supportService = DefaultAppleSupportService( + dependencies: DefaultAppleSupportClient( + logger: Logger(label: "test") { _ in SwiftLogNoOpLogHandler() }, + dependencies: HTTPTestTransport(responses: responses))) + } + + func supportRenderer(output: OutputOptions) -> DefaultSupportRenderer { + DefaultSupportRenderer(output: output.format, audience: output.audience) + } +} + +private let executionHTML = [ + "support/articles": """ +

Articles

Resources.

+ """, + "help": """ +

Help guides and articles

Resources.

+

App Store Connect

Manage apps.

+

More topics

Membership

+

Glossary

Terms.

+ """, + "help/app-store-connect": """ +
+

App Store Connect Help

Manage apps.

+ """, + "help/glossary": """ +

Glossary

Definitions.

+

Account Holder

Manages membership.

+
+ """, + "support/terms": """ +

Terms

Agreements and guidelines.

+

Guidelines

+

App Review Guidelines

Review criteria.

+

View guidelines

+
+ """, + "support/fee-waiver": """ +
Membership +

Fee waiver

Eligible organizations.

+ """, +] diff --git a/Tests/CLITests/cmd/support/SupportCommandTests.swift b/Tests/CLITests/cmd/support/SupportCommandTests.swift new file mode 100644 index 0000000..e841db3 --- /dev/null +++ b/Tests/CLITests/cmd/support/SupportCommandTests.swift @@ -0,0 +1,64 @@ +import Foundation +import Testing + +@testable import CLI + +@Suite("Support CLI commands") +struct SupportCommandTests { + @Test("registers support commands with independent audience and format", arguments: supportCommandArguments) + func parsesCommands(arguments: [String]) throws { + // -- Arrange -- + let arguments = ["--verbose"] + arguments + ["--agent", "--json"] + + // -- Act -- + let command = try #require(CLI.parseAsRoot(arguments) as? any SupportExecutableCommand) + + // -- Assert -- + #expect(command.global.verbose) + #expect(command.output.agent) + #expect(command.output.json) + } + + @Test( + "requires explicit identifiers for content selection", + arguments: [ + ["support", "view"], ["support", "guides", "contents"], + ["support", "glossary", "view"], ["support", "terms", "view"], + ]) + func requiresIdentifiers(arguments: [String]) { + // -- Arrange -- + let arguments = arguments + + // -- Act -- + let parse = { try CLI.parseAsRoot(arguments) } + + // -- Assert -- + #expect(throws: (any Error).self) { try parse() } + } + + @Test("keeps built-in help separate from support content") + func keepsBuiltInHelp() throws { + // -- Arrange -- + let arguments = ["help", "support", "guides"] + + // -- Act -- + let command = try CLI.parseAsRoot(arguments) + let help = CLI.helpMessage() + + // -- Assert -- + #expect(!(command is any SupportExecutableCommand)) + #expect(help.contains("support")) + #expect(help.contains("--help")) + } +} + +let supportCommandArguments = [ + ["support", "articles", "list", "--category", "membership"], + ["support", "guides", "list"], + ["support", "guides", "contents", "--name", "app-store-connect"], + ["support", "glossary", "list", "--query", "account"], + ["support", "glossary", "view", "--term", "Account Holder"], + ["support", "terms", "list", "--category", "guidelines"], + ["support", "terms", "view", "--name", "app-review-guidelines"], + ["support", "view", "--path", "support/fee-waiver"], +] diff --git a/Tests/CLITests/support/SupportContentParserTests.swift b/Tests/CLITests/support/SupportContentParserTests.swift index 9d7da84..00cf387 100644 --- a/Tests/CLITests/support/SupportContentParserTests.swift +++ b/Tests/CLITests/support/SupportContentParserTests.swift @@ -48,6 +48,80 @@ struct SupportContentParserTests { #expect(article.content.count == 4) } + @Test("preserves ordered breadcrumbs including unlinked category labels") + func preservesBreadcrumbs() throws { + // -- Arrange -- + let html = """ +

+ App Store Connect/ + Reference/ + App information + /Specifications

+

Specifications

Details.

+ """ + let parser = try SupportHTMLParser( + document: SupportHTMLDocument( + destination: SupportDestination( + path: "help/app-store-connect/reference/app-information/specifications"), + html: html, responseByteCount: html.utf8.count)) + + // -- Act -- + let article = try parser.article() + + // -- Assert -- + #expect( + article.breadcrumbs.map(\.title) == [ + "App Store Connect", "Reference", "App information", "Specifications", + ]) + #expect(article.breadcrumbs[0].url?.absoluteString == "https://developer.apple.com/help/app-store-connect/") + #expect(article.breadcrumbs[1].url == nil) + } + + @Test("uses validated canonical metadata for articles served through a support alias") + func canonicalArticleURL() throws { + // -- Arrange -- + let html = """ + +

Fee waiver

Details.

+ """ + let parser = try SupportHTMLParser( + document: SupportHTMLDocument( + destination: SupportDestination(path: "support/fee-waiver"), html: html, + responseByteCount: html.utf8.count)) + + // -- Act -- + let article = try parser.article() + + // -- Assert -- + #expect(article.url.absoluteString == "https://developer.apple.com/help/account/membership/fee-waivers/") + } + + @Test("named anchors without href preserve their content and navigation target") + func retainsNamedAnchors() throws { + // -- Arrange -- + let html = """ +
+ """ + let parser = try SupportHTMLParser( + document: SupportHTMLDocument( + destination: SupportDestination(path: "support/terms/example"), html: html, + responseByteCount: html.utf8.count)) + + // -- Act -- + let article = try parser.article() + + // -- Assert -- + #expect( + article.content == [ + .paragraph([ + .text("Terms "), .anchor(name: "OLE_LINK24", content: []), + .anchor(name: "OLE_LINK25", content: [.text("survive")]), .text("."), + ]) + ]) + } + @Test("retains legal section anchors and substantive footer notices") func retainsLegalNotices() throws { // -- Arrange --