react-native-minimal-webview 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/android/build.gradle +1 -1
  2. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  3. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +67 -120
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +23 -32
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +8 -18
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +30 -49
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +48 -36
  9. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  10. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +30 -40
  11. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  12. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  16. package/build/WebView.d.ts +8 -1
  17. package/build/WebView.d.ts.map +1 -1
  18. package/build/WebView.js +30 -80
  19. package/build/WebView.js.map +1 -1
  20. package/build/bridge/createBridge.d.ts +1 -5
  21. package/build/bridge/createBridge.d.ts.map +1 -1
  22. package/build/bridge/createBridge.js +3 -15
  23. package/build/bridge/createBridge.js.map +1 -1
  24. package/build/bridge/endpoint.d.ts +1 -2
  25. package/build/bridge/endpoint.d.ts.map +1 -1
  26. package/build/bridge/endpoint.js +5 -6
  27. package/build/bridge/endpoint.js.map +1 -1
  28. package/build/bridge/matchesOrigin.d.ts +11 -0
  29. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  30. package/build/bridge/matchesOrigin.js +26 -0
  31. package/build/bridge/matchesOrigin.js.map +1 -0
  32. package/build/bridge/origins.d.ts +2 -13
  33. package/build/bridge/origins.d.ts.map +1 -1
  34. package/build/bridge/origins.js +1 -30
  35. package/build/bridge/origins.js.map +1 -1
  36. package/build/bridge/pageClient.generated.d.ts +1 -1
  37. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  38. package/build/bridge/pageClient.generated.js +2 -2
  39. package/build/bridge/pageClient.generated.js.map +1 -1
  40. package/build/bridge/protocol.d.ts +3 -5
  41. package/build/bridge/protocol.d.ts.map +1 -1
  42. package/build/bridge/protocol.js +12 -14
  43. package/build/bridge/protocol.js.map +1 -1
  44. package/build/index.d.ts +1 -1
  45. package/build/index.js +1 -1
  46. package/build/navigationRules.d.ts +0 -5
  47. package/build/navigationRules.d.ts.map +1 -1
  48. package/build/navigationRules.js +3 -12
  49. package/build/navigationRules.js.map +1 -1
  50. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  51. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  52. package/build/reactNativeWebViewDefaults.js +0 -4
  53. package/build/reactNativeWebViewDefaults.js.map +1 -1
  54. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  55. package/build/reactNativeWebViewMessages.js +0 -1
  56. package/build/reactNativeWebViewMessages.js.map +1 -1
  57. package/build/refStore.d.ts +0 -2
  58. package/build/refStore.d.ts.map +1 -1
  59. package/build/refStore.js +0 -6
  60. package/build/refStore.js.map +1 -1
  61. package/build/types.d.ts +33 -16
  62. package/build/types.d.ts.map +1 -1
  63. package/ios/Asks.swift +6 -9
  64. package/ios/DelegateProxy.swift +6 -20
  65. package/ios/DownloadName.swift +0 -2
  66. package/ios/Downloads.swift +0 -2
  67. package/ios/Hooks.swift +6 -7
  68. package/ios/Loads.swift +37 -19
  69. package/ios/MinimalWebView+Dialogs.swift +2 -6
  70. package/ios/MinimalWebView+Navigation.swift +25 -57
  71. package/ios/MinimalWebView+Scripts.swift +4 -16
  72. package/ios/MinimalWebView.podspec +1 -2
  73. package/ios/MinimalWebView.swift +58 -144
  74. package/ios/MinimalWebViewModule.swift +1 -18
  75. package/ios/NavigationRules.swift +2 -9
  76. package/ios/OriginRules.swift +4 -13
  77. package/ios/PlatformSettings.swift +19 -38
  78. package/ios/ReadAccess.swift +0 -2
  79. package/ios/Records.swift +18 -0
  80. package/ios/Recovery.swift +2 -8
  81. package/ios/SharedCookies.swift +10 -25
  82. package/package.json +4 -4
  83. package/src/WebView.tsx +45 -95
  84. package/src/bridge/createBridge.ts +5 -20
  85. package/src/bridge/endpoint.ts +6 -9
  86. package/src/bridge/matchesOrigin.ts +27 -0
  87. package/src/bridge/origins.ts +2 -30
  88. package/src/bridge/pageClient.generated.ts +2 -2
  89. package/src/bridge/pageClient.ts +1 -7
  90. package/src/bridge/protocol.ts +16 -18
  91. package/src/index.ts +1 -1
  92. package/src/navigationRules.ts +6 -12
  93. package/src/reactNativeWebViewDefaults.ts +0 -4
  94. package/src/reactNativeWebViewMessages.ts +0 -1
  95. package/src/refStore.ts +0 -7
  96. package/src/types.ts +33 -16
@@ -1,8 +1,8 @@
1
1
  import ExpoModulesCore
2
2
  import WebKit
3
3
 
4
- // swiftlint:disable file_length - because the view is the aggregate root: it holds what has one owner (the Expo surface, the platform WebView's life, crash recovery, the Document scope, the navigation state, the hook plumbing), and a feature with state of its own gets its own class
5
- // swiftlint:disable:next type_body_length - because the view is the aggregate root, see the file_length reason above
4
+ // swiftlint:disable file_length - because the view is the aggregate root
5
+ // swiftlint:disable:next type_body_length - because the view is the aggregate root
6
6
  class MinimalWebView: ExpoView, WKNavigationDelegate {
7
7
  let onNavigationState = EventDispatcher()
8
8
  let onBridge = EventDispatcher()
@@ -11,16 +11,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
11
11
  let onProcessGone = EventDispatcher()
12
12
  let onNavigation = EventDispatcher()
13
13
 
14
- // Props, applied together in applyProps(). The bridge, the hooks with a configure step and the `configuration`
15
- // settings are fixed at mount (see `webView`).
16
14
  var source: WebViewSource?
17
15
  var bridgeScript: String?
18
16
  var bridgeOrigins: [String] = []
19
- /// The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions).
20
17
  var hookOptions: [String: Any] = [:] {
21
18
  didSet { if webView != nil { optionsChanged(from: oldValue) } }
22
19
  }
23
- /// The `ios` prop: WebKit properties by name, applied by PlatformSettings.
24
20
  var settings: [String: Any] = [:]
25
21
  let platformSettings = PlatformSettings()
26
22
  var pullToRefresh = false
@@ -35,68 +31,43 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
35
31
  var injectedScripts: [InjectedScript] = [] {
36
32
  didSet { if let webView { installScripts(webView.configuration.userContentController) } }
37
33
  }
38
- /// The user scripts installScripts added: the others in the content controller are a hook's.
39
34
  var ownScripts: [WKUserScript] = []
40
- /// The page requests JS has a prop for, by prop name (`onDownload`, `onNavigationRequest`, ...), and `onNavigation`, read when a
41
- /// request comes or a decision is reported.
42
35
  var requestHandlers: Set<String> = []
43
36
  private var loadedSource: NSDictionary?
44
37
 
45
- // Created once, from the first props: WebKit reads some WKWebViewConfiguration settings only at creation.
46
38
  private(set) var webView: WKWebView?
47
39
  private var observations: [NSKeyValueObservation] = []
48
40
  private lazy var downloads = Downloads(view: self)
49
41
  private lazy var proxy = DelegateProxy(core: self)
50
- /// When the user last tapped the WKWebView: a link activation counts as user-initiated only right after a tap.
51
42
  let taps = Taps(target: nil, action: nil)
52
43
 
53
- // Navigation state, derived from WebKit in refreshUrls(). Native owns the committed URL; JS is told.
54
44
  private(set) var url = ""
55
- /// `url` as the hooks see it (`WebViewContext.url`): it follows `url` while no load is in flight and WebKit's own URL
56
- /// agrees, and takes the new page at each commit, after `onDocumentEnd`. WebKit moves the back-forward list to the
57
- /// next page before didCommit, and `url` can follow it early.
45
+ /// `WebViewContext.url`: WebKit moves the back-forward list to the next page before didCommit, and `url` can follow it early.
58
46
  private(set) var hookUrl = ""
59
47
  private var pendingUrl: String?
60
- /// An html source never reaches the back-forward list (WebKit hides substitute-data loads from session history):
61
- /// while the item that was current at its commit stays current, the html page is what is on screen.
48
+ /// WebKit hides substitute-data loads (an html source) from the back-forward list.
62
49
  private var htmlNavigation: WKNavigation?
63
50
  private var htmlCommit: (url: String, item: WKBackForwardListItem?)?
64
- /// The loads this view starts itself (source, `load`, reload after an error, an allowed new window), each until its
65
- /// main-frame policy check, which skips the rules, with `mainFrameChecks` at its start. A list: a load can start
66
- /// before the previous one's check, and the page being left can commit after it. A commit drops the loads a later
67
- /// check passed (cut off before their own), so a page can't later skip the rules by navigating to one.
68
- var ownLoads: [(url: URL, checks: Int)] = []
69
- var mainFrameChecks = 0
70
- private(set) lazy var asks = Asks { [weak self] in self?.onHookEvent($0) }
71
- /// The attached hooks' contexts in attach order, for the life of the WKWebView: a hook may keep its own.
51
+ var ownLoads = OwnLoads()
52
+ // No weak self: forming a weak reference to an object in deinit aborts, and deinit's tearDown can be the first use.
53
+ private(set) lazy var asks = Asks { [onHookEvent] in onHookEvent($0) }
72
54
  var hookContexts: [HookContext] = []
73
- /// URLs an `ask` allowed in this Document, keyed by mainFrame: a subframe's answer doesn't decide the main frame's.
74
55
  var askedAndAllowed: [Bool: Set<String>] = [:]
75
- /// A `source` or `load` load is being prepared (shared cookies): loads wait until it is done.
76
56
  private var preparing = false
77
- /// The ref's `load` while it is prepared: it loads instead of the `source` being prepared, if any.
78
57
  private var queuedUrl: URL?
79
- /// The last `load` since the last `source`: a retry of it reads, as it did, only within a file's directory.
80
- private var refLoad: URL?
81
- /// After a failed main-frame load `url` is the failed URL (as on Android, which commits an error page);
82
- /// WKWebView itself keeps the previous page, so `url` and reload() use this.
83
- private(set) var failedUrl: String?
84
- /// How the last load ended, "finished", "failed" or "cancelled"; JS sees it only while nothing loads.
85
- private var outcome: String?
58
+ private var directoryOnlyNavigation: WKNavigation?
59
+ /// WKWebView keeps the previous page after a failed main-frame load.
60
+ private var failedLoad: (url: String, inSourceRoot: Bool)?
61
+ private var outcome: Loads.Outcome?
86
62
  private var lastEmitted: NSDictionary?
87
63
  private var updateScheduled = false
88
64
  private var crashTimes: [TimeInterval] = []
89
- /// A web-process death whose reload waits until the view can be seen; a `load`, reload or new `source` replaces it.
90
65
  private var recoveryPending = false
91
- /// `evaluate` calls waiting for their result, by id, until a new document or a dead web process rejects them.
92
66
  var evaluations: [Int: Promise] = [:]
93
67
  var nextEvaluation = 0
94
68
 
95
- // The origin of the document whose page client last posted, as `location.origin` writes it (`*` when every origin is
96
- // allowed). JS's messages are delivered only while the page still has it.
97
69
  var bridgeOrigin: String?
98
- // The JS dialog on screen, and how to complete it if it has to go away.
99
- // While one is up the page is blocked, and an accessibility query into it (XCTest's) hangs: hide it.
70
+ // While a JS dialog is up the page is blocked, and an accessibility query into it (XCTest's) hangs.
100
71
  var dialog: (controller: UIAlertController, cancel: () -> Void)? {
101
72
  didSet { webView?.accessibilityElementsHidden = dialog != nil }
102
73
  }
@@ -104,8 +75,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
104
75
  required init(appContext: AppContext? = nil) {
105
76
  super.init(appContext: appContext)
106
77
  clipsToBounds = true
107
- // Made here, not lazily in the deinit fallback's endDocument(.closing), where its closure can't form a weak self.
108
- _ = asks
109
78
  NotificationCenter.default.addObserver(
110
79
  self, selector: #selector(recoverIfVisible), name: UIApplication.didBecomeActiveNotification, object: nil)
111
80
  }
@@ -115,8 +84,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
115
84
  recoverIfVisible()
116
85
  }
117
86
 
118
- /// Crash recovery reloads only in a window of an app not in the background, as on Android: there the reload
119
- /// could die the same way, unseen.
120
87
  @objc private func recoverIfVisible() {
121
88
  guard recoveryPending, window != nil, UIApplication.shared.applicationState != .background else { return }
122
89
  recoveryPending = false
@@ -131,34 +98,30 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
131
98
  if !opening { asks.documentEnded(reason) }
132
99
  failEvaluations()
133
100
  bridgeOrigin = nil
134
- // JS queues bridge messages until the next page is ready; at unmount it rejects what is in flight itself.
135
101
  if reason == .committed, bridgeScript != nil { onBridge(["navigated": true]) }
136
102
  if reason == .crashed, bridgeScript != nil { onBridge(["crashed": true]) }
137
103
  askedAndAllowed.removeAll()
138
104
  dismissDialog()
139
- // The spinner belongs to a load, and a crash ends the load without a delegate callback.
105
+ // A crash ends the load without a delegate callback.
140
106
  if reason == .crashed { refreshControl.endRefreshing() }
141
107
  if !opening { hookContexts.forEach { $0.documentEnded(reason) } }
142
108
  }
143
109
 
144
- /// Called once per prop batch. `source` loads last so everything else is ready first.
145
110
  func applyProps() {
146
111
  if webView == nil { createWebView() }
147
112
  guard let webView, !preparing else { return }
148
113
  report(platformSettings.apply(settings, webView: webView))
149
114
  let refresh = pullToRefresh ? refreshControl : nil
150
115
  if webView.scrollView.refreshControl !== refresh { webView.scrollView.refreshControl = refresh }
151
- cookies.set(sharedCookies)
116
+ cookies.set(sharedCookies, for: webView.configuration.websiteDataStore.httpCookieStore)
152
117
  // Records aren't Equatable: compare their dictionaries.
153
118
  guard let next = source, loadedSource != next.toDictionary() as NSDictionary else { return }
154
119
  loadedSource = next.toDictionary() as NSDictionary
155
- // New content from the app: the crash-loop guard starts over (recovery reloads don't come through here).
156
120
  crashTimes = []
157
121
  recoveryPending = false
158
122
  prepare(next)
159
123
  }
160
124
 
161
- /// The ref's `load`. It is prepared as a `source` load is, and a later call replaces one still waiting.
162
125
  func load(url: String) {
163
126
  guard let target = URL(string: url) else { return warn("load: \(url) is not a URL") }
164
127
  guard webView != nil else { return }
@@ -173,17 +136,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
173
136
  cookies.prepare { [weak self, weak webView] in
174
137
  guard let self, let webView, webView === self.webView else { return }
175
138
  preparing = false
176
- // A load asked for while the source was prepared replaces it: started first, the source's request (a POST
177
- // included) would be sent only to be cut off.
178
139
  if let queuedUrl {
179
140
  self.queuedUrl = nil
180
- refLoad = queuedUrl
181
141
  loadProgrammatic(URLRequest(url: queuedUrl), inSourceRoot: false)
182
142
  } else if let source {
183
- refLoad = nil
184
143
  load(source)
185
144
  }
186
- // Props that changed while preparing (a newer source) apply now.
187
145
  applyProps()
188
146
  }
189
147
  }
@@ -203,44 +161,35 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
203
161
  } else {
204
162
  let baseURL = source.baseUrl.flatMap(URL.init)
205
163
  // WebKit puts the html load through decidePolicyFor at its base URL, about:blank without one.
206
- if let own = baseURL ?? URL(string: "about:blank") { ownLoads.append((own, mainFrameChecks)) }
164
+ if let own = baseURL ?? URL(string: "about:blank") { ownLoads.started(own) }
207
165
  htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: baseURL)
208
166
  }
209
167
  }
210
168
 
211
- /// The page on screen (`url`) is the `source`: its URL, or an html source whose commit no other commit or failed load
212
- /// has followed.
213
169
  private var onSource: Bool {
214
170
  guard let source else { return false }
215
- guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil && failedUrl == nil }
171
+ guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil && failedLoad == nil }
216
172
  return Recovery.showsSource(uri.absoluteString, url)
217
173
  }
218
174
 
219
- /// The page on screen is the POST `source`: it can't be fetched again by URL, so reload loads the source instead.
220
175
  private var onPostSource: Bool { source?.body != nil && onSource }
221
176
 
222
- /// Settings keys that could not be applied, as warnings: JS logs them with console.warn.
223
- private func report(_ rejected: [[String: String]]) {
224
- for entry in rejected {
225
- warn("ios.\(entry["key"] ?? ""): \(entry["reason"] ?? "")")
226
- }
177
+ private func report(_ rejected: [PlatformSettings.Rejected]) {
178
+ rejected.forEach { warn("ios.\($0.key): \($0.reason)") }
227
179
  }
228
180
 
229
- /// Loads a request the app started (see `ownLoads`). A file URL goes through loadFileURL, so the page's own assets
230
- /// load (load(_:) can't read local files), with the source's read root or, outside it, the file's directory.
231
181
  func loadProgrammatic(_ request: URLRequest, inSourceRoot: Bool = true) {
232
- if let url = request.url { ownLoads.append((url, mainFrameChecks)) }
182
+ if let url = request.url { ownLoads.started(url) }
233
183
  if let url = request.url, url.isFileURL {
234
184
  let access = ReadAccess.root(for: url, inSourceRoot ? source?.readAccessRoot : nil)
235
185
  if let warning = access.warning { warn(warning) }
236
- webView?.loadFileURL(url, allowingReadAccessTo: access.root)
186
+ let navigation = webView?.loadFileURL(url, allowingReadAccessTo: access.root)
187
+ if !inSourceRoot { directoryOnlyNavigation = navigation }
237
188
  } else {
238
189
  webView?.load(request)
239
190
  }
240
191
  }
241
192
 
242
- /// The ref's reload: an explicit retry starts the crash-loop guard over, like a new source. Pull-to-refresh uses
243
- /// reload().
244
193
  func retry() {
245
194
  crashTimes = []
246
195
  reload()
@@ -248,37 +197,27 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
248
197
 
249
198
  func reload() {
250
199
  recoveryPending = false
251
- // WebKit's reload redoes no failed load, POST or html source (it fetches the base URL), and loads nothing while `url`
252
- // is nil (no commit, a dead process).
200
+ // WebKit's reload redoes no failed load, POST or html source, and loads nothing while `url` is nil.
253
201
  let onHtmlSource = onSource && source?.uri == nil
254
- if let webView, webView.url != nil, failedUrl == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
202
+ if let webView, webView.url != nil, failedLoad == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
255
203
  }
256
204
 
257
- /// Loads the page on screen again, as crash recovery does. In order:
258
- /// - the `source`, when it is the page or nothing has committed (so its headers, POST body or html are used);
259
- /// - else the failed URL;
260
- /// - else the back-forward list's item (a dead web process relaunches with it, so history stays).
261
- /// A `source` being prepared loads once it is ready instead.
262
205
  private func loadAgain() {
263
206
  guard let webView, !preparing else { return }
264
- if let source, onSource || failedUrl == nil && webView.backForwardList.currentItem == nil {
207
+ if let source, onSource || failedLoad == nil && webView.backForwardList.currentItem == nil {
265
208
  load(source)
266
- } else if let failedUrl, let target = URL(string: failedUrl) {
267
- loadProgrammatic(URLRequest(url: target), inSourceRoot: !(refLoad.map { Loads.sameURL($0, target) } ?? false))
209
+ } else if let failedLoad, let target = URL(string: failedLoad.url) {
210
+ loadProgrammatic(URLRequest(url: target), inSourceRoot: failedLoad.inSourceRoot)
268
211
  } else {
269
212
  webView.reload()
270
213
  }
271
214
  }
272
215
 
273
- /// `source` loads from applyProps once the load is prepared.
274
216
  private func createWebView() {
275
217
  let configuration = WKWebViewConfiguration()
276
- // The creation-time settings (`ios.configuration`) and the configure hooks go first and the bridge after them,
277
- // so nothing they set displaces the content controller the bridge is installed in.
278
218
  report(platformSettings.apply(settings, webView: nil, configuration: configuration))
279
219
  hookContexts = MinimalWebViewHooks.hooks.filter { hookOptions[$0.key] != nil }.map { HookContext($0, self) }
280
220
  for context in hookContexts { context.hook.configure?(configuration, context) }
281
- // A typo, or a hook's module not linked or not rebuilt.
282
221
  for key in hookOptions.keys where !hookContexts.contains(where: { $0.key == key }) {
283
222
  warn("extension \(key): no hook is registered under this key")
284
223
  }
@@ -306,18 +245,14 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
306
245
  webView.observe(\.estimatedProgress) { _, _ in update() }
307
246
  ] + [\WKWebView.canGoBack, \.canGoForward].map { webView.observe($0) { _, _ in update() } }
308
247
  self.webView = webView
309
- cookies.didCreate(webView)
310
- // The live settings before the hooks, as on Android: what a hook sets wins over the package's defaults.
311
248
  report(platformSettings.apply(settings, webView: webView))
312
249
  hookContexts.forEach { $0.hook.attach(webView, $0) }
313
250
  }
314
251
 
315
- /// React Native calls `invalidate` on this view (the Fabric component view; Expo's are never recycled) at every
316
- /// unmount. Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: declared here, it wins at
317
- /// runtime, and it calls the inherited one as `super` would.
252
+ /// React Native calls `invalidate` at every unmount (Expo's views are never recycled), and Expo's (React Native 0.82+) resets its size-update guard.
253
+ /// Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: this one wins at runtime.
318
254
  @objc func invalidate() {
319
255
  tearDown()
320
- // Expo's (React Native 0.82+) resets its size-update guard; React Native's UIView default does nothing.
321
256
  let selector = #selector(invalidate)
322
257
  typealias Invalidate = @convention(c) (AnyObject, Selector) -> Void
323
258
  guard class_respondsToSelector(ExpoView.self, selector),
@@ -325,12 +260,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
325
260
  unsafeBitCast(inherited, to: Invalidate.self)(self, selector)
326
261
  }
327
262
 
328
- /// Once: from invalidate, or from deinit if that never ran (there weak self is nil, so in-flight evaluates can't be
329
- /// rejected).
330
263
  private func tearDown() {
331
264
  guard let webView else { return }
332
265
  endDocument(.closing)
333
- cookies.detach()
266
+ cookies.set(false, for: webView.configuration.websiteDataStore.httpCookieStore)
334
267
  let closed = hookContexts
335
268
  closed.forEach { $0.detach() }
336
269
  hookContexts = []
@@ -352,26 +285,21 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
352
285
  MainActor.assumeIsolated { tearDown() }
353
286
  }
354
287
 
355
- /// The page on screen: the back-forward list's current item, which a commit creates or moves to a moment before
356
- /// didCommit (a history step may move it earlier), and pushState/replaceState/hash update.
357
288
  private func refreshUrls() {
358
289
  guard let webView else { return }
359
290
  let item = webView.backForwardList.currentItem
360
- // Empty before the first commit: the URL being loaded is pendingUrl.
361
291
  let committed = htmlCommit.flatMap { $0.item === item ? $0.url : nil } ?? item?.url.absoluteString ?? ""
362
- url = failedUrl ?? committed
292
+ url = failedLoad?.url ?? committed
363
293
  // WebKit's `url` is the active URL: a pending or provisional load shows here first.
364
294
  let active = webView.url?.absoluteString
365
295
  pendingUrl = webView.isLoading && active != committed ? active : nil
366
- if !webView.isLoading, failedUrl != nil || active == committed { hookUrl = url }
296
+ if !webView.isLoading, failedLoad != nil || active == committed { hookUrl = url }
367
297
  }
368
298
 
369
- /// WebKit's KVO fires before the delegate callbacks: the state is read and emitted one main-queue turn later, once
370
- /// per turn, so changes within one pass are combined into one event. The start of a load goes out at once as well: a
371
- /// load that starts and fails within one pass must still reach JS as loading true -> false. The end of a load waits
372
- /// for the pass, because WebKit clears isLoading before it reports the failure (the error and outcome go first).
299
+ /// WebKit's KVO fires before the delegate callbacks, and clears isLoading before it reports a failure: the state is
300
+ /// read a main-queue turn later.
373
301
  private func scheduleUpdate() {
374
- if let webView, webView.isLoading, lastEmitted?["loading"] as? Bool != true { emitState() }
302
+ if loadStartUnsent { emitState() }
375
303
  guard !updateScheduled else { return }
376
304
  updateScheduled = true
377
305
  DispatchQueue.main.async { [weak self] in
@@ -382,6 +310,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
382
310
  }
383
311
  }
384
312
 
313
+ private var loadStartUnsent: Bool { webView?.isLoading == true && lastEmitted?["loading"] as? Bool != true }
314
+
385
315
  private func emitState() {
386
316
  guard let webView else { return }
387
317
  let state: NSDictionary = [
@@ -392,41 +322,17 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
392
322
  "progress": webView.estimatedProgress,
393
323
  "canGoBack": webView.canGoBack,
394
324
  "canGoForward": webView.canGoForward,
395
- "outcome": webView.isLoading ? NSNull() : outcome as Any? ?? NSNull()
325
+ "outcome": webView.isLoading ? NSNull() : outcome?.rawValue as Any? ?? NSNull()
396
326
  ]
397
327
  guard state != lastEmitted else { return }
398
328
  lastEmitted = state
399
329
  onNavigationState(state as? [String: Any] ?? [:])
400
330
  }
401
331
 
402
- /// An observation callback the core implements: every hook delegate that implements it gets it after the core.
403
332
  private func forward(_ callback: (WKNavigationDelegate) -> Void) {
404
333
  proxy.navigationDelegates.forEach(callback)
405
334
  }
406
335
 
407
- /// A main-frame load WebKit ended with `error`: reports it to onError when it failed (`Loads.ended`), and returns its
408
- /// outcome.
409
- private func ended(with error: Error) -> String {
410
- let nsError = error as NSError
411
- let end = Loads.ended(by: nsError)
412
- guard let kind = end.kind else { return end.outcome }
413
- let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
414
- ?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
415
- failedUrl = failing
416
- onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
417
- return end.outcome
418
- }
419
-
420
- // MARK: WKNavigationDelegate
421
-
422
- func webView(
423
- _ webView: WKWebView,
424
- decidePolicyFor navigationAction: WKNavigationAction,
425
- decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
426
- ) {
427
- decideNavigation(navigationAction, decide: decisionHandler)
428
- }
429
-
430
336
  func webView(
431
337
  _ webView: WKWebView,
432
338
  decidePolicyFor navigationResponse: WKNavigationResponse,
@@ -460,8 +366,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
460
366
 
461
367
  func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
462
368
  endDocument(.committed)
463
- ownLoads.removeAll { $0.checks < mainFrameChecks }
464
- failedUrl = nil
369
+ ownLoads.committed()
370
+ failedLoad = nil
465
371
  htmlCommit = navigation === htmlNavigation
466
372
  ? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
467
373
  refreshUrls()
@@ -471,30 +377,42 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
471
377
  }
472
378
 
473
379
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
474
- loadEnded { $0.webView?(webView, didFinish: navigation) }
380
+ loadEnded(.finished) { $0.webView?(webView, didFinish: navigation) }
475
381
  }
476
382
 
477
383
  func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
478
- loadEnded(error) { $0.webView?(webView, didFail: navigation, withError: error) }
384
+ loadFailed(navigation, error) { $0.webView?(webView, didFail: navigation, withError: error) }
479
385
  }
480
386
 
481
387
  func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
482
- loadEnded(error) { $0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error) }
388
+ loadFailed(navigation, error) { $0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error) }
389
+ }
390
+
391
+ private func loadFailed(_ navigation: WKNavigation?, _ error: Error, _ callback: (WKNavigationDelegate) -> Void) {
392
+ let nsError = error as NSError
393
+ let end = Loads.ended(by: nsError)
394
+ if let kind = end.kind {
395
+ let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
396
+ ?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
397
+ failedLoad = (failing, inSourceRoot: navigation == nil || navigation !== directoryOnlyNavigation)
398
+ onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
399
+ }
400
+ loadEnded(end.outcome, callback)
483
401
  }
484
402
 
485
- private func loadEnded(_ error: Error? = nil, _ callback: (WKNavigationDelegate) -> Void) {
486
- outcome = error.map { ended(with: $0) } ?? "finished"
403
+ private func loadEnded(_ outcome: Loads.Outcome, _ callback: (WKNavigationDelegate) -> Void) {
404
+ self.outcome = outcome
487
405
  // The spinner stops, or it would ignore the next pull.
488
406
  refreshControl.endRefreshing()
489
407
  scheduleUpdate()
490
408
  forward(callback)
491
409
  }
492
410
 
493
- /// The web content process died. The WKWebView survives it, so reload, unless it keeps crashing.
411
+ /// The WKWebView survives its web content process's death.
494
412
  func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
495
413
  let recovered = Recovery.crashAllowsReload(&crashTimes, now: ProcessInfo.processInfo.systemUptime) && !onPostSource
496
414
  endDocument(.crashed)
497
- if lastEmitted?["loading"] as? Bool == true { outcome = "failed" } // the load the crash cut off
415
+ if lastEmitted?["loading"] as? Bool == true { outcome = .failed }
498
416
  if recovered {
499
417
  recoveryPending = true
500
418
  recoverIfVisible()
@@ -504,9 +422,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
504
422
  }
505
423
  }
506
424
 
507
- /// What the hooks see of this view, through a HookContext per attached hook.
508
425
  extension MinimalWebView {
509
- /// Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewClass` whose key turns on.
510
426
  private func optionsChanged(from old: [String: Any]) {
511
427
  for key in inRegistrationOrder(Set(old.keys).union(hookOptions.keys), MinimalWebViewHooks.hooks.map(\.key)) {
512
428
  let (was, value) = (old[key], hookOptions[key])
@@ -523,7 +439,6 @@ extension MinimalWebView {
523
439
  guard let webView, let hook = MinimalWebViewHooks.hooks.first(where: { $0.key == key }) else {
524
440
  return warn("extension \(key): no hook is registered under this key")
525
441
  }
526
- // configure edits the configuration the WKWebView was created from, and webViewClass makes it: too late for this one.
527
442
  guard hook.configure == nil, hook.webViewClass == nil else {
528
443
  let why = hook.configure != nil ? "configure" : "a webViewClass"
529
444
  return warn("extension \(key): its hook has \(why), so it attaches only when the WebView is created")
@@ -537,7 +452,6 @@ extension MinimalWebView {
537
452
  hookContexts.first { $0.key == key && $0.isOn }?.handlers[method]
538
453
  }
539
454
 
540
- /// Gives the proxy the delegates of the hooks that are on, in attach order, then each hook's own order.
541
455
  func routeDelegates() {
542
456
  let on = hookContexts.filter(\.isOn)
543
457
  proxy.navigationDelegates = on.flatMap(\.navigationDelegates)
@@ -41,7 +41,7 @@ public class MinimalWebViewModule: Module {
41
41
  AsyncFunction("bridgePost") { (view: MinimalWebView, message: String) in view.bridgePost(message) }
42
42
  AsyncFunction("answer") { (view: MinimalWebView, askId: Int, json: String) in
43
43
  let value = try? JSONSerialization.jsonObject(with: Data(json.utf8), options: .fragmentsAllowed)
44
- view.asks.answer(askId, value is NSNull ? nil : value)
44
+ MainActor.assumeIsolated { view.asks.answer(askId, value is NSNull ? nil : value) }
45
45
  }
46
46
  AsyncFunction("hook") { (view: MinimalWebView, name: String, method: String, args: String, promise: Promise) in
47
47
  hook(view, name, method, args, promise)
@@ -92,20 +92,3 @@ private func reject(_ promise: Promise, _ error: Error) {
92
92
  let platform = error as? PlatformError
93
93
  promise.reject(platform?.code ?? "native_error", platform?.message ?? error.localizedDescription)
94
94
  }
95
-
96
- // A prop that fails to convert is dropped whole (ExpoFabricView's try?), so every field is optional.
97
-
98
- struct WebViewSource: Record {
99
- @Field var uri: String? = nil
100
- @Field var headers: [String: String]? = nil
101
- @Field var body: String? = nil
102
- @Field var readAccessRoot: String? = nil
103
- @Field var html: String? = nil
104
- @Field var baseUrl: String? = nil
105
- }
106
-
107
- struct InjectedScript: Record {
108
- @Field var code: String? = nil
109
- @Field var allFrames: Bool? = nil
110
- }
111
-
@@ -1,6 +1,5 @@
1
1
  import Foundation
2
2
 
3
- /// The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Kotlin).
4
3
  enum NavigationRules {
5
4
  struct Request {
6
5
  let url: String
@@ -8,7 +7,6 @@ enum NavigationRules {
8
7
  let newWindow: Bool
9
8
  let userInitiated: Bool
10
9
 
11
- /// The fields JS events carry.
12
10
  var payload: [String: Any] {
13
11
  ["url": url, "mainFrame": mainFrame, "newWindow": newWindow, "userInitiated": userInitiated]
14
12
  }
@@ -22,7 +20,6 @@ enum NavigationRules {
22
20
  let rule: Int?
23
21
  }
24
22
 
25
- /// What rules match; `params` are the query's `&`-separated parameters.
26
23
  private struct Parts {
27
24
  let scheme: String
28
25
  let host: String?
@@ -30,10 +27,8 @@ enum NavigationRules {
30
27
  let params: [String]
31
28
  }
32
29
 
33
- /// Load in place without the rules.
34
30
  private static let internalSchemes: Set<String> = ["about", "data", "javascript"]
35
- /// Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
36
- /// past the engine's limits on what a page may navigate the top frame to.
31
+ /// The core loads an allowed new window itself, past WebKit's limits on what a page may navigate the top frame to.
37
32
  private static let noNewWindowSchemes = internalSchemes.union(["blob", "file"])
38
33
 
39
34
  /// The rules' decision, gated for `ask`: blocked when nothing can answer it (`canAsk` false), allowed when its URL is
@@ -55,7 +50,6 @@ enum NavigationRules {
55
50
  let scheme = request.url.firstIndex(of: ":").map { request.url[..<$0].lowercased() } ?? ""
56
51
  if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: .block, rule: nil) }
57
52
  if internalSchemes.contains(scheme) { return Decision(action: .allow, rule: nil) }
58
- // JS sends defaultNavigationRules when the prop is unset; no rules, nil or empty, match nothing.
59
53
  guard let rules, !rules.isEmpty,
60
54
  let parts = scheme == "blob" ? blobOrigin(request.url) : urlParts(scheme, request.url)
61
55
  else { return Decision(action: .block, rule: nil) }
@@ -66,10 +60,9 @@ enum NavigationRules {
66
60
  }
67
61
 
68
62
  private static func urlParts(_ scheme: String, _ url: String) -> Parts {
69
- // shortcut: an unparseable URL has no host and path "/", so only host-less rules match; parse it by hand when a rule must match such URLs
70
63
  let components = URLComponents(string: url)
71
64
  let rawPath = components?.percentEncodedPath ?? ""
72
- // No authority (`myapp:/abs`, `myapp:open`): the path is "/", as in Kotlin. `file:///x` has an empty one, not none.
65
+ // URLComponents gives `file:///x` an empty host, not none.
73
66
  let path = rawPath.isEmpty || components?.host == nil ? "/" : rawPath
74
67
  let params = components?.percentEncodedQuery?.split(separator: "&").map(String.init) ?? []
75
68
  return Parts(scheme: scheme, host: host(components), path: path, params: params)
@@ -1,14 +1,8 @@
1
1
  import Foundation
2
2
  import WebKit
3
3
 
4
- /// Origin rules in Android's format (the bridge's `allowedOrigins`):
5
- /// `*`, an exact http(s) origin such as `https://example.com:8443`, or `https://*.example.com` for subdomains.
6
- /// Compared case-insensitively, a missing port is the scheme's default, and a malformed rule matches nothing.
7
- /// createBridge validates the rules on the JS side. Cases: src/__tests__/vectors/origin-rules.json.
8
4
  enum OriginRules {
9
- /// The origin string of a frame, `scheme://host[:port]`, or `null` for an opaque origin (no scheme: an html source
10
- /// without `baseUrl`, a sandboxed page). The default port is left out (WebKit reports it as 0) and an IPv6 host is
11
- /// bracketed.
5
+ /// The origin as `location.origin` writes it: `null` for an opaque one (no scheme). WebKit reports a default port as 0.
12
6
  static func origin(_ scheme: String, _ host: String, _ port: Int) -> String {
13
7
  guard !scheme.isEmpty else { return "null" }
14
8
  let defaultPort = scheme == "https" ? 443 : scheme == "http" ? 80 : nil
@@ -16,12 +10,11 @@ enum OriginRules {
16
10
  return "\(scheme)://\(host)" + (port == 0 || port == defaultPort ? "" : ":\(port)")
17
11
  }
18
12
 
19
- /// The origin as `location.origin` writes it, so the bridge can compare the two exactly.
20
13
  static func origin(of security: WKSecurityOrigin) -> String {
21
14
  origin(security.protocol, security.host, security.port)
22
15
  }
23
16
 
24
- static func allows(_ rules: [String], _ origin: String) -> Bool {
17
+ @MainActor static func allows(_ rules: [String], _ origin: String) -> Bool {
25
18
  let value = parse(origin)
26
19
  return rules.contains { rule in
27
20
  guard let r = parse(rule), let o = value, !o.wildcard else { return rule == "*" }
@@ -29,13 +22,11 @@ enum OriginRules {
29
22
  }
30
23
  }
31
24
 
32
- // Built once: a regex literal in the function body is compiled again on every call. Regex isn't Sendable; every
33
- // caller is a WebKit delegate callback on the main thread.
34
- nonisolated(unsafe) private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
25
+ @MainActor private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
35
26
 
36
27
  private struct Parsed { let scheme: Substring, wildcard: Bool, host: Substring, port: Int }
37
28
 
38
- private static func parse(_ text: String) -> Parsed? {
29
+ @MainActor private static func parse(_ text: String) -> Parsed? {
39
30
  guard let m = try? pattern.wholeMatch(in: text.lowercased()) else { return nil }
40
31
  return Parsed(scheme: m.1, wildcard: m.2 != nil, host: m.3, port: m.4.flatMap { Int($0) } ?? (m.1 == "https" ? 443 : 80))
41
32
  }