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
@@ -2,37 +2,23 @@ import ObjectiveC
2
2
  import UIKit
3
3
  import WebKit
4
4
 
5
- /// The `ios` settings prop, `{ configuration: {…}, preferences: {…}, webpagePreferences: {…}, webView: {…},
6
- /// scrollView: {…} }`, applied by Objective-C property name through Key-Value Coding, so a public property this
7
- /// package doesn't know (one a newer WebKit adds) needs no code here. `configuration` is read once, when the WKWebView
8
- /// is created; the other roots apply live, to `webView.configuration.preferences`,
9
- /// `webView.configuration.defaultWebpagePreferences`, the WKWebView and its scroll view.
10
- ///
11
- /// A value must fit the property's type (coerce); anything else is rejected before KVC runs: a wrong value in an object-typed property can take the process down
12
- /// (WebKit asserts), and an unknown key raises an Objective-C exception Swift can't catch. Underscore (private)
13
- /// properties are refused, and the only private keys accepted are the two react-native-webview sets by KVC
14
- /// (`privateBools`).
15
- ///
16
- /// `get` reads a property of a root and `call` invokes a method on one by selector, through MRWInvoke (MRWInvoke.h),
17
- /// which sets the arguments by the method's signature. For those two, `websiteDataStore` and `httpCookieStore` are
18
- /// roots as well.
19
5
  final class PlatformSettings {
20
- /// "root.key" -> the last value applied or rejected, so an unchanged value is neither applied nor reported again.
6
+ typealias Rejected = (key: String, reason: String)
7
+
21
8
  private var applied: [String: NSObject] = [:]
22
- /// "root.key" of a live root -> its value before the first write (NSNull for nil), set back when the key is removed.
23
9
  private var originals: [String: Any] = [:]
24
10
 
25
11
  /// Applies `settings`. While creating (`configuration` given, no WebView yet) only the `configuration` root applies;
26
- /// live, every other root does (JS remounts the view for a new `configuration`), and a key applied before and missing
27
- /// now goes back to its value before the first write. Returns the rejected keys.
28
- func apply(_ settings: [String: Any], webView: WKWebView?, configuration: WKWebViewConfiguration? = nil) -> [[String: String]] {
29
- var rejected: [[String: String]] = []
12
+ /// live, every other root does, and a key applied before and missing now goes back to its value before the first
13
+ /// write. Returns the rejected keys.
14
+ func apply(_ settings: [String: Any], webView: WKWebView?, configuration: WKWebViewConfiguration? = nil) -> [Rejected] {
15
+ var rejected: [Rejected] = []
30
16
  let creating = configuration != nil
31
- // Before the new values, so restoring one (a scroll view's inset) can't undo another (its offset).
17
+ // Restoring a scroll view's inset can move its offset.
32
18
  if !creating { rejected += restore(removedFrom: settings, webView: webView) }
33
19
  for (rootName, entries) in settings {
34
20
  guard let entries = entries as? [String: Any] else {
35
- rejected.append(["key": rootName, "reason": "not an object"])
21
+ rejected.append((rootName, "not an object"))
36
22
  continue
37
23
  }
38
24
  let isConfiguration = rootName == "configuration"
@@ -43,11 +29,11 @@ final class PlatformSettings {
43
29
  if applied[id] == boxed { continue }
44
30
  applied[id] = boxed
45
31
  guard let object = root(rootName, webView: webView, configuration: configuration) else {
46
- rejected.append(["key": id, "reason": "unknown root: use \(Self.roots)"])
32
+ rejected.append((id, "unknown root: use \(Self.roots)"))
47
33
  continue
48
34
  }
49
35
  if let reason = set(object, key, value, original: isConfiguration ? nil : id) {
50
- rejected.append(["key": id, "reason": reason])
36
+ rejected.append((id, reason))
51
37
  }
52
38
  }
53
39
  }
@@ -55,22 +41,20 @@ final class PlatformSettings {
55
41
  }
56
42
 
57
43
  /// Forgets each applied key `settings` no longer has and sets its original value back; returns those that failed.
58
- private func restore(removedFrom settings: [String: Any], webView: WKWebView?) -> [[String: String]] {
44
+ private func restore(removedFrom settings: [String: Any], webView: WKWebView?) -> [Rejected] {
59
45
  var present = Set<String>()
60
46
  for (rootName, entries) in settings {
61
47
  guard let entries = entries as? [String: Any] else { continue }
62
48
  present.formUnion(entries.keys.map { "\(rootName).\($0)" })
63
49
  }
64
- var failed: [[String: String]] = []
50
+ var failed: [Rejected] = []
65
51
  for id in applied.keys where !present.contains(id) {
66
52
  applied[id] = nil
67
53
  guard let original = originals.removeValue(forKey: id), let dot = id.firstIndex(of: "."),
68
54
  let object = root(String(id[..<dot]), webView: webView, configuration: nil) else { continue }
69
55
  let key = String(id[id.index(after: dot)...])
70
- // shortcut: a null_resettable property (underPageBackgroundColor) comes back as the value read, not as "follow the
71
- // default"; set nil for those if one matters.
72
56
  if let reason = __MRWCatchException({ object.setValue(original is NSNull ? nil : original, forKey: key) }) {
73
- failed.append(["key": id, "reason": "removed, but restoring it failed: \(reason)"])
57
+ failed.append((id, "removed, but restoring it failed: \(reason)"))
74
58
  }
75
59
  }
76
60
  return failed
@@ -126,10 +110,8 @@ final class PlatformSettings {
126
110
  return String(decoding: data, as: UTF8.self)
127
111
  }
128
112
 
129
- /// Selector prefixes `call` refuses: what the ref and the core own (every load, navigation, script, download and
130
- /// delegate selector), private API, the plumbing that would reach either (KVC, KVO's willChange/didChange,
131
- /// performSelector), object lifecycle (init, copy, new: a re-initialized live object, or a +1 result MRWInvoke would
132
- /// leak) and reference counting. `mutable` covers `mutableCopy` and KVC's `mutableArrayValueForKey:` and its kin.
113
+ /// KVC, KVO and performSelector reach any selector; `init`, `copy`, `new` and `mutableCopy` return a +1 object
114
+ /// MRWInvoke would leak.
133
115
  private static let refused = [
134
116
  "_", "load", "go", "reload", "stop", "evaluateJavaScript", "callAsyncJavaScript", "startDownload", "resumeDownload",
135
117
  "setInteractionState", "setNavigationDelegate", "setUIDelegate", "setDelegate", "setValue", "setValuesForKeys", "valueForKey",
@@ -152,8 +134,7 @@ final class PlatformSettings {
152
134
  }
153
135
 
154
136
  /// Sets one property, or returns why not; with `original`, first keeps the value it replaces under that id unless one
155
- /// is kept already. The property's type encoding (`TB`, `TQ`, `T@"NSString"`, `T{UIEdgeInsets=dddd}`, …) decides what
156
- /// the value may be.
137
+ /// is kept already.
157
138
  private func set(_ object: NSObject, _ key: String, _ value: Any, original id: String?) -> String? {
158
139
  guard !key.hasPrefix("_"), !key.contains(".") else { return "private and nested keys are not allowed" }
159
140
  guard let attributes = Self.attributes(object, key) else { return "no such property" }
@@ -174,14 +155,14 @@ final class PlatformSettings {
174
155
  return String(cString: property_getAttributes(property)!).split(separator: ",")
175
156
  }
176
157
 
177
- /// KVC reaches these through WebKit's `_set…` accessors: WebKit declares no property by these names. They widen what
178
- /// `file:` pages read: other `file:` URLs, and any URL.
158
+ /// KVC reaches these through WebKit's `_set…` accessors: WebKit declares no property by these names.
179
159
  private static let privateBools: [String: AnyClass] = [
180
160
  "allowFileAccessFromFileURLs": WKPreferences.self,
181
161
  "allowUniversalAccessFromFileURLs": WKWebViewConfiguration.self,
182
162
  ]
183
163
 
184
- /// `value` as KVC must get it for a property of type encoding `type`; NSNull stands for nil. Nil: doesn't fit.
164
+ /// `value` as KVC must get it for a property of type encoding `type`; NSNull stands for nil. Nil: doesn't fit. A value
165
+ /// of the wrong class in an object-typed property can take the process down (WebKit asserts).
185
166
  private static func coerce(_ value: Any, _ type: String) -> Any? {
186
167
  let isBool = CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID()
187
168
  let number = isBool ? nil : value as? NSNumber
@@ -1,6 +1,5 @@
1
1
  import Foundation
2
2
 
3
- /// The read root of a `file:` load the app starts, from `source.readAccessRoot`.
4
3
  enum ReadAccess {
5
4
  /// `root` when it is a `file:` URL that contains `file`, else `file`'s directory and a warning that says why `root`
6
5
  /// didn't apply. Always a file URL: loadFileURL raises an exception (a crash) for any other.
@@ -10,7 +9,6 @@ enum ReadAccess {
10
9
  guard let url = URL(string: root), url.isFileURL else {
11
10
  return (directory, "source.readAccessRoot \(root) is not a file: URL, so the file's directory applies")
12
11
  }
13
- // Components, not a string prefix: `..` is resolved, and /a/site2 isn't inside /a/site.
14
12
  guard file.standardizedFileURL.pathComponents.starts(with: url.standardizedFileURL.pathComponents) else {
15
13
  return (directory, "source.readAccessRoot \(root) doesn't contain \(file.absoluteString), so the file's directory applies")
16
14
  }
@@ -0,0 +1,18 @@
1
+ import ExpoModulesCore
2
+
3
+ // A prop that fails to convert is dropped whole (ExpoFabricView's try?), so every field is optional.
4
+
5
+ struct WebViewSource: Record {
6
+ @Field var uri: String? = nil
7
+ @Field var headers: [String: String]? = nil
8
+ @Field var body: String? = nil
9
+ @Field var readAccessRoot: String? = nil
10
+ @Field var html: String? = nil
11
+ @Field var baseUrl: String? = nil
12
+ }
13
+
14
+ struct InjectedScript: Record {
15
+ @Field var code: String? = nil
16
+ @Field var allFrames: Bool? = nil
17
+ }
18
+
@@ -1,10 +1,6 @@
1
1
  import Foundation
2
2
 
3
- /// Crash recovery's choices that need no WebView, as on Android (`showsSource` and `crashAllowsReload` in
4
- /// MinimalWebView.kt). Cases: src/__tests__/vectors/recovery.json.
5
3
  enum Recovery {
6
- /// Whether the committed `url` is the page of the `source` with this `uri`: the same `Loads.canonical` form up to
7
- /// trailing slashes.
8
4
  static func showsSource(_ uri: String, _ url: String) -> Bool {
9
5
  func page(_ url: String) -> String {
10
6
  (URL(string: url).map(Loads.canonical) ?? url).replacingOccurrences(of: "/+$", with: "", options: .regularExpression)
@@ -12,15 +8,13 @@ enum Recovery {
12
8
  return page(uri) == page(url)
13
9
  }
14
10
 
15
- /// Records a web content process death at `now` in `times`, and says whether to reload after it: not after more than
16
- /// `maxCrashesPerWindow` in `crashWindow`, a death exactly `crashWindow` back included. `now` is in seconds of
17
- /// `ProcessInfo.systemUptime`, which a change of device time doesn't move.
11
+ /// Records a web content process death at `now`, in seconds of `ProcessInfo.systemUptime`, in `times`, and says
12
+ /// whether to reload after it.
18
13
  static func crashAllowsReload(_ times: inout [TimeInterval], now: TimeInterval) -> Bool {
19
14
  times = times.filter { now - $0 <= crashWindow } + [now]
20
15
  return times.count <= maxCrashesPerWindow
21
16
  }
22
17
  }
23
18
 
24
- // shortcut: a fixed crash-loop guard, make it a prop if an app needs a different policy
25
19
  private let maxCrashesPerWindow = 3
26
20
  private let crashWindow: TimeInterval = 60
@@ -1,30 +1,22 @@
1
1
  import WebKit
2
2
 
3
- /// The `sharedCookies` prop. In the core, not a hook: the copy before the first `source` load is something nothing
4
- /// outside the core can hold.
5
3
  final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
6
- private weak var store: WKHTTPCookieStore?
7
- private var enabled = false
4
+ private weak var observed: WKHTTPCookieStore?
8
5
  private var copyScheduled = false
9
- /// The WebView's cookies at the last copy: one gone from it since is deleted from native too.
10
6
  private var copied: [HTTPCookie] = []
11
7
 
12
- /// Once, before the first `set`: the view's one WKWebView, which a crash keeps.
13
- func didCreate(_ webView: WKWebView) {
14
- store = webView.configuration.websiteDataStore.httpCookieStore
8
+ func set(_ enabled: Bool, for store: WKHTTPCookieStore) {
9
+ let next = enabled ? store : nil
10
+ guard next !== observed else { return }
11
+ observed?.remove(self)
12
+ next?.add(self)
13
+ observed = next
15
14
  }
16
15
 
17
- func set(_ enabled: Bool) {
18
- guard enabled != self.enabled else { return }
19
- self.enabled = enabled
20
- if enabled { store?.add(self) } else { store?.remove(self) }
21
- }
22
-
23
- /// Work that must finish before a `source` load: calls `done` once the native cookies are in the WebView.
16
+ /// Calls `done` once the native cookies are in the WebView.
24
17
  func prepare(done: @escaping () -> Void) {
25
- guard enabled, let store else { return done() }
18
+ guard let store = observed else { return done() }
26
19
  let group = DispatchGroup()
27
- // shortcut: one setCookie per cookie, use iOS 26's batch setCookies once the minimum allows
28
20
  for cookie in HTTPCookieStorage.shared.cookies ?? [] {
29
21
  group.enter()
30
22
  store.setCookie(cookie) { group.leave() }
@@ -32,27 +24,20 @@ final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
32
24
  group.notify(queue: .main, execute: done)
33
25
  }
34
26
 
35
- /// One copy per main-queue turn: `prepare`'s setCookie calls, or a page setting many cookies, each fire this.
36
27
  func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
37
28
  guard !copyScheduled else { return }
38
29
  copyScheduled = true
39
30
  DispatchQueue.main.async { [weak self] in
40
31
  guard let self else { return }
41
- // Cleared before the read: a change after it schedules the next copy.
42
32
  self.copyScheduled = false
43
- self.store?.getAllCookies { [weak self] cookies in
33
+ self.observed?.getAllCookies { [weak self] cookies in
44
34
  guard let self else { return }
45
35
  let key = { (cookie: HTTPCookie) in [cookie.name, cookie.domain, cookie.path] }
46
36
  let present = Set(cookies.map(key))
47
- // Deleted or expired in the WebView (a logout): native drops it too. Cookies only native set stay.
48
37
  self.copied.filter { !present.contains(key($0)) }.forEach(HTTPCookieStorage.shared.deleteCookie)
49
38
  cookies.forEach(HTTPCookieStorage.shared.setCookie)
50
39
  self.copied = cookies
51
40
  }
52
41
  }
53
42
  }
54
-
55
- func detach() {
56
- store?.remove(self)
57
- }
58
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-minimal-webview",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "description": "A React Native WebView that hands you the iOS and Android WebView APIs, instead of wrapping each one in a prop",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -27,11 +27,11 @@
27
27
  "scripts": {
28
28
  "build": "tsc && tsc -p extensions",
29
29
  "clean": "rm -rf build extensions/build",
30
- "pretest": "npm run build:page-client -- --check && npm run gen:platform-types -- --check && npm run gen:defaults -- --check",
30
+ "pretest": "node --test '.github/scripts/*.test.mts' && npm run build:page-client -- --check && npm run gen:platform-types -- --check && npm run gen:defaults -- --check && node .github/scripts/check-docc-topics.mts",
31
31
  "test": "jest",
32
32
  "lint": "eslint --max-warnings 0 src extensions example .github && prettier --check .",
33
33
  "prepare": "npm run clean && npm run build",
34
- "check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && node .github/scripts/check-expo-set.mts && npm run prepare && npm run docs:check && tsc --noEmit -p .github/scripts && tsc --noEmit -p example/maestro/scripts",
34
+ "check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && node .github/scripts/check-expo-set.mts && node .github/scripts/check-lockfile-libc.mts && node .github/scripts/check-cache-keys.mts && (cd example && npx expo export -p ios -p android --dev --no-bytecode --output-dir ../build/example-bundle) && npm run prepare && npm run docs:check && tsc --noEmit -p .github/scripts && tsc --noEmit -p example/maestro/scripts",
35
35
  "mutation": "stryker run .config/stryker.config.json",
36
36
  "build:page-client": "node .github/scripts/build-page-client.mts",
37
37
  "gen:platform-types": "node .github/scripts/gen-platform-types.mts",
@@ -72,7 +72,7 @@
72
72
  "globals": "^17.14.0",
73
73
  "jest": "^30.0.0",
74
74
  "jest-expo": "~58.0.15",
75
- "knip": "6.45.1",
75
+ "knip": "6.46.1",
76
76
  "prettier": "^3.10.1",
77
77
  "react": "19.3.0",
78
78
  "react-native": "0.88.1",
package/src/WebView.tsx CHANGED
@@ -38,11 +38,9 @@ export type AskableEvent = {
38
38
  askId?: number;
39
39
  };
40
40
 
41
- /**
42
- * Page requests the core answers natively, by prop name, and `onNavigation`, for the decisions it reports. Native sends
43
- * JS each only while its prop is set, and reads the set when it would send one, so a prop can come and go.
44
- */
45
- const REQUESTS = [
41
+ export type CoreEventPayloads = { warning: { message: string }; askCancelled: { askId: number } };
42
+
43
+ const REQUEST_HANDLER_PROPS = [
46
44
  'onNavigationRequest',
47
45
  'onOpenExternal',
48
46
  'onFileRequest',
@@ -52,7 +50,6 @@ const REQUESTS = [
52
50
  'onNavigation',
53
51
  ] as const;
54
52
 
55
- /** Every prop that is not a `ViewProps` one, so it never reaches the outermost view. */
56
53
  const OWN = [
57
54
  'source',
58
55
  'ios',
@@ -69,12 +66,11 @@ const OWN = [
69
66
  'onProcessGone',
70
67
  'onLoadStart',
71
68
  'onLoadEnd',
72
- ...REQUESTS,
69
+ ...REQUEST_HANDLER_PROPS,
73
70
  'ref',
74
71
  'children',
75
72
  ] as const satisfies (Exclude<keyof WebViewProps, keyof ViewProps> | 'children')[];
76
73
  type Unlisted = Exclude<Exclude<keyof WebViewProps, keyof ViewProps>, (typeof OWN)[number]>;
77
- // A prop missing from OWN fails to compile here, by name.
78
74
  const OWN_SET: Set<string> &
79
75
  ([Unlisted] extends [never] ? unknown : Record<Unlisted, 'missing from OWN'>) = new Set(OWN);
80
76
 
@@ -82,13 +78,11 @@ type NativeSettings = Record<string, Record<string, SettingValue | undefined>>;
82
78
 
83
79
  type NativeProps = ViewProps &
84
80
  Pick<WebViewProps, 'source' | 'navigationRules' | 'pullToRefresh'> & {
85
- /** With each script's `origins` in its code (`nativeScripts`). */
86
81
  injectedScripts: Omit<InjectedScript, 'origins'>[] | undefined;
87
82
  ref: Ref<NativeMethods>;
88
83
  sharedCookies: boolean | undefined;
89
84
  /**
90
- * The platform's settings by root and name, as JSON: `ios` or `android` with the cross-platform props on top. A
91
- * string, so that a `null` (reset this key) survives the trip; the native dictionary conversion drops it.
85
+ * A string, so that a `null` (reset this key) survives the trip; the native dictionary conversion drops it.
92
86
  */
93
87
  settings: string;
94
88
  bridgeScript: string | undefined;
@@ -111,7 +105,6 @@ export type NativeMethods = {
111
105
  reload(): Promise<void>;
112
106
  stopLoading(): Promise<void>;
113
107
  bridgePost(message: string): Promise<void>;
114
- /** Answers a native `ask`. `json` is JSON, as for `call`. */
115
108
  answer(askId: number, json: string): Promise<void>;
116
109
  /** The JSON-encoded result. */
117
110
  evaluate(script: string): Promise<string>;
@@ -151,7 +144,6 @@ function assertLinked() {
151
144
  const notRegistered = (error: unknown) =>
152
145
  (error as { code?: string } | null)?.code === 'ERR_VIEW_NOT_FOUND';
153
146
 
154
- /** A native call nothing awaits: a rejection is logged, bar one for a view not registered yet, where it does nothing. */
155
147
  const unawaited = (call: Promise<unknown> | undefined, name: string) =>
156
148
  void call?.catch((error: unknown) => {
157
149
  if (!notRegistered(error))
@@ -192,12 +184,9 @@ function useBridgeChangeWarning(bridge: WebViewProps['bridge']) {
192
184
  }, [bridge]);
193
185
  }
194
186
 
195
- /** One native WebView's life: a new creation key remounts it, so its state, ref attachment and bridge start over. */
196
187
  function WebViewInstance({ ref, ...props }: WebViewProps) {
197
188
  const native = useRef<NativeMethods>(null);
198
189
 
199
- // The rejecters of native calls not settled yet. An unmount rejects them: native may never answer (a hook handler
200
- // that never replies), and a late answer then settles nothing.
201
190
  const [inFlight] = useState(() => new Set<(error: Error) => void>());
202
191
  useEffect(
203
192
  () => () => {
@@ -212,25 +201,15 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
212
201
  const gone = (): never => {
213
202
  throw codedError({ code: 'unavailable', message: 'the WebView is gone' });
214
203
  };
215
- const settled = (promise: Promise<string>) =>
216
- new Promise<string>((resolve, reject) => {
204
+ const settled = <T,>(promise: Promise<T>) =>
205
+ new Promise<T>((resolve, reject) => {
217
206
  inFlight.add(reject);
218
- promise.then(
219
- (value) => {
220
- inFlight.delete(reject);
221
- resolve(value);
222
- },
223
- (error: unknown) => {
224
- inFlight.delete(reject);
225
- reject(error);
226
- }
227
- );
207
+ promise.finally(() => inFlight.delete(reject)).then(resolve, reject);
228
208
  });
229
- // Retries each frame until Expo has registered the view.
230
- const mounted = async (call: () => Promise<string> | undefined) => {
209
+ const retriedUntilViewRegistered = async <T,>(call: () => Promise<T> | undefined) => {
231
210
  for (let frame = 0; ; frame++) {
232
211
  try {
233
- return JSON.parse(await settled(call() ?? gone())) as unknown;
212
+ return await settled(call() ?? gone());
234
213
  } catch (error) {
235
214
  if (!notRegistered(error)) throw error;
236
215
  if (frame === 60 || AppState.currentState === 'background') gone();
@@ -238,6 +217,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
238
217
  }
239
218
  }
240
219
  };
220
+ const jsonResultOf = async (call: () => Promise<string> | undefined) =>
221
+ JSON.parse(await retriedUntilViewRegistered(call)) as unknown;
241
222
  return {
242
223
  goBack: () => unawaited(native.current?.goBack(), 'goBack'),
243
224
  goForward: () => unawaited(native.current?.goForward(), 'goForward'),
@@ -249,10 +230,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
249
230
  );
250
231
  return;
251
232
  }
252
- // mounted() parses a JSON result, and load has none. A view that went away or never came loads nothing, as
253
- // a navigation method does after an unmount.
254
233
  unawaited(
255
- mounted(() => native.current?.load(url).then(() => 'null')).catch((error: unknown) => {
234
+ retriedUntilViewRegistered(() => native.current?.load(url)).catch((error: unknown) => {
256
235
  const code = (error as { code?: string } | null)?.code;
257
236
  if (code !== 'unavailable' && code !== 'navigated') throw error;
258
237
  }),
@@ -261,12 +240,12 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
261
240
  },
262
241
  reload: () => unawaited(native.current?.reload(), 'reload'),
263
242
  stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
264
- evaluate: (script) => mounted(() => native.current?.evaluate(script)),
265
- get: (key) => mounted(() => native.current?.get(key)),
243
+ evaluate: (script) => jsonResultOf(() => native.current?.evaluate(script)),
244
+ get: (key) => jsonResultOf(() => native.current?.get(key)),
266
245
  call: (method, args = []) =>
267
- mounted(() => native.current?.call(method, JSON.stringify(args))),
246
+ jsonResultOf(() => native.current?.call(method, JSON.stringify(args))),
268
247
  hook: (name, method, args = []) =>
269
- mounted(() => native.current?.hook(name, method, JSON.stringify(args))),
248
+ jsonResultOf(() => native.current?.hook(name, method, JSON.stringify(args))),
270
249
  };
271
250
  });
272
251
  const publish = useAttach(ref, handle);
@@ -279,7 +258,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
279
258
  if (was.loading && !state.loading) props.onLoadEnd?.(state);
280
259
  };
281
260
 
282
- // The same string while nothing in it changed, so a re-render sends native nothing.
283
261
  const settings = JSON.stringify(platformSettings(props));
284
262
  const injectedScripts = useMemo(
285
263
  () => nativeScripts(props.injectedScripts),
@@ -296,7 +274,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
296
274
  const hookOptions = useHookOptions(props.extensions);
297
275
  const navigationRules = useNavigationRules(props.navigationRules);
298
276
 
299
- // One per ask in flight, by id: aborted when native stops waiting (the core's `askCancelled`) or at unmount.
300
277
  const [asks] = useState(() => new Map<number, AbortController>());
301
278
  useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
302
279
 
@@ -304,33 +281,36 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
304
281
  nativeEvent: { key, name, payload, askId },
305
282
  }: Native<AskableEvent>) => {
306
283
  const core = key === 'core';
307
- // The core's own events: a warning for the developer, and an ask native stopped waiting for.
308
284
  if (core && name === 'warning')
309
- return console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
310
- if (core && name === 'askCancelled') return asks.get(payload['askId'] as number)?.abort();
311
- const request = REQUESTS.find((prop) => core && prop === name);
312
- // The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
285
+ return console.warn(
286
+ `[react-native-minimal-webview] ${(payload as CoreEventPayloads['warning']).message}`
287
+ );
288
+ if (core && name === 'askCancelled')
289
+ return asks.get((payload as CoreEventPayloads['askCancelled']).askId)?.abort();
290
+ const request = REQUEST_HANDLER_PROPS.find((prop) => core && prop === name);
313
291
  const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
314
292
  const handler = request
315
293
  ? (props[request] as ((payload: unknown, signal?: AbortSignal) => unknown) | undefined)
316
- : (_: unknown, signal?: AbortSignal) => owner?.onEvent?.({ name, payload }, signal);
317
- // Only an ask can be cancelled, so only an ask gets a signal.
294
+ : (_: unknown, signal?: AbortSignal) =>
295
+ signal && owner?.onAsk
296
+ ? owner.onAsk({ name, payload }, signal)
297
+ : owner?.onEvent?.({ name, payload }, signal);
318
298
  let controller: AbortController | undefined;
319
299
  if (askId !== undefined) {
320
300
  controller = new AbortController();
321
301
  asks.set(askId, controller);
322
302
  }
323
- const failure = request ? `${request} failed` : `onEvent failed for ${key}.${name}`;
303
+ const failure = request
304
+ ? `${request} failed`
305
+ : `${hookHandlerName(owner, askId)} failed for ${key}.${name}`;
324
306
  let value: unknown = null;
325
307
  try {
326
308
  value = await handler?.(payload, controller?.signal);
327
309
  } catch (error) {
328
- // Native waits on this handler: one that throws still answers, with null (native's safe default).
329
310
  console.error(`[react-native-minimal-webview] ${failure}`, error);
330
311
  }
331
312
  if (askId === undefined) return;
332
313
  asks.delete(askId);
333
- // Native already answered a cancelled ask with null; a late answer would find nothing.
334
314
  if (!controller?.signal.aborted) await native.current?.answer(askId, answerJson(value));
335
315
  };
336
316
 
@@ -358,7 +338,9 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
358
338
  );
359
339
  }
360
340
 
361
- /** An ask's answer for native: null for one JSON can't encode (a function, a cycle, a BigInt), so the ask settles. */
341
+ const hookHandlerName = (owner: HookExtension | undefined, askId: number | undefined) =>
342
+ askId !== undefined && owner?.onAsk ? 'onAsk' : 'onEvent';
343
+
362
344
  function answerJson(value: unknown) {
363
345
  try {
364
346
  return JSON.stringify(value) ?? 'null';
@@ -367,10 +349,6 @@ function answerJson(value: unknown) {
367
349
  }
368
350
  }
369
351
 
370
- /**
371
- * The scripts as native runs them: one whose `origins` lack `*` runs inside a function, so that even its function
372
- * declarations take effect only where the guard lets it run.
373
- */
374
352
  function nativeScripts(scripts: InjectedScript[] | undefined) {
375
353
  return scripts?.map(({ code, allFrames, origins }) => {
376
354
  if (!Array.isArray(origins))
@@ -380,10 +358,6 @@ function nativeScripts(scripts: InjectedScript[] | undefined) {
380
358
  });
381
359
  }
382
360
 
383
- /**
384
- * The rules as the core gets them (`checkNavigationRules`), and a development warning for each malformed one. The same
385
- * array when none is malformed.
386
- */
387
361
  function useNavigationRules(rules: WebViewProps['navigationRules']) {
388
362
  const { checked, warnings } = useMemo(
389
363
  () => checkNavigationRules(rules ?? defaultNavigationRules),
@@ -393,27 +367,23 @@ function useNavigationRules(rules: WebViewProps['navigationRules']) {
393
367
  return checked;
394
368
  }
395
369
 
396
- /** Logs each warning in development, again only when the list changes. */
370
+ function useJsonStable<T>(value: T): T {
371
+ const json = JSON.stringify(value);
372
+ return useMemo(() => JSON.parse(json) as T, [json]);
373
+ }
374
+
397
375
  function useDevWarnings(warnings: string[]) {
398
- const json = JSON.stringify(warnings);
376
+ const stable = useJsonStable(warnings);
399
377
  useEffect(() => {
400
378
  if (!__DEV__) return;
401
- for (const warning of JSON.parse(json) as string[])
402
- console.warn(`[react-native-minimal-webview] ${warning}`);
403
- }, [json]);
379
+ for (const warning of stable) console.warn(`[react-native-minimal-webview] ${warning}`);
380
+ }, [stable]);
404
381
  }
405
382
 
406
- /** The `REQUESTS` with a prop set, as a new array only when that set changes. */
407
- function useRequestHandlers(props: WebViewProps) {
408
- const key = REQUESTS.filter((prop) => props[prop]).join();
409
- return useMemo(() => (key ? key.split(',') : []), [key]);
383
+ function useRequestHandlers(props: WebViewProps): string[] {
384
+ return useJsonStable(REQUEST_HANDLER_PROPS.filter((prop) => props[prop]));
410
385
  }
411
386
 
412
- /**
413
- * The core's `hookOptions`: each extension's `options` by its key, the later of two extensions with one key winning (a
414
- * development warning). The same object while the JSON is the same, so a render with new handlers sends the core
415
- * nothing.
416
- */
417
387
  function useHookOptions(extensions: WebViewProps['extensions']) {
418
388
  const on = (extensions ?? []).filter((extension) => !!extension);
419
389
  const keys = on.map(({ key }) => key);
@@ -422,25 +392,14 @@ function useHookOptions(extensions: WebViewProps['extensions']) {
422
392
  (key) => `extensions: two extensions have the key ${key}; the later one wins`
423
393
  )
424
394
  );
425
- const json = JSON.stringify(
426
- withoutOff(
427
- Object.fromEntries(
428
- // An unset `options` is `true` (HookExtension.options).
429
- on.map(({ key, options = true }) => [key, options])
430
- )
431
- )
395
+ return useJsonStable<Record<string, unknown>>(
396
+ withoutOff(Object.fromEntries(on.map(({ key, options = true }) => [key, options])))
432
397
  );
433
- return useMemo(() => JSON.parse(json) as Record<string, unknown>, [json]);
434
398
  }
435
399
 
436
- /** Bridges by identity, for the creation key. */
437
400
  const bridgeIds = new WeakMap<object, number>();
438
401
  let lastBridgeId = 0;
439
402
 
440
- /**
441
- * What native sets up once, at creation (the bridge, `ios.configuration`). As WebViewInstance's `key`, a change
442
- * remounts it.
443
- */
444
403
  function creationKey(props: WebViewProps) {
445
404
  const bridge = props.bridge;
446
405
  let id = bridge && bridgeIds.get(bridge);
@@ -451,13 +410,11 @@ function creationKey(props: WebViewProps) {
451
410
  );
452
411
  }
453
412
 
454
- /** A null or false value is off, and its key is left out: native treats a present key as on. */
455
413
  const withoutOff = (options: Record<string, unknown>) =>
456
414
  Object.fromEntries(
457
415
  Object.entries(options).filter(([, value]) => value != null && value !== false)
458
416
  );
459
417
 
460
- /** A JSON.stringify replacer: the same options in another key order are the same key. */
461
418
  const sortedKeys = (_: string, value: unknown) =>
462
419
  value && typeof value === 'object' && !Array.isArray(value)
463
420
  ? Object.fromEntries(Object.entries(value).sort())
@@ -467,7 +424,6 @@ function viewPropsOf(props: WebViewProps): ViewProps {
467
424
  return Object.fromEntries(Object.entries(props).filter(([key]) => !OWN_SET.has(key)));
468
425
  }
469
426
 
470
- /** Each root's keys with its `other` ones among them, as native takes them; a generated key wins. */
471
427
  const flattened = (
472
428
  roots: Record<string, { other?: NativeSettings[string] } | undefined> = {}
473
429
  ): NativeSettings =>
@@ -475,18 +431,12 @@ const flattened = (
475
431
  Object.entries(roots).map(([name, { other, ...keys } = {}]) => [name, { ...other, ...keys }])
476
432
  );
477
433
 
478
- /** Each layer's roots over the earlier layers', key by key. */
479
434
  const layered = (...layers: NativeSettings[]) =>
480
435
  layers.reduce<NativeSettings>((out, layer) => {
481
436
  for (const [root, keys] of Object.entries(layer)) out[root] = { ...out[root], ...keys };
482
437
  return out;
483
438
  }, {});
484
439
 
485
- /**
486
- * The platform's settings for native: the package's defaults, react-native-webview's over them, the app's `ios` or
487
- * `android` roots over those, and `userAgent` on top. Native restores the key of a removed `userAgent`. Android's
488
- * own defaults are written natively.
489
- */
490
440
  function platformSettings(props: WebViewProps): NativeSettings {
491
441
  const [defaults, rnw, app, userAgent] =
492
442
  Platform.OS === 'ios'