also looking at this
feat(ios): the Zig runtime, offered to a Swift-hosted app
#103
7 files
+868
-59
| @@ -338,6 +338,12 @@ struct CraftWebView: UIViewRepresentable { | ||
| 338 | 338 | webView.navigationDelegate = context.coordinator |
| 339 | 339 | webView.isOpaque = false |
| 340 | 340 | |
| 341 | // Before any message can be offered. Zig evaluates every reply against | |
| 342 | // this webview, and without it an action would run, succeed, and reach | |
| 343 | // `error.NoWebView` on the way back — the page hearing nothing while | |
| 344 | // the work happened. | |
| 345 | CraftZigRuntime.attach(webView) | |
| 346 | ||
| 341 | 347 | // Register with DeepLinkManager |
| 342 | 348 | DeepLinkManager.shared.setWebView(webView) |
| 343 | 349 | |
| @@ -363,6 +369,13 @@ struct CraftWebView: UIViewRepresentable { | ||
| 363 | 369 | |
| 364 | 370 | func updateUIView(_ webView: WKWebView, context: Context) {} |
| 365 | 371 | |
| 372 | /// The teardown half of `CraftZigRuntime.attach`, called by SwiftUI when | |
| 373 | /// this representable goes away. Without it Zig keeps an unretained | |
| 374 | /// pointer to a deallocated webview and answers into freed memory. | |
| 375 | static func dismantleUIView(_ uiView: WKWebView, coordinator: Coordinator) { | |
| 376 | CraftZigRuntime.detach(uiView) | |
| 377 | } | |
| 378 | ||
| 366 | 379 | func makeCoordinator() -> Coordinator { |
| 367 | 380 | let coordinator = Coordinator(config: config) |
| 368 | 381 | // The Zig dispatcher finds CraftSwiftShim by class name; the shim finds |
| @@ -516,7 +529,24 @@ struct CraftWebView: UIViewRepresentable { | ||
| 516 | 529 | guard let body = message.body as? [String: Any], |
| 517 | 530 | let action = body["action"] as? String else { return } |
| 518 | 531 | |
| 519 | dispatch(action: action, body: body, callbackId: body["callbackId"] as? String) | |
| 532 | let callbackId = body["callbackId"] as? String | |
| 533 | ||
| 534 | // The Zig runtime first, when there is one. | |
| 535 | // | |
| 536 | // `offer` returns true when Zig has taken responsibility for the | |
| 537 | // call — served it, or refused it and settled the page's promise | |
| 538 | // on the way. Either way the answer is on its way and this method | |
| 539 | // must not produce a second one. False means no Zig module | |
| 540 | // recognised the action, which is every action still listed in the | |
| 541 | // switch below and nothing else. | |
| 542 | // | |
| 543 | // In an app with no Zig runtime linked, `offer` is a `dlsym` miss | |
| 544 | // that answers false for everything, and the switch serves the | |
| 545 | // whole surface exactly as it did before. That is why this is one | |
| 546 | // line and not a build flag. | |
| 547 | if CraftZigRuntime.offer(action: action, body: body, callbackId: callbackId) { return } | |
| 548 | ||
| 549 | dispatch(action: action, body: body, callbackId: callbackId) | |
| 520 | 550 | } |
| 521 | 551 | |
| 522 | 552 | /// The action switch, reachable from two directions: the |
| @@ -2421,6 +2451,27 @@ struct CraftWebView: UIViewRepresentable { | ||
| 2421 | 2451 | } |
| 2422 | 2452 | })(window.craft); |
| 2423 | 2453 | |
| 2454 | // The reply route for actions the Zig runtime serves. | |
| 2455 | // | |
| 2456 | // Zig owns one wire format and calls these two functions by name; | |
| 2457 | // this page owns `_callbacks`, keyed by the 'cb_<n>' ids `_invoke` | |
| 2458 | // hands out. The whole adaptation is turning the numeric id Zig | |
| 2459 | // carries back into that key. Nothing else is translated, because | |
| 2460 | // nothing else differs: `craftSpeechStart` and friends already | |
| 2461 | // arrive as plain CustomEvents from both sides. | |
| 2462 | // | |
| 2463 | // A null id means the page sent no callback — the tray-style | |
| 2464 | // fire-and-forget posts — so there is nothing to settle and | |
| 2465 | // dropping it is correct rather than lossy. | |
| 2466 | window.__craftBridgeResult = function (action, result, id) { | |
| 2467 | if (id === null || id === undefined) return; | |
| 2468 | window.craft._resolveCallback('cb_' + id, result); | |
| 2469 | }; | |
| 2470 | window.__craftBridgeError = function (ctx) { | |
| 2471 | if (!ctx || ctx.id === null || ctx.id === undefined) return; | |
| 2472 | window.craft._rejectCallback('cb_' + ctx.id, ctx.message, ctx.code); | |
| 2473 | }; | |
| 2474 | ||
| 2424 | 2475 | // Dispatch ready event |
| 2425 | 2476 | window.dispatchEvent(new CustomEvent('craftReady', {detail: window.craft})); |
| 2426 | 2477 | console.log('Craft iOS bridge initialized'); |
| @@ -5193,6 +5244,123 @@ extension CraftWebView.Coordinator: WCSessionDelegate { | ||
| 5193 | 5244 | |
| 5194 | 5245 | // MARK: - Zig hand-off shim |
| 5195 | 5246 | |
| 5247 | /// The seam the page's messages reach the Zig runtime through. | |
| 5248 | /// | |
| 5249 | /// The opposite direction from `CraftSwiftShim` below, and the two together | |
| 5250 | /// are the whole hand-off: this class offers each message to Zig, Zig serves | |
| 5251 | /// what it has migrated and declines the rest, and for anything Zig *did* | |
| 5252 | /// take that needs Swift work, `CraftSwiftShim` is how it comes back. | |
| 5253 | /// | |
| 5254 | /// Discovery is `dlsym`, exactly as the shim's is, and for the same reason: | |
| 5255 | /// neither side links the other. An app built without the Zig static library | |
| 5256 | /// finds nothing here, `offer` answers false for every action, and the | |
| 5257 | /// coordinator's switch serves the entire surface as it always has. There is | |
| 5258 | /// no build flag and no second code path — the absence of a symbol is the | |
| 5259 | /// off switch. | |
| 5260 | @objc(CraftZigRuntime) | |
| 5261 | final class CraftZigRuntime: NSObject { | |
| 5262 | private typealias SetWebViewFn = @convention(c) (UnsafeMutableRawPointer?) -> Void | |
| 5263 | private typealias ClearWebViewFn = @convention(c) (UnsafeMutableRawPointer?) -> Void | |
| 5264 | private typealias HandleActionFn = @convention(c) ( | |
| 5265 | UnsafePointer<CChar>, UInt, UnsafePointer<CChar>, UInt, Int64 | |
| 5266 | ) -> Bool | |
| 5267 | ||
| 5268 | private static let image: UnsafeMutableRawPointer? = dlopen(nil, RTLD_NOW) | |
| 5269 | ||
| 5270 | private static let setWebViewFn: SetWebViewFn? = { | |
| 5271 | guard let sym = dlsym(image, "craft_ios_set_webview") else { return nil } | |
| 5272 | return unsafeBitCast(sym, to: SetWebViewFn.self) | |
| 5273 | }() | |
| 5274 | ||
| 5275 | private static let clearWebViewFn: ClearWebViewFn? = { | |
| 5276 | guard let sym = dlsym(image, "craft_ios_clear_webview") else { return nil } | |
| 5277 | return unsafeBitCast(sym, to: ClearWebViewFn.self) | |
| 5278 | }() | |
| 5279 | ||
| 5280 | private static let handleActionFn: HandleActionFn? = { | |
| 5281 | guard let sym = dlsym(image, "craft_ios_handle_action") else { return nil } | |
| 5282 | return unsafeBitCast(sym, to: HandleActionFn.self) | |
| 5283 | }() | |
| 5284 | ||
| 5285 | /// Whether this build has a Zig runtime at all. Read by nothing here; kept | |
| 5286 | /// because "is Zig linked" is the first question to ask when an action | |
| 5287 | /// behaves like the Swift one after a migration was supposed to move it. | |
| 5288 | @objc static var isLinked: Bool { handleActionFn != nil } | |
| 5289 | ||
| 5290 | /// Give Zig the webview its replies are evaluated against. | |
| 5291 | /// | |
| 5292 | /// Unretained on purpose, on both sides: this is the app's own root view | |
| 5293 | /// and it outlives the runtime. A retain here would be a cycle with | |
| 5294 | /// nothing to break it. | |
| 5295 | static func attach(_ webView: WKWebView) { | |
| 5296 | setWebViewFn?(Unmanaged.passUnretained(webView).toOpaque()) | |
| 5297 | } | |
| 5298 | ||
| 5299 | /// Forget this webview, if Zig is still holding it. | |
| 5300 | /// | |
| 5301 | /// `attach` hands over an unretained pointer, so the moment SwiftUI | |
| 5302 | /// deallocates the view Zig is holding freed memory and every later reply | |
| 5303 | /// is an `objc_msgSend` into it. Nothing called this before, and nothing | |
| 5304 | /// had to while the app had exactly one webview for its whole life — but | |
| 5305 | /// a `UIViewRepresentable` is rebuilt whenever its identity changes, and | |
| 5306 | /// the second rebuild is where that assumption stops holding. | |
| 5307 | /// | |
| 5308 | /// The webview is passed rather than implied: Zig clears only if this is | |
| 5309 | /// still the pointer it has, so a rebuild that makes the replacement | |
| 5310 | /// before dismantling the original cannot blank the live one. | |
| 5311 | static func detach(_ webView: WKWebView) { | |
| 5312 | clearWebViewFn?(Unmanaged.passUnretained(webView).toOpaque()) | |
| 5313 | } | |
| 5314 | ||
| 5315 | /// Offer one page message to the Zig dispatcher. | |
| 5316 | /// | |
| 5317 | /// Returns true when Zig has taken responsibility — the caller must not | |
| 5318 | /// answer as well. False when no Zig module recognised the action, or when | |
| 5319 | /// there is no runtime to ask. | |
| 5320 | static func offer(action: String, body: [String: Any], callbackId: String?) -> Bool { | |
| 5321 | guard let handleActionFn else { return false } | |
| 5322 | ||
| 5323 | // `_invoke` flattens the payload into the message — | |
| 5324 | // `Object.assign({}, payload, {action, callbackId})` — so the payload | |
| 5325 | // Zig's handlers parse is the message minus the two envelope keys. | |
| 5326 | // This is the exact inverse of what `CraftSwiftShim.handleAction` does | |
| 5327 | // when a call travels the other way, and the two must stay inverses: | |
| 5328 | // leaving `action` in would put a key in the payload no handler | |
| 5329 | // expects, and dropping a real field would hand a handler defaults the | |
| 5330 | // page never asked for. | |
| 5331 | var payload = body | |
| 5332 | payload.removeValue(forKey: "action") | |
| 5333 | payload.removeValue(forKey: "callbackId") | |
| 5334 | ||
| 5335 | // A payload that will not serialise is not offered. Falling through to | |
| 5336 | // the Swift switch is the safe direction: it reads `body` directly and | |
| 5337 | // never needs the round trip through JSON that just failed. | |
| 5338 | guard JSONSerialization.isValidJSONObject(payload), | |
| 5339 | let data = try? JSONSerialization.data(withJSONObject: payload), | |
| 5340 | let json = String(data: data, encoding: .utf8) | |
| 5341 | else { return false } | |
| 5342 | ||
| 5343 | return action.withCString { a in | |
| 5344 | json.withCString { p in | |
| 5345 | handleActionFn(a, UInt(strlen(a)), p, UInt(strlen(p)), requestId(from: callbackId)) | |
| 5346 | } | |
| 5347 | } | |
| 5348 | } | |
| 5349 | ||
| 5350 | /// "cb_7" -> 7, and -1 for a message with no callback waiting on it. | |
| 5351 | /// | |
| 5352 | /// -1 rather than 0, matching what `craft_ios_deliver_result` already | |
| 5353 | /// treats as "no id": zero is a perfectly good callback number, and a | |
| 5354 | /// sentinel that collides with a real id would deliver one caller's answer | |
| 5355 | /// to another. | |
| 5356 | private static func requestId(from callbackId: String?) -> Int64 { | |
| 5357 | guard let callbackId, callbackId.hasPrefix("cb_"), | |
| 5358 | let n = Int64(callbackId.dropFirst(3)) | |
| 5359 | else { return -1 } | |
| 5360 | return n | |
| 5361 | } | |
| 5362 | } | |
| 5363 | ||
| 5196 | 5364 | /// The seam the Zig dispatcher hands unmigrated actions through. |
| 5197 | 5365 | /// |
| 5198 | 5366 | /// Discovery is symmetric and both directions are runtime-only. Zig finds this |