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
190 changes: 190 additions & 0 deletions Sources/WebViewBundle/Bridge.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import Foundation

#if canImport(WebKit)
import WebKit

/// The native bridge for communicate with WKWebView.
@MainActor
public final class Bridge: NSObject, WKScriptMessageHandler {
public typealias Handler = @MainActor (_ params: Any?) async throws -> Any?

/// The `window.webkit.messageHandlers` name the web side posts to.
static let messageHandlerName = "wvbIos"

private(set) var handlers: [String: Handler] = [:]

public override init() {
super.init()
}

@discardableResult
public func handler(_ name: String, _ handler: @escaping Handler) -> Bridge {
handlers[name] = handler
return self
}

@discardableResult
public func add(_ handlers: any BridgeHandlers) -> Bridge {
handlers.register(on: self)
return self
}

/// Registers this bridge on `configuration` as the `wvbIos` message handler.
func install(on configuration: WKWebViewConfiguration) {
configuration.userContentController.add(self, name: Self.messageHandlerName)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: install(on:) is not idempotent and can crash when called more than once on the same configuration. Remove existing handler before re-adding wvbIos.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At Sources/WebViewBundle/Bridge.swift, line 34:

<comment>`install(on:)` is not idempotent and can crash when called more than once on the same configuration. Remove existing handler before re-adding `wvbIos`.</comment>

<file context>
@@ -0,0 +1,190 @@
+
+    /// Registers this bridge on `configuration` as the `wvbIos` message handler.
+    func install(on configuration: WKWebViewConfiguration) {
+      configuration.userContentController.add(self, name: Self.messageHandlerName)
+    }
+
</file context>

}

public func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
// WebKit exposes the message handler to every frame, so an embedded
// (possibly third-party) iframe could invoke privileged native commands.
// Only the main frame is allowed; subframe messages are dropped.
guard message.frameInfo.isMainFrame else {
Log.bridge.error("invoke message dropped: not from the main frame")
return
}
guard let body = message.body as? [String: Any],
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
let successExpr = body["success"] as? String,
let errorExpr = body["error"] as? String
else {
// No callback to reply through: the message is dropped and the web
// `Promise` hangs with no other signal, so log it loudly.
let name = (message.body as? [String: Any])?["name"] as? String ?? "<unknown>"
Log.bridge.error(
"invoke message dropped: missing success/error callback (command: \(name, privacy: .public))"
)
return
}
let name = body["name"] as? String ?? ""
let params = body["params"] is NSNull ? nil : body["params"]
let webView = message.webView
let handler = handlers[name]

// Inherits the main actor; `await` lets an async handler suspend without
// blocking the main thread, then resumes here to evaluate the reply.
Task { [weak webView] in
let js: String
do {
guard let handler else {
throw InvokeError.handlerNotFound(name)
}
let result = try await handler(params)
js = "\(successExpr)(\(try Self.encode(result)))"
} catch {
let payload =
(try? Self.encode(Self.errorJSON(error))) ?? "{\"message\":\"unknown error\"}"
js = "\(errorExpr)(\(payload))"
}
// Usually benign (page navigated, or WebKit's "unsupported type" on an
// `undefined` return from a successful reply), so a warning, not an error.
do {
_ = try await webView?.evaluateJavaScript(js)
} catch {
Log.bridge.warning(
"invoke reply eval failed (command: \(name, privacy: .public)): \(error.localizedDescription, privacy: .public)"
)
}
}
}

/// Builds the `{ code?, message }` error payload delivered to the webview.
static func errorJSON(_ error: Swift.Error) -> [String: Any] {
let message: String
let code: String?
if let failure = error as? BridgeFailure {
message = failure.message
code = failure.code
} else {
message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
code = nil
}
var json: [String: Any] = ["message": message]
if let code { json["code"] = code }
return json
}

/// Serializes a handler result to a JSON literal for a callback argument.
static func encode(_ value: Any?) throws -> String {
guard let value, !(value is NSNull) else { return "null" }
guard isJSONEncodable(value), let json = jsonString(value) else {
throw InvokeError.unencodableResult
}
return json
}

/// Whether `value` (and, recursively, its contents) is a finite JSON value
/// that `JSONSerialization` can encode without raising.
private static func isJSONEncodable(_ value: Any) -> Bool {
switch value {
case let number as NSNumber:
// Bool/Int/Double/Float all bridge to NSNumber; reject NaN/±Infinity.
return number.doubleValue.isFinite
case is String, is NSNull:
// JSON `null` decodes to NSNull and serializes back to `null`.
return true
case let array as [Any]:
return array.allSatisfy(isJSONEncodable)
case let object as [String: Any]:
return object.values.allSatisfy(isJSONEncodable)
default:
return false
}
}

private static func jsonString(_ value: Any) -> String? {
guard
let data = try? JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed]),
let json = String(data: data, encoding: .utf8)
else {
return nil
}
return escapeForJS(json)
}

// JSON permits the raw line separators U+2028/U+2029 inside strings, but they
// are line terminators in JavaScript source and would break the
// `callback(<json>)` we evaluate. Built from scalars to keep the source ASCII.
private static let lineSeparator = String(UnicodeScalar(0x2028)!)
private static let paragraphSeparator = String(UnicodeScalar(0x2029)!)

private static func escapeForJS(_ string: String) -> String {
string
.replacingOccurrences(of: lineSeparator, with: "\\u2028")
.replacingOccurrences(of: paragraphSeparator, with: "\\u2029")
}
}

@MainActor
public protocol BridgeHandlers {
func register(on bridge: Bridge)
}

/// Errors raised by the ``Bridge`` dispatch itself
public enum InvokeError: Swift.Error, LocalizedError, BridgeFailure, Equatable {
/// No handler was registered for the requested command name.
case handlerNotFound(String)
/// A handler returned a value that is not a JSON value (a custom type, or a
/// non-finite number), so it cannot be delivered to the web side.
case unencodableResult

public var errorDescription: String? {
switch self {
case .handlerNotFound(let name):
return "no invoke handler registered for \"\(name)\""
case .unencodableResult:
return "invoke handler returned a value that is not JSON-encodable"
}
}

public var code: String? {
switch self {
case .handlerNotFound: return "handler_not_found"
case .unencodableResult: return "unencodable_result"
}
}

public var message: String { errorDescription ?? "" }
}
#endif
39 changes: 39 additions & 0 deletions Sources/WebViewBundle/BridgeCodec.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Foundation

/// Bridges raw `invoke()` payloads to typed Swift values via `Codable`.
enum BridgeCodec {
/// Decodes the `invoke()` params object into a typed arguments value.
static func decode<T: Decodable>(_ params: Any?, as type: T.Type) throws -> T {
let object = params ?? [String: Any]()
guard JSONSerialization.isValidJSONObject(object) else {
throw BridgeError(code: "invalid_params", message: "invoke params must be an object")
}
let data = try JSONSerialization.data(withJSONObject: object)
do {
return try JSONDecoder().decode(T.self, from: data)
} catch let error as DecodingError {
throw BridgeError(code: "invalid_params", message: describe(error))
}
}

/// Encodes an `Encodable` response payload to a JSON-native value
/// (`[String: Any]` / `[Any]` / scalar) for the bridge reply.
static func jsonObject<T: Encodable>(_ value: T) throws -> Any {
let data = try JSONEncoder().encode(value)
return try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
}

private static func describe(_ error: DecodingError) -> String {
switch error {
case .keyNotFound(let key, _):
return "missing required param \"\(key.stringValue)\""
case .typeMismatch(_, let context), .valueNotFound(_, let context):
let path = context.codingPath.map(\.stringValue).joined(separator: ".")
return path.isEmpty ? context.debugDescription : "invalid param \"\(path)\""
case .dataCorrupted(let context):
return context.debugDescription
@unknown default:
return "invalid invoke params"
}
}
}
23 changes: 23 additions & 0 deletions Sources/WebViewBundle/BridgeError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import Foundation

/// A Swift error that maps to the web-facing `{ code?, message }` bridge error
/// shape. Conform a custom error to deliver a `code` alongside its `message`
public protocol BridgeFailure: Swift.Error {
/// Optional machine-readable code, omitted from the payload when `nil`.
var code: String? { get }
/// Human-readable message, always present in the payload.
var message: String { get }
}

/// The canonical `{ code?, message }` error thrown to reject an `invoke()`
/// command. Other thrown errors are encoded with their localized description as
/// `message` and no `code`.
public struct BridgeError: BridgeFailure, Equatable {
public var code: String?
public var message: String

public init(code: String? = nil, message: String) {
self.code = code
self.message = message
}
}
60 changes: 30 additions & 30 deletions Sources/WebViewBundle/Conversions.swift
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
import Foundation

extension HttpMethod {
/// Maps a `URLRequest.httpMethod` string to the FFI ``HttpMethod``.
/// Defaults to `.get` for unknown or missing methods.
static func from(_ method: String?) -> HttpMethod {
switch method?.uppercased() {
case "GET": return .get
case "HEAD": return .head
case "OPTIONS": return .options
case "POST": return .post
case "PUT": return .put
case "PATCH": return .patch
case "DELETE": return .delete
case "TRACE": return .trace
case "CONNECT": return .connect
default: return .get
}
/// Maps a `URLRequest.httpMethod` string to the FFI ``HttpMethod``.
/// Defaults to `.get` for unknown or missing methods.
static func from(_ method: String?) -> HttpMethod {
switch method?.uppercased() {
case "GET": return .get
case "HEAD": return .head
case "OPTIONS": return .options
case "POST": return .post
case "PUT": return .put
case "PATCH": return .patch
case "DELETE": return .delete
case "TRACE": return .trace
case "CONNECT": return .connect
default: return .get
}
}
}

extension HttpResponse {
/// Builds an `HTTPURLResponse` for `url` from this response's status and
/// headers.
func makeURLResponse(url: URL) -> HTTPURLResponse {
HTTPURLResponse(
url: url,
statusCode: Int(status),
httpVersion: "HTTP/1.1",
headerFields: headers
) ?? HTTPURLResponse(
url: url,
statusCode: Int(status),
httpVersion: "HTTP/1.1",
headerFields: nil
)!
}
/// Builds an `HTTPURLResponse` for `url` from this response's status and
/// headers.
func makeURLResponse(url: URL) -> HTTPURLResponse {
HTTPURLResponse(
url: url,
statusCode: Int(status),
httpVersion: "HTTP/1.1",
headerFields: headers
) ?? HTTPURLResponse(
url: url,
statusCode: Int(status),
httpVersion: "HTTP/1.1",
headerFields: nil
)!
}
}
48 changes: 48 additions & 0 deletions Sources/WebViewBundle/Log.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import Foundation
import os

/// Severity of an SDK log event; mirrors Rust `tracing` levels so core events
/// can forward into the same pipeline (see ``CoreLog``).
enum LogLevel: Int, Sendable, Comparable {
case trace, debug, info, warning, error

static func < (lhs: LogLevel, rhs: LogLevel) -> Bool { lhs.rawValue < rhs.rawValue }

/// `os` has no `warning`, so it folds into `.default`.
var osLogType: OSLogType {
switch self {
case .trace, .debug: return .debug
case .info: return .info
case .warning: return .default
case .error: return .error
}
}
}

/// Unified `os.Logger` channels. Filter on `subsystem == "webview-bundle"` to
/// see Swift-side and (once enabled) Rust-core logs together.
enum Log {
static let subsystem = "webview-bundle"

static let bridge = Logger(subsystem: subsystem, category: "bridge")
static let core = Logger(subsystem: subsystem, category: "core")
}

/// Seam for forwarding the Rust core's `tracing` into the unified `core`
/// channel. The level/route mapping is implemented; wiring it to an FFI
/// log-subscriber callback is pending (the FFI exposes none yet).
enum CoreLog {
/// `message` is already formatted by the core; `target` is its module path.
/// Logged `.public` since tracing is an explicit opt-in, so the core must not
/// emit user PII into tracing messages.
static func forward(level: LogLevel, target: String, message: String) {
Log.core.log(
level: level.osLogType,
"[\(target, privacy: .public)] \(message, privacy: .public)")
}
}

extension WebViewBundle {
/// The unified-logging subsystem the SDK logs under.
public static let logSubsystem = Log.subsystem
}
14 changes: 5 additions & 9 deletions Sources/WebViewBundle/RequestHandler.swift
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import Foundation

/// Common shape of the UniFFI request handlers used by the WebView integration.
///
/// Both ``BundleUrlHandler`` and ``LocalUrlHandler`` (generated into this module
/// by UniFFI) already expose this exact `handle` signature, so they conform
/// without extra code.
protocol WebViewBundleRequestHandler: AnyObject, Sendable {
func handle(
method: HttpMethod,
uri: String,
headers: [String: String]?
) async throws -> HttpResponse
func handle(
method: HttpMethod,
uri: String,
headers: [String: String]?
) async throws -> HttpResponse
}

extension BundleUrlHandler: WebViewBundleRequestHandler {}
Expand Down
Loading