Skip to content
Open
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
52 changes: 52 additions & 0 deletions Sources/JSONLD/Core/URLSessionDocumentLoader.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright 2026 kPherox
// SPDX-License-Identifier: Apache-2.0

#if canImport(FoundationNetworking)
import Foundation
public import class FoundationNetworking.URLSession
public import class FoundationNetworking.HTTPURLResponse
#else
public import Foundation
#endif

/// A reference document loader backed by `URLSession`.
///
/// This loader is opt-in. Assign an instance to `JSONLDProcessor.loader` to enable
/// remote document loading with Swift Concurrency.
public struct URLSessionDocumentLoader: JSONLDDocumentLoader {
/// The session used to perform network requests.
public let session: URLSession

/// Creates a URLSession-backed document loader.
public init(session: URLSession = .shared) {
self.session = session
}

/// Loads a remote JSON-LD document from the specified URL.
public func load(url: String) async -> Result<RemoteDocument, any Error> {
guard let requestURL = URL(string: url) else {
return .failure(URLError(.badURL))
}

do {
let (data, response) = try await self.session.data(from: requestURL)
let jsonValue = try JSONDecoder().decode(JSONValue.self, from: data)

let httpResponse = response as? HTTPURLResponse
let responseURL = httpResponse?.url ?? response.url ?? requestURL
let contentType = httpResponse?.value(forHTTPHeaderField: "Content-Type")
let linkHeader = httpResponse?.value(forHTTPHeaderField: "Link")

return .success(
RemoteDocument(
documentURL: responseURL.absoluteString,
document: jsonValue,
contentType: contentType,
linkHeader: linkHeader
)
)
} catch {
return .failure(error)
}
}
}
Loading