// fixtures/engines/leaving-webkit.swift — leaving.mjs in WebKit itself: a // WKWebView, which keeps pages in its back/forward cache as Safari does // (Playwright's WebKit does not). Its window is never shown, so the page // is hidden and runs no frames, as an occluded Safari tab does. Same // protocol as leaving.mjs, driven by internal/docs/leaving_browser_test.go. // // Built by the test with swiftc; macOS only. import Cocoa import WebKit struct Config: Decodable { struct Cookie: Decodable { let Name: String let Value: String } let origin: String let doc: String let remote: String let cookies: [Cookie] } @MainActor final class Harness: NSObject, NSApplicationDelegate { var window: NSWindow! var web: WKWebView! let config: Config init(config: Config) { self.config = config } func applicationDidFinishLaunching(_ notification: Notification) { Task { do { try await run() exit(0) } catch { print("LEAVING FAILED \(error)") exit(1) } } } func js(_ script: String) async throws -> Any? { try await web.evaluateJavaScript(script) } func until(_ script: String, seconds: Double) async -> Bool { let end = Date().addingTimeInterval(seconds) while Date() < end { if (try? await js(script)) as? Bool == true { return true } try? await Task.sleep(for: .milliseconds(100)) } return false } func line() async -> String? { await withCheckedContinuation { c in DispatchQueue.global().async { c.resume(returning: Swift.readLine()) } } } func run() async throws { setbuf(stdout, nil) let cfg = WKWebViewConfiguration() cfg.websiteDataStore = .nonPersistent() let host = URL(string: config.origin)!.host! for c in config.cookies { let cookie = HTTPCookie(properties: [.name: c.Name, .value: c.Value, .domain: host, .path: "/"])! await cfg.websiteDataStore.httpCookieStore.setCookie(cookie) } let source = """ window.requestAnimationFrame = () => 0; window.__shown = []; addEventListener('pageshow', (e) => window.__shown.push(e.persisted)); const ES = window.EventSource; window.EventSource = class extends ES { constructor(...args) { super(...args); sessionStorage.setItem('opened', '1'); } }; """ cfg.userContentController.addUserScript(WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true)) web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800), configuration: cfg) window = NSWindow(contentRect: web.frame, styleMask: [.titled], backing: .buffered, defer: false) window.contentView = web web.load(URLRequest(url: URL(string: config.origin + "/")!)) guard await until("location.pathname === '/' && document.readyState === 'complete'", seconds: 30) else { throw NSError(domain: "the documents list never loaded", code: 1) } // Leave the moment the editor has opened its stream. From here, // not from the page: WebKit turns a script's navigation before the // load event into a replacement, and there would be no going back. web.load(URLRequest(url: URL(string: config.origin + "/d/" + config.doc)!)) guard await until("sessionStorage.getItem('opened') === '1'", seconds: 30) else { throw NSError(domain: "the editor never opened its stream", code: 1) } web.load(URLRequest(url: URL(string: config.origin + "/")!)) guard await until("location.pathname === '/' && document.readyState === 'complete'", seconds: 30) else { throw NSError(domain: "the document was never left", code: 1) } print("LEAVING LEFT") guard await line() == "BACK" else { throw NSError(domain: "expected BACK", code: 1) } web.goBack() let remote = config.remote.replacingOccurrences(of: "'", with: "\\'") let caughtUp = await until("(document.querySelector('[docs-text]') || { textContent: '' }).textContent.includes('\(remote)')", seconds: 15) let persisted = ((try? await js("window.__shown.includes(true)")) as? Bool) ?? false print("LEAVING SHOWN {\"persisted\":\(persisted),\"caughtUp\":\(caughtUp)}") _ = await line() } } let config = try! JSONDecoder().decode(Config.self, from: ProcessInfo.processInfo.environment["DOCS_LEAVING_CONFIG"]!.data(using: .utf8)!) MainActor.assumeIsolated { let app = NSApplication.shared let delegate = Harness(config: config) app.delegate = delegate app.setActivationPolicy(.accessory) app.run() }