react-native-minimal-webview 0.0.0-stage → 1.0.0

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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
package/src/types.ts ADDED
@@ -0,0 +1,1194 @@
1
+ import type { Ref } from 'react';
2
+ import type { ViewProps } from 'react-native';
3
+
4
+ import type { BridgeConnection, CONNECTION } from './bridge/createBridge';
5
+ import type {
6
+ AndroidSettingKeys,
7
+ CGPoint,
8
+ CGRect,
9
+ CGSize,
10
+ IOSSettingKeys,
11
+ UIEdgeInsets,
12
+ } from './platform.generated';
13
+
14
+ /**
15
+ * What the WebView loads: a URL, or an HTML string.
16
+ * @group WebView
17
+ */
18
+ export type WebViewSource =
19
+ | {
20
+ /**
21
+ * The URL to load.
22
+ *
23
+ * A `file://` URL reads only within `readAccessRoot` on iOS; Android needs `android.settings.allowFileAccess`,
24
+ * which lets a `file:` page read any file the app can.
25
+ */
26
+ uri: string;
27
+ /** Sent with the first request only, not on later navigations. */
28
+ headers?: Record<string, string>;
29
+ /**
30
+ * Makes the request a POST with this form-urlencoded body.
31
+ *
32
+ * Its `Content-Type` is `application/x-www-form-urlencoded` unless iOS `headers` set one; Android sends no
33
+ * `headers`.
34
+ * `reload()` sends the POST again; {@link ProcessGoneEvent.recovered | crash recovery} doesn't.
35
+ * @example
36
+ * ```ts
37
+ * const source: WebViewSource = { uri: 'https://example.com/form', body: 'a=1&b=2' };
38
+ * ```
39
+ */
40
+ body?: string;
41
+ /**
42
+ * For a `file://` `uri`, the `file://` directory the page may read, which must contain the file. Without it, or
43
+ * when it isn't a `file:` URL or doesn't contain the file (a warning says so), the file's directory.
44
+ * @ios
45
+ */
46
+ readAccessRoot?: string;
47
+ }
48
+ | {
49
+ /** The page's HTML. */
50
+ html: string;
51
+ /** The page's URL: its relative URLs resolve against it, and it has this origin. Without it, `about:blank`. */
52
+ baseUrl?: string;
53
+ };
54
+
55
+ /**
56
+ * What happens to a navigation.
57
+ *
58
+ * - `allow`: it loads in place, on iOS a tapped universal link too (instead of opening the app that claims it).
59
+ * - `block`: it is cancelled.
60
+ * - `external`: `onOpenExternal`, or else the system, opens it.
61
+ * @group Navigation
62
+ */
63
+ export type NavigationAction = 'allow' | 'block' | 'external';
64
+
65
+ /**
66
+ * A pattern over a navigation's URL and kind, and what the navigations it matches do.
67
+ *
68
+ * Every field it sets must match; for a list, one matching entry is enough. A field left out matches anything; a flag
69
+ * set to `false` matches only the requests without it.
70
+ * @example
71
+ * ```ts
72
+ * const navigationRules: NavigationRule[] = [
73
+ * { query: ['gad_source', 'utm_term=google'], action: 'block' }, // gad_source with any value, utm_term only =google
74
+ * { scheme: ['tel', 'mailto'], action: 'external' },
75
+ * { host: ['*.example.com'], path: ['/checkout'], action: 'external' }, // shop.example.com/checkouts too
76
+ * { host: ['example.com', '*.example.com'], action: 'allow' }, // *.example.com alone skips example.com
77
+ * ];
78
+ * ```
79
+ * @group Navigation
80
+ */
81
+ export type NavigationRule = {
82
+ /** URL schemes without the `:` (`tel`), exact and case-insensitive. */
83
+ scheme?: string[];
84
+ /**
85
+ * Hosts: exact, or a `*.` suffix wildcard that matches subdomains only, not the domain itself.
86
+ *
87
+ * Case, port, userinfo and a trailing dot are ignored.
88
+ */
89
+ host?: string[];
90
+ /**
91
+ * Path prefixes: plain prefixes of the percent-encoded URL path, not whole segments.
92
+ *
93
+ * A URL without an authority (`myapp:/open`) has the path `/`.
94
+ */
95
+ path?: string[];
96
+ /**
97
+ * Query parameters, percent-encoded as in the URL and case-sensitive: a name matches that parameter whatever its
98
+ * value, and `name=value` only that exact value.
99
+ */
100
+ query?: string[];
101
+ /**
102
+ * The main frame's navigation (true) or an iframe's (false).
103
+ *
104
+ * Android decides only an iframe's non-http(s) navigations, so a `mainFrame: false` rule for http(s) is iOS only.
105
+ */
106
+ mainFrame?: boolean;
107
+ /**
108
+ * A `target=_blank` or `window.open` navigation, always a main-frame one.
109
+ *
110
+ * An allowed one loads in place: there is never a second WebView, so no `window.opener` (a native hook that takes
111
+ * `createWebViewWith` on iOS or `onCreateWindow` on Android owns real popups).
112
+ *
113
+ * One to `data:`, `blob:`, `javascript:`, `about:` or `file:` is always blocked (on Android, WebView may still run a
114
+ * `javascript:` one's script, with the page's origin), and one opened with no URL (`window.open('')`) is decided by
115
+ * the URL the page sends it to within 5 s, and dropped otherwise.
116
+ *
117
+ * One opened without a user gesture reaches the rules only with `javaScriptCanOpenWindowsAutomatically` on
118
+ * (`ios.preferences`, `android.settings`; off by default); otherwise WebKit or WebView drops it unreported.
119
+ */
120
+ newWindow?: boolean;
121
+ /**
122
+ * A user gesture started it: the user's tap, click or key press.
123
+ *
124
+ * - Android: WebView's flag (`hasGesture()`, `onCreateWindow`'s `isUserGesture`), Chromium's user activation, which
125
+ * a tap that doesn't scroll, a click or a key press gives the page for up to 5 s. Any navigation the page starts in
126
+ * that time is true: a `location.href` change or `window.open` from a click handler, a timer's, a link a script
127
+ * clicks.
128
+ * - iOS: only a link activation (`<a>`, `<area>`, `target=_blank` too) within 1 s after a tap on the WebView that
129
+ * scrolls and zooms nothing. WebKit reports a link a script clicks as it does a tapped one, so the core times the
130
+ * tap itself. A `location.href` change or `window.open` is false, from a click handler too, as is a link activated
131
+ * from a hardware keyboard; a tapped link's redirect is true only within that second. VoiceOver and Switch Control
132
+ * activate a link without a touch: while either runs, every link activation is true, a script's too.
133
+ *
134
+ * A redirect of a load the core starts itself (an allowed new window, and on Android an allowed `ask`) is never
135
+ * user-initiated.
136
+ */
137
+ userInitiated?: boolean;
138
+ /**
139
+ * What the navigations it matches do; `ask` puts each to `onNavigationRequest`.
140
+ *
141
+ * On Android, which can't hold a navigation until JS answers, it works only for the main frame (elsewhere it is
142
+ * `block`): the navigation is cancelled, and an allowed one loads again after the answer, without the page's referrer
143
+ * policy or the gesture flag.
144
+ */
145
+ action: NavigationAction | 'ask';
146
+ };
147
+
148
+ /**
149
+ * A navigation an `ask` rule puts to `onNavigationRequest`, or an `external` one to `onOpenExternal`.
150
+ * @group Navigation
151
+ */
152
+ export type NavigationRequest = {
153
+ /** The URL it goes to. */
154
+ url: string;
155
+ /** Whether it's the main frame's, not an iframe's. */
156
+ mainFrame: boolean;
157
+ /** Whether it's a new-window navigation ({@link NavigationRule.newWindow}). */
158
+ newWindow: boolean;
159
+ /** Whether a user gesture started it ({@link NavigationRule.userInitiated}). */
160
+ userInitiated: boolean;
161
+ };
162
+
163
+ /**
164
+ * A navigation decision, for `onNavigation`.
165
+ * @group Navigation
166
+ */
167
+ export type NavigationEvent = NavigationRequest & {
168
+ /** Without `onOpenExternal`, or when it returns false, an `external` URL that no app opens is reported as `block`. */
169
+ action: NavigationAction;
170
+ /**
171
+ * Index of the matching rule in `navigationRules`, or in {@link defaultNavigationRules} when that is unset; null when
172
+ * no rule decided (none matched, a scheme that always loads in place or is always blocked, or a download opened
173
+ * externally).
174
+ */
175
+ rule: number | null;
176
+ };
177
+
178
+ /**
179
+ * A WebView's navigation state, as native reports it: from `useWebViewState` and `onNavigationStateChange`.
180
+ *
181
+ * While no WebView is mounted it is the initial state: `url` and `title` empty, `pendingUrl` and `outcome` null,
182
+ * `loading`, `canGoBack` and `canGoForward` false, `progress` 0.
183
+ * @group Navigation
184
+ */
185
+ export type NavigationState = {
186
+ /**
187
+ * The page on screen: changes on commit and same-document navigation (pushState, replaceState, hash), and stays the
188
+ * old page while a load is in progress.
189
+ *
190
+ * After a failed load, the failed URL. Iframes never change it.
191
+ */
192
+ url: string;
193
+ /**
194
+ * A main-frame load in progress, which may still fail or be blocked.
195
+ *
196
+ * Iframes never change it. Always null on Android with a WebView older than 146.
197
+ */
198
+ pendingUrl: string | null;
199
+ title: string;
200
+ loading: boolean;
201
+ /** From 0 to 1. */
202
+ progress: number;
203
+ canGoBack: boolean;
204
+ canGoForward: boolean;
205
+ /**
206
+ * How the last main-frame load ended; null while one is loading, and before the first.
207
+ *
208
+ * - `failed`: a network or SSL error, or a renderer crash, cut it off.
209
+ * - `cancelled`: it never showed a page (a stop before the response, a download, a 204, a redirect the rules blocked,
210
+ * a load a newer one replaced); a stop after the page arrived is `cancelled` on iOS but `finished` on Android, and
211
+ * a 204 is `finished` on iOS 17.
212
+ *
213
+ * An HTTP error status (404) is `finished`: the site's page shows, and `onError` gets an `http` error. On Android
214
+ * with a WebView older than 146, a load that never commits changes nothing here.
215
+ */
216
+ outcome: 'finished' | 'failed' | 'cancelled' | null;
217
+ };
218
+
219
+ /**
220
+ * A main-frame error, for `onError`.
221
+ *
222
+ * - `network` and `ssl`: the load failed, no page arrived; an SSL error always cancels the load. `code` is the
223
+ * platform's own: on iOS the `NSError` code (an `NSURLError*` constant, usually), on Android `WebViewClient.ERROR_*`
224
+ * for `network` and `SslError.SSL_*` for `ssl`.
225
+ * - `http`: the response had an HTTP error status (400+), and the site's own error page shows.
226
+ * @group Events
227
+ */
228
+ export type LoadErrorEvent =
229
+ | { kind: 'network' | 'ssl'; url: string; code: number; description: string }
230
+ | { kind: 'http'; url: string; statusCode: number };
231
+
232
+ /**
233
+ * The renderer process died, for `onProcessGone`.
234
+ * @group Events
235
+ */
236
+ export type ProcessGoneEvent = {
237
+ /**
238
+ * Why it died: `crash` when the renderer crashed, `memory` when the system killed it to reclaim memory, and `unknown`
239
+ * on iOS, where WebKit doesn't say.
240
+ */
241
+ cause: 'crash' | 'memory' | 'unknown';
242
+ /**
243
+ * Whether the core reloads the page: on iOS in place; on Android in a new WebView, once the view's window is visible,
244
+ * with the history restored unless the `source` page was on screen, and with the props applied but not what `call`
245
+ * set.
246
+ *
247
+ * False while a POST `source` is on screen, which, as in a browser, isn't sent again unasked (`reload()` sends it),
248
+ * and after more than 3 crashes in 60 s, counted for the whole app on Android, until the next
249
+ * {@link WebViewRef.reload | reload()} (on iOS also a `source` change); pull-to-refresh doesn't lift it.
250
+ */
251
+ recovered: boolean;
252
+ };
253
+
254
+ /**
255
+ * Runs at document start, before any page script and before the DOM is parsed.
256
+ * @example
257
+ * ```ts
258
+ * const script: InjectedScript = {
259
+ * code: "addEventListener('DOMContentLoaded', () => document.body.classList.add('in-app'));",
260
+ * origins: ['https://example.com'],
261
+ * };
262
+ * ```
263
+ * @group Scripts
264
+ */
265
+ export type InjectedScript = {
266
+ code: string;
267
+ /**
268
+ * Runs it in every frame, iframes included.
269
+ * @default `false`
270
+ */
271
+ allFrames?: boolean;
272
+ /**
273
+ * The origins whose frames run it, in the syntax of {@link BridgeOptions.allowedOrigins}. Each frame is matched by
274
+ * its own `location.origin`, so a listed page's iframes from other origins don't run it; about:blank and srcdoc
275
+ * frames have their parent's origin. `'*'` matches every origin, opaque ones (`data:`, sandboxed frames) and
276
+ * `file:` included; `[]` matches none.
277
+ *
278
+ * Without `'*'` in the list, the code runs inside a function: its top-level `let`, `const`, `class`, `function` and
279
+ * `var` stay local to it, so put what the page should see on `window`. An invalid rule throws when the WebView
280
+ * renders.
281
+ */
282
+ origins: string[];
283
+ };
284
+
285
+ /**
286
+ * Who sent a call or event: the page's origin as `location.origin` writes it (`https://example.com:8443`), checked by
287
+ * native code, not taken from the page.
288
+ *
289
+ * Every allowed origin gets the same trust; a handler scopes itself with this.
290
+ * @group Bridge
291
+ */
292
+ export type BridgeSender = { origin: string };
293
+
294
+ /**
295
+ * Answers a bridge call: the return value (a promise is awaited) is the result.
296
+ *
297
+ * A throw or rejection rejects the call with the {@link ErrorCode} `handler_error` and the error's message.
298
+ * @group Bridge
299
+ */
300
+ export type BridgeHandler<Params = unknown, Result = unknown> = (
301
+ params: Params,
302
+ sender: BridgeSender
303
+ ) => Result | Promise<Result>;
304
+
305
+ /**
306
+ * What crosses a bridge, for `createBridge<Schema>`: the methods each side handles, which the other side calls, and the
307
+ * events.
308
+ *
309
+ * With a schema, `handle` takes only the `reactNative` methods and `call` only the `page` ones, `emit` and `on` only its
310
+ * events (another name doesn't compile), and `params` or a payload is required where its type doesn't allow
311
+ * `undefined`. A method's `params` and `result` are left out when it has none. Every key is required: `{}` for a side
312
+ * that handles nothing. The method and event maps are `type`s or written inline, not `interfaces` (an interface has no
313
+ * index signature, so it doesn't satisfy `Record`).
314
+ * @example
315
+ * ```ts
316
+ * type ShopBridge = {
317
+ * reactNative: { share: { params: { url: string }; result: boolean } };
318
+ * page: { getCartCount: { result: number } };
319
+ * events: { themeChanged: 'light' | 'dark' };
320
+ * };
321
+ * const bridge = createBridge<ShopBridge>({ allowedOrigins: ['https://example.com'] });
322
+ * ```
323
+ * @group Bridge
324
+ */
325
+ export type BridgeSchema = {
326
+ /** The methods React Native answers with `bridge.handle`, and the page calls with `nativeBridge.call`. */
327
+ reactNative: Record<string, { params?: unknown; result?: unknown }>;
328
+ /** The methods the page answers with `nativeBridge.handle`, and React Native calls with `bridge.call`. */
329
+ page: Record<string, { params?: unknown; result?: unknown }>;
330
+ /** The events, by name and payload, that either side emits and the other listens to. */
331
+ events: Record<string, unknown>;
332
+ };
333
+
334
+ type ParamsOf<Method> = 'params' extends keyof Method ? Method['params' & keyof Method] : undefined;
335
+ type ResultOf<Method> = 'result' extends keyof Method ? Method['result' & keyof Method] : unknown;
336
+ /** `call`'s arguments after the method: `params`, required unless they can be `undefined`, then the options. */
337
+ type CallArgs<Method> =
338
+ undefined extends ParamsOf<Method>
339
+ ? [params?: ParamsOf<Method>, options?: { timeoutMs?: number }]
340
+ : [params: ParamsOf<Method>, options?: { timeoutMs?: number }];
341
+ /** `emit`'s argument after the event: the payload, required unless it can be `undefined`. */
342
+ type PayloadArg<Payload> = undefined extends Payload ? [payload?: Payload] : [payload: Payload];
343
+
344
+ /**
345
+ * A promise-based RPC channel to `window.nativeBridge` in the page, typed by a {@link BridgeSchema}.
346
+ *
347
+ * Attach it with the `bridge` prop. Handlers and listeners belong to the bridge, not to a WebView: they stay across
348
+ * unmounts. Messages have no size limit.
349
+ *
350
+ * What it sends waits for the page's `DOMContentLoaded`, so the handlers and listeners of the page's synchronous and
351
+ * deferred scripts are in place, and never reaches a later page, even one on the same origin. The page's own calls
352
+ * don't wait: one made before React Native has registered its method rejects with `not_found`.
353
+ *
354
+ * A call or event made while no WebView is mounted with the bridge waits the same way. A call's timeout runs
355
+ * meanwhile, and only the latest 1000 are kept: an older call rejects with `unavailable`.
356
+ * Unmounting rejects the calls in flight with `navigated`.
357
+ *
358
+ * The page's `window.nativeBridge` has the same four methods, from its side: {@link PageBridge}.
359
+ * @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#the-bridge)
360
+ * @group Bridge
361
+ */
362
+ export type Bridge<Schema extends BridgeSchema = BridgeSchema> = {
363
+ /**
364
+ * Answers `nativeBridge.call(method, params)` from the page, for a method of the schema's `reactNative`.
365
+ *
366
+ * One handler per method: a later one replaces it. Returns an unsubscribe function, which removes only this handler.
367
+ */
368
+ handle<M extends keyof Schema['reactNative'] & string>(
369
+ method: M,
370
+ handler: BridgeHandler<ParamsOf<Schema['reactNative'][M]>, ResultOf<Schema['reactNative'][M]>>
371
+ ): () => void;
372
+ /**
373
+ * Calls a method of the schema's `page`, which the page registered with `nativeBridge.handle`.
374
+ *
375
+ * Rejects with a {@link CodedError}: `timeout`, `not_found`, `handler_error`, `navigated` or `unavailable`.
376
+ * `timeoutMs` overrides the bridge's for this call, and one that isn't 0 or more rejects with a plain `RangeError`.
377
+ */
378
+ call<M extends keyof Schema['page'] & string>(
379
+ method: M,
380
+ ...args: CallArgs<Schema['page'][M]>
381
+ ): Promise<ResultOf<Schema['page'][M]>>;
382
+ /**
383
+ * Fires an event the page listens to with `nativeBridge.on`.
384
+ *
385
+ * Dropped if the page goes away before it arrives, or if the page has no listener for it.
386
+ */
387
+ emit<E extends keyof Schema['events'] & string>(
388
+ event: E,
389
+ ...payload: PayloadArg<Schema['events'][E]>
390
+ ): void;
391
+ /**
392
+ * Listens to `nativeBridge.emit(event, payload)` from the page. Returns an unsubscribe function.
393
+ *
394
+ * A listener that throws is reported as an unhandled promise rejection; the event's other listeners still run.
395
+ */
396
+ on<E extends keyof Schema['events'] & string>(
397
+ event: E,
398
+ listener: (payload: Schema['events'][E], sender: BridgeSender) => void
399
+ ): () => void;
400
+ /** What `<WebView>` attaches to. Only `createBridge` sets it, so a hand-made or mock `Bridge` doesn't type-check. */
401
+ readonly [CONNECTION]: BridgeConnection;
402
+ };
403
+
404
+ /**
405
+ * The page's `window.nativeBridge`, for the page's own TypeScript: the same {@link BridgeSchema} as {@link Bridge}, read
406
+ * from the page's side.
407
+ *
408
+ * `handle` takes the schema's `page` methods, and its handler gets the params only (no sender), `call` takes the
409
+ * `reactNative` ones, and `emit` and `on` take the `events`. `call` rejects with a {@link CodedError}: `timeout`,
410
+ * `not_found`, `handler_error`, or `navigated` when the page comes back from the back-forward cache. Its timeout
411
+ * defaults to the bridge's `timeoutMs`, and a `timeoutMs` that isn't 0 or more rejects with a plain `RangeError`.
412
+ *
413
+ * `window.nativeBridge` exists only in the main frame of a page on one of the bridge's `allowedOrigins`, so a page
414
+ * declares it optional. The page's project needs this package as a dev dependency for the type, which is a type-only
415
+ * import and costs nothing at runtime, and must share or copy the schema type.
416
+ * @example
417
+ * ```ts
418
+ * import type { PageBridge } from 'react-native-minimal-webview';
419
+ *
420
+ * declare global {
421
+ * interface Window {
422
+ * nativeBridge?: PageBridge<ShopBridge>;
423
+ * }
424
+ * }
425
+ * ```
426
+ * @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#in-the-page)
427
+ * @group Bridge
428
+ */
429
+ export type PageBridge<Schema extends BridgeSchema = BridgeSchema> = {
430
+ /** Answers `bridge.call(method, params)` from React Native. A later handler replaces it. Returns an unsubscribe function. */
431
+ handle<M extends keyof Schema['page'] & string>(
432
+ method: M,
433
+ handler: (
434
+ params: ParamsOf<Schema['page'][M]>
435
+ ) => ResultOf<Schema['page'][M]> | Promise<ResultOf<Schema['page'][M]>>
436
+ ): () => void;
437
+ /** Calls a method React Native registered with `bridge.handle`: `call(method, params, { timeoutMs })`. */
438
+ call<M extends keyof Schema['reactNative'] & string>(
439
+ method: M,
440
+ ...args: CallArgs<Schema['reactNative'][M]>
441
+ ): Promise<ResultOf<Schema['reactNative'][M]>>;
442
+ /** Fires an event React Native listens to with `bridge.on`. */
443
+ emit<E extends keyof Schema['events'] & string>(
444
+ event: E,
445
+ ...payload: PayloadArg<Schema['events'][E]>
446
+ ): void;
447
+ /** Listens to `bridge.emit(event, payload)` from React Native. Returns an unsubscribe function. */
448
+ on<E extends keyof Schema['events'] & string>(
449
+ event: E,
450
+ listener: (payload: Schema['events'][E]) => void
451
+ ): () => void;
452
+ };
453
+
454
+ /**
455
+ * The options of `createBridge`.
456
+ * @group Bridge
457
+ */
458
+ export type BridgeOptions = {
459
+ /**
460
+ * The origins whose pages get `window.nativeBridge`, main frame only: an origin, a `*.` wildcard that matches
461
+ * subdomains only (not the domain itself), an IP literal, or `'*'` for any origin, opaque ones too.
462
+ *
463
+ * Each takes an optional port. http or https, no path, ASCII (punycode) hosts; case is ignored, and a missing port
464
+ * means 80 or 443.
465
+ * @example
466
+ * ```ts
467
+ * createBridge({ allowedOrigins: ['https://example.com', 'https://*.example.com', 'http://[::1]:8080'] });
468
+ * ```
469
+ */
470
+ allowedOrigins: string[];
471
+ /**
472
+ * Per-call timeout in milliseconds, also the default for the page's `nativeBridge.call`; `0` or `Infinity` means
473
+ * none.
474
+ * @default `10000`
475
+ */
476
+ timeoutMs?: number;
477
+ };
478
+
479
+ /**
480
+ * An `<input type="file">`.
481
+ * @android
482
+ * @group Page requests
483
+ */
484
+ export type FileRequest = {
485
+ /** Its `accept` list as written: MIME types and extensions (`.pdf`). */
486
+ accept: string[];
487
+ /** Its `multiple` attribute. */
488
+ multiple: boolean;
489
+ /** Its `capture` attribute: the page wants the camera. */
490
+ capture: boolean;
491
+ };
492
+
493
+ /**
494
+ * A device resource a page can ask for.
495
+ *
496
+ * `geolocation` and `protectedMedia` (the device id DRM playback needs, Widevine) are Android only: on iOS, location
497
+ * always shows WebKit's own prompt, and FairPlay asks nothing.
498
+ * @group Page requests
499
+ */
500
+ export type PermissionResource = 'camera' | 'microphone' | 'geolocation' | 'protectedMedia';
501
+ /**
502
+ * A page's permission request, for `onPermissionRequest`.
503
+ *
504
+ * Only the main frame asks (on Android, which doesn't name the frame, any frame of the top page's origin); other
505
+ * frames, and a page with an opaque origin (`data:`, a sandboxed frame), are denied without asking.
506
+ * @group Page requests
507
+ */
508
+ export type PermissionRequest = {
509
+ /** The requesting page's origin, as `location.origin` writes it; every `file:` page is `file://`. */
510
+ origin: string;
511
+ resources: PermissionResource[];
512
+ };
513
+
514
+ /**
515
+ * A finished download.
516
+ * @group Page requests
517
+ */
518
+ export type Download = {
519
+ ok: true;
520
+ /** A `file://` in the app's cache (iOS: the temporary directory), which the core never deletes. */
521
+ uri: string;
522
+ /**
523
+ * A plain file name, no path, but the page chose it, like the content and `mimeType`: don't open the file as
524
+ * trusted.
525
+ */
526
+ filename: string;
527
+ mimeType: string;
528
+ /** The server URL the file came from; `null` when the page generated it (`data:` or `blob:` URL). */
529
+ url: string | null;
530
+ };
531
+
532
+ /**
533
+ * A download that could not be saved; `kind` says why.
534
+ *
535
+ * - `network`: connecting or reading the response failed, or a redirect was refused.
536
+ * - `http`: the response had an error status (Android only: iOS saves what the server sent).
537
+ * - `data`: the content: a bad `data:` or `blob:` URL, the page not reading its blob, an unsupported scheme, or
538
+ * (Android) a file above 100 MB or a `blob:` URL the main frame can't read (a cross-origin iframe's, or one already
539
+ * revoked).
540
+ * @group Page requests
541
+ */
542
+ export type DownloadFailure =
543
+ | {
544
+ /** Tells it from a {@link Download}. */
545
+ ok: false;
546
+ kind: 'network' | 'data';
547
+ filename: string;
548
+ /** As in {@link Download}. */
549
+ url: string | null;
550
+ description: string;
551
+ }
552
+ | { ok: false; kind: 'http'; filename: string; url: string; statusCode: number };
553
+
554
+ /**
555
+ * What `onDownload` gets.
556
+ * @group Page requests
557
+ */
558
+ export type DownloadResult = Download | DownloadFailure;
559
+
560
+ /**
561
+ * What a platform setting can take: what its property or setter accepts. An object is one of the iOS structs.
562
+ * @group Platform settings
563
+ */
564
+ export type SettingValue =
565
+ boolean | number | string | null | UIEdgeInsets | CGPoint | CGSize | CGRect;
566
+
567
+ /**
568
+ * A settings root: its generated keys ({@link IOSSettingKeys}, {@link AndroidSettingKeys}, from the SDK headers), so a
569
+ * misspelled key fails to compile, and `other` for the keys they lack.
570
+ * @group Platform settings
571
+ */
572
+ export type SettingsRoot<Keys> = Keys & {
573
+ /**
574
+ * Any other key the platform has (a newer SDK's, one the headers don't list), untyped. It is set as if it were at
575
+ * the root; a generated key can't go here.
576
+ */
577
+ other?: Record<string, SettingValue | undefined> & { [K in keyof Keys]?: never };
578
+ };
579
+
580
+ /**
581
+ * The private WebKit settings {@link IOSSettings} takes besides {@link IOSSettingKeys}, both off by default.
582
+ * @ios
583
+ * @group Platform settings
584
+ */
585
+ export type IOSPrivateSettingKeys = {
586
+ /** `WKWebViewConfiguration` */
587
+ configuration: {
588
+ /** Lets a `file:` page read any URL. */
589
+ allowUniversalAccessFromFileURLs?: boolean;
590
+ };
591
+ /** `WKPreferences` */
592
+ preferences: {
593
+ /** Lets a `file:` page read other `file:` URLs. */
594
+ allowFileAccessFromFileURLs?: boolean;
595
+ };
596
+ };
597
+
598
+ /**
599
+ * WebKit settings by Objective-C property name.
600
+ *
601
+ * Any public property works, including ones this package has never heard of (under a root's `other`). The keys the SDK
602
+ * headers list autocomplete, with their `@since`, as do the {@link IOSPrivateSettingKeys}. A value must fit the
603
+ * property's type: enums and option sets by raw value (from {@link IOSConstants}), structs as objects, a `UIColor` as
604
+ * `#rrggbb` or `#rrggbbaa`, an `NSURL` as a string, `websiteDataStore` as `'default'` or `'nonPersistent'`.
605
+ *
606
+ * A key that doesn't fit, a private (`_`) one, or one the device's iOS lacks (its `@since` is newer) is skipped with a
607
+ * warning; nothing here can crash the app. So is a property UIKit declares without runtime metadata, such as
608
+ * `webView.opaque`: set it with `call('webView.setOpaque:', [false])`.
609
+ *
610
+ * A root's default keys are the package's, and yours go over them; a key the package doesn't set keeps WebKit's
611
+ * default, and a key you remove goes back to the value it had before you first set it. The ref's
612
+ * {@link WebViewRef.get | get} and {@link WebViewRef.call | call} take these roots, plus `websiteDataStore` and
613
+ * `httpCookieStore`.
614
+ *
615
+ * WebKit has no mixed-content setting: it applies its own policy.
616
+ * @example
617
+ * ```tsx
618
+ * <WebView
619
+ * source={{ uri: 'https://example.com' }}
620
+ * ios={{
621
+ * configuration: { dataDetectorTypes: IOSConstants.DataDetectorTypes.link },
622
+ * scrollView: { bounces: false, contentInset: { top: 0, left: 0, bottom: 80, right: 0 } },
623
+ * }}
624
+ * />
625
+ * ```
626
+ * @ios
627
+ * @see [Platform settings example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#platform-settings)
628
+ * @group Platform settings
629
+ */
630
+ export type IOSSettings = {
631
+ /**
632
+ * `WKWebViewConfiguration`: read once, when the WKWebView is created; a change recreates the WebView (the page
633
+ * reloads and the navigation state starts over). It is a copy, so `call` on it changes nothing.
634
+ * @default `{ allowsInlineMediaPlayback: true }`
635
+ */
636
+ configuration?: SettingsRoot<
637
+ IOSSettingKeys['configuration'] & IOSPrivateSettingKeys['configuration']
638
+ >;
639
+ /** `WKPreferences` (`configuration.preferences`), live. */
640
+ preferences?: SettingsRoot<IOSSettingKeys['preferences'] & IOSPrivateSettingKeys['preferences']>;
641
+ /** `WKWebpagePreferences` (`configuration.defaultWebpagePreferences`), live from the next navigation. */
642
+ webpagePreferences?: SettingsRoot<IOSSettingKeys['webpagePreferences']>;
643
+ /**
644
+ * The `WKWebView`, live.
645
+ * @default `{ inspectable: __DEV__ }`
646
+ */
647
+ webView?: SettingsRoot<IOSSettingKeys['webView']>;
648
+ /**
649
+ * Its `UIScrollView`, live.
650
+ *
651
+ * `directionalLockEnabled` is on by default, as react-native-webview has it.
652
+ */
653
+ scrollView?: SettingsRoot<IOSSettingKeys['scrollView']>;
654
+ };
655
+
656
+ /**
657
+ * Android settings by setter name without `set`.
658
+ *
659
+ * Any public setter works, including ones a newer SDK or androidx.webkit adds (under a root's `other`). The keys the
660
+ * SDK lists autocomplete, with their `@since`; the constants are in {@link AndroidConstants}. An `int` setter takes a
661
+ * number up to `0xFFFFFFFF`, truncated, so an ARGB color such as `0xFF202020` works.
662
+ *
663
+ * A key with no public setter for the value's type, or one this device's WebView lacks, is skipped with a warning;
664
+ * nothing here can crash the app. A root's default keys are the package's, and yours go over them; a key the package
665
+ * doesn't set, such as `overScrollMode`, keeps the platform's default. A key you remove goes back to the value it had
666
+ * before you first set it; one with no getter, such as `geolocationEnabled`, keeps its value until the WebView is
667
+ * recreated, with a warning.
668
+ *
669
+ * The ref's {@link WebViewRef.get | get} and {@link WebViewRef.call | call} take these roots, plus `cookieManager` and
670
+ * `webStorage`, the WebView profile's (`webView.profile`, the default one unless set); a key is the getter's name
671
+ * without `get` or `is`.
672
+ * @example
673
+ * ```tsx
674
+ * <WebView
675
+ * source={{ uri: 'https://example.com' }}
676
+ * android={{
677
+ * settings: { textZoom: 120, cacheMode: AndroidConstants.WebSettings.LOAD_NO_CACHE },
678
+ * webView: { overScrollMode: 2 },
679
+ * }}
680
+ * />
681
+ * ```
682
+ * @android
683
+ * @see [Platform settings example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#platform-settings)
684
+ * @group Platform settings
685
+ */
686
+ export type AndroidSettings = {
687
+ /**
688
+ * `WebSettings` setters, then static `WebSettingsCompat` ones.
689
+ *
690
+ * Each new WebView starts with `javaScriptEnabled`, `domStorageEnabled`, `supportMultipleWindows` and
691
+ * `builtInZoomControls` on; `allowFileAccess`, `allowContentAccess`, `displayZoomControls` and
692
+ * `downloadFaviconsEnabled` off; `mixedContentMode` `MIXED_CONTENT_NEVER_ALLOW`; and, with WebView 146 and newer,
693
+ * `backForwardCacheEnabled` on. `useWideViewPort` and `loadWithOverviewMode` are on by default, as
694
+ * react-native-webview has them. `userAgentString: null` is WebView's default user agent.
695
+ */
696
+ settings?: SettingsRoot<AndroidSettingKeys['settings']>;
697
+ /**
698
+ * `WebView` setters (static and inherited `View` ones too), then `WebViewCompat` ones, then `CookieManager`'s
699
+ * `acceptThirdPartyCookies`.
700
+ *
701
+ * `acceptThirdPartyCookies` is on by default, as react-native-webview has it. `webContentsDebuggingEnabled` is
702
+ * refused: it is process-wide, set with {@link AndroidWebView.setWebContentsDebuggingEnabled}.
703
+ */
704
+ webView?: SettingsRoot<AndroidSettingKeys['webView']>;
705
+ };
706
+
707
+ /**
708
+ * An event a native hook sent with `emit` or `ask`.
709
+ * @typeParam N - The event's name, to type one hook's events.
710
+ * @typeParam P - Its payload.
711
+ * @example
712
+ * ```ts
713
+ * type PageLoaded = HookEvent<'pageLoaded', { count: number }>;
714
+ * ```
715
+ * @group Native hooks
716
+ */
717
+ export type HookEvent<N extends string = string, P = Record<string, unknown>> = {
718
+ /** The name the hook sent it with, such as `pageLoaded`. */
719
+ name: N;
720
+ /** What the hook sent with it. */
721
+ payload: P;
722
+ };
723
+
724
+ /**
725
+ * A native hook's JS side, for {@link WebViewProps.extensions}: its key, its options, and what takes its events.
726
+ *
727
+ * A package with a native hook exports a function that returns one, so that an app turns the hook on by putting it in
728
+ * `extensions`.
729
+ * @typeParam E - The hook's events, to type `onEvent`: a union of {@link HookEvent}s, which nothing checks at runtime.
730
+ * @see [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
731
+ * @group Native hooks
732
+ */
733
+ export type HookExtension<E extends HookEvent = HookEvent> = {
734
+ /**
735
+ * The key the hook is registered under.
736
+ *
737
+ * A key no hook is registered under warns: pass a one-platform hook's extension on that platform only. Two extensions
738
+ * with one key warn in development, and the later one wins.
739
+ */
740
+ key: string;
741
+ /**
742
+ * What the hook gets as its options. Null or false switches the hook off, as does leaving its extension out of
743
+ * `extensions`: it stays attached and gets null, but the core routes none of its delegates, clients or listeners,
744
+ * drops its events, answers its asks with null, and rejects `ref.hook` calls to its handlers with `not_found`.
745
+ * Undefined, the default, means `true`. Turning it on again gives it the new options.
746
+ */
747
+ options?: unknown;
748
+ /**
749
+ * Each of the hook's events: it goes to the extension with the hook's key (the later of two with one key), and one no
750
+ * extension owns is dropped. For an `ask`, the return value (a promise is awaited) is the answer, and `undefined`, or
751
+ * a value JSON can't encode, answers null. `signal` is set only for an `ask`, and aborts when native stops waiting for
752
+ * the answer: an ask has no timeout, but one still open when the page goes away is answered null.
753
+ *
754
+ * The latest `onEvent` always takes the events: a render with new handlers sends native nothing.
755
+ */
756
+ onEvent?(event: E, signal?: AbortSignal): unknown;
757
+ };
758
+
759
+ /**
760
+ * A fullscreen change, for `onFullscreenChange`.
761
+ * @android
762
+ * @group Events
763
+ */
764
+ export type FullscreenChangeEvent = { active: boolean };
765
+
766
+ /**
767
+ * Why a ref method or a bridge call rejected. Each code means the same on every method that rejects with it.
768
+ *
769
+ * - `timeout`: a bridge call got no answer in time.
770
+ * - `not_found`: nothing by that name answers: no bridge handler for the method, no attached hook `name` that is on
771
+ * and handles `method`, or no such root, key, method (on Android, one that takes these arguments) or selector (on
772
+ * this OS or WebView version too; a private `_` key of an iOS `get` too), or a malformed path.
773
+ * - `handler_error`: the handler of a bridge call, on either side, or of a `hook` call failed; the `message` is its
774
+ * error's.
775
+ * - `script_error`: `evaluate`'s script threw, rejected or didn't parse.
776
+ * - `native_error`: the platform refused or failed the call: a member the core owns (or a private selector for an iOS
777
+ * `call`), a key `get` can't read, wrong arguments (iOS), a completion handler `call` can't await, a native
778
+ * exception or `NSError`, or a result JSON can't carry (`NaN`).
779
+ * - `navigated`: the page or the WebView went away while the call was pending (a navigation, a crash, an unmount), so
780
+ * it may have run: retry only what is safe to repeat.
781
+ * - `unavailable`: the call didn't run: the WebView is gone or not mounted yet, is being rebuilt after its renderer
782
+ * died (Android), the bridge's queue was full and dropped it, or lacks the feature (the method's TSDoc names the
783
+ * Android System WebView it needs, or a compat method this WebView doesn't support).
784
+ *
785
+ * A programming error, such as an argument of the wrong type, can reject with a plain `TypeError` instead.
786
+ * @group WebView
787
+ */
788
+ export type ErrorCode =
789
+ | 'timeout'
790
+ | 'not_found'
791
+ | 'handler_error'
792
+ | 'script_error'
793
+ | 'native_error'
794
+ | 'navigated'
795
+ | 'unavailable';
796
+
797
+ /**
798
+ * What a ref method or a bridge call rejects with: an `Error` whose `code` says why.
799
+ * @group WebView
800
+ */
801
+ export type CodedError = Error & { code: ErrorCode };
802
+
803
+ /**
804
+ * What the WebView loads, its settings, and the callbacks for its events and the page's requests.
805
+ *
806
+ * The ones from React Native's `ViewProps` (`style`, `testID`, `nativeID`, the accessibility props, layout and touch
807
+ * events) go to the native view.
808
+ *
809
+ * Every `on…` callback is read when its event or request comes, so adding, changing or removing one applies to the
810
+ * next, and a request without one gets the default described on its prop. One that answers a request and throws (or
811
+ * rejects) is logged with `console.error` and gives the refusing answer: `onNavigationRequest` `block`,
812
+ * `onOpenExternal` null (the core opens nothing), `onFileRequest` cancel, `onPermissionRequest` deny, an extension's
813
+ * `onEvent` null.
814
+ *
815
+ * The `signal` such a callback gets aborts when native stops waiting for its answer (the page moved on, crashed or
816
+ * unmounted), and a late answer is dropped.
817
+ *
818
+ * JS dialogs (`alert`, `confirm`, `prompt`) and HTTP auth have no prop. iOS shows a `UIAlertController` titled with the
819
+ * frame's host, or `JavaScript` for a frame without one (`data:`, sandboxed, `file:`), one at a time (one that comes
820
+ * while another shows is cancelled), and Android WebView's own dialogs. An auth challenge is cancelled on Android, and
821
+ * gets WebKit's default handling on iOS: without a stored credential, the site's 401 page shows. `dialogs` and
822
+ * `basicAuthCredential` of `@react-native-minimal-webview/extensions` take them over, or a native hook does.
823
+ * @group WebView
824
+ */
825
+ export interface WebViewProps extends Omit<ViewProps, 'children'> {
826
+ /**
827
+ * What to load.
828
+ *
829
+ * A new `source` loads at once, unless it equals the loaded one field by field: that loads nothing, even after the
830
+ * page navigated away.
831
+ */
832
+ source: WebViewSource;
833
+ /**
834
+ * WebKit settings by property name; see {@link IOSSettings}.
835
+ * @ios
836
+ */
837
+ ios?: IOSSettings;
838
+ /**
839
+ * Android settings by setter name; see {@link AndroidSettings}.
840
+ * @android
841
+ */
842
+ android?: AndroidSettings;
843
+ /**
844
+ * Replaces the whole user agent, over `ios.webView.customUserAgent` and `android.settings.userAgentString`. Without
845
+ * it, those keys apply; unset, they are the platform's own user agent.
846
+ *
847
+ * To append to the default one instead, set `ios.configuration.applicationNameForUserAgent` and, on Android,
848
+ * `android.settings.userAgentString` to `AndroidWebView.defaultUserAgent` plus your suffix.
849
+ *
850
+ * A change applies from the next navigation.
851
+ */
852
+ userAgent?: string;
853
+ /**
854
+ * Scripts to run at document start, before the page's own, in the frames picked by each script's `allFrames` and
855
+ * `origins`.
856
+ *
857
+ * A change applies from the next navigation. On Android with a WebView older than 101 they don't run (a warning says
858
+ * so, once per process).
859
+ */
860
+ injectedScripts?: InjectedScript[];
861
+ /**
862
+ * Which navigations load in place, open externally or are blocked, decided natively; the first matching rule wins,
863
+ * and with no match the navigation is blocked.
864
+ *
865
+ * Unset, the rules are {@link defaultNavigationRules}; `[]` is no rules, so every navigation they decide is blocked.
866
+ *
867
+ * A malformed rule, one with an unknown key, a field of the wrong type (a list that isn't an array of strings, a flag
868
+ * that isn't a boolean) or no valid `action`, blocks every navigation that reaches it, whatever it was meant to match
869
+ * or do: native would otherwise skip the key or flag and match more than intended, and so could allow more than a
870
+ * correct rule would. In development a warning names the rule's index and the problem, once. The rules before it
871
+ * decide as usual; one that isn't an array is `[]`.
872
+ *
873
+ * `about:`, `data:` and `javascript:` always load in place. A `blob:` URL is decided as the origin it carries:
874
+ * `blob:https://example.com/…` as `https://example.com/`, and one with an opaque origin (`blob:null/…`, made by a
875
+ * `data:` or sandboxed frame, or a page from an html `source` without `baseUrl`) is blocked, a download of it too.
876
+ *
877
+ * The `source` load, reloads and back/forward skip the rules; a redirect of the `source` load doesn't, nor on Android
878
+ * a redirect of a reload or back/forward. The rules never see a form POST, on either platform: it loads in place, and
879
+ * one to a new window loads in place on iOS, and on Android isn't shown (the request may still reach the server).
880
+ *
881
+ * An `external` `intent:` URL (Android) opens only as a browsable intent, without its explicit component or selector;
882
+ * when no app handles it, an http(s) `S.browser_fallback_url` goes through the rules (main frame, no user gesture),
883
+ * and the `intent:` itself is reported as `block`.
884
+ *
885
+ * A change applies from the next navigation.
886
+ *
887
+ * A native hook can take these decisions, defaults included: see `WebViewContext.clients` (Android) and
888
+ * `navigationDelegates` (iOS).
889
+ * @example
890
+ * ```tsx
891
+ * <WebView
892
+ * source={{ uri: 'https://example.com' }}
893
+ * // myapp: opens externally even without a user gesture; everything else as by default
894
+ * navigationRules={[{ scheme: ['myapp'], action: 'external' }, ...defaultNavigationRules]}
895
+ * />
896
+ * ```
897
+ * @see [Navigation rules example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#navigation-rules)
898
+ */
899
+ navigationRules?: readonly NavigationRule[];
900
+ /**
901
+ * Decides each navigation an `ask` rule matches, within 1 s.
902
+ *
903
+ * A late, missing or other answer is `block`, as is one still pending when another page commits; `signal` aborts at
904
+ * the timeout and at that commit. Without this prop, `ask` is `block`. Until the next commit, a URL it allowed isn't
905
+ * asked again on a redirect back to it (Android), or when the same kind of frame loads it again (iOS).
906
+ */
907
+ onNavigationRequest?: (
908
+ request: NavigationRequest,
909
+ signal: AbortSignal
910
+ ) => NavigationAction | Promise<NavigationAction>;
911
+ /**
912
+ * Opens `external` navigations, every one, an Android `intent:` URL included, before `onNavigation` reports them.
913
+ *
914
+ * Return false (a promise is awaited) to hand it back: the core then opens it as it does without this prop, an
915
+ * `intent:`'s fallback URL included. Any other answer, `undefined` too, means you opened it. When `signal` aborts,
916
+ * nothing opens it.
917
+ *
918
+ * Without this prop, the system browser or app for the URL opens it, without asking `canOpenURL` first, so no
919
+ * `LSApplicationQueriesSchemes` (iOS) or `<queries>` (Android) entries are needed.
920
+ */
921
+ onOpenExternal?: (
922
+ request: NavigationRequest,
923
+ signal: AbortSignal
924
+ ) => boolean | void | Promise<boolean | void>;
925
+ /**
926
+ * The bridge to the page, from `createBridge`, of any schema.
927
+ *
928
+ * Read when the WebView is created: another bridge recreates it (the page reloads and the navigation state starts
929
+ * over), so make it once, at module scope or with `useMemo` (in development, a WebView warns the first time another
930
+ * bridge replaces its own). A bridge serves one mounted WebView at a time: attaching it to a second throws.
931
+ *
932
+ * On Android with a WebView older than 101 there is no bridge: calls reject with `unavailable`, and a warning says
933
+ * so, once per process.
934
+ */
935
+ bridge?: Pick<Bridge, typeof CONNECTION>;
936
+ /**
937
+ * The native hooks to turn on, as {@link HookExtension}s: a package with a native hook exports a function that
938
+ * returns one.
939
+ *
940
+ * A false, null or undefined entry is left out, so `on && extension(…)` switches one on and off; see
941
+ * {@link HookExtension.options} for what off means. A hook attaches when its key first appears, and a later change of
942
+ * its `options` reaches it live, without recreating the WebView. A key turned on after the WebView was created
943
+ * attaches its hook then, unless the hook has a `configure` step or its own WebView class (`webViewClass`,
944
+ * `webViewFactory`): that one attaches only when the WebView is created, and a warning says so.
945
+ * @see [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
946
+ */
947
+ extensions?: readonly (HookExtension | false | null | undefined)[];
948
+ /**
949
+ * Pull down at the top of the page to reload: `UIRefreshControl` on iOS, `SwipeRefreshLayout` on Android, where a
950
+ * pull inside a scrolled inner scroller (`overflow: auto`) scrolls it instead.
951
+ *
952
+ * It reloads as {@link WebViewRef.reload | reload()} does, a POST `source` included. A change applies at once.
953
+ * @default `false`
954
+ */
955
+ pullToRefresh?: boolean;
956
+ /**
957
+ * Copies `HTTPCookieStorage` (native requests) into the WebView before each `source` load, which waits for it, and
958
+ * the WebView's cookie changes, deletions included, back as they happen.
959
+ *
960
+ * Android needs nothing: `CookieManager` is shared app-wide, and flushed when the app goes to the background. A
961
+ * WebView on another `android.webView.profile` has that profile's cookies instead.
962
+ * @default `false`
963
+ * @ios
964
+ */
965
+ sharedCookies?: boolean;
966
+ /**
967
+ * Answers `<input type="file">` with `file://` or `content://` URIs, or null to cancel.
968
+ *
969
+ * Without it, the system file chooser opens, one at a time for the whole app, and ignores `capture`: a request while
970
+ * one is open is cancelled, and if the chooser's activity died without returning a result, so is every request until
971
+ * the app restarts.
972
+ *
973
+ * iOS always shows WebKit's picker, which needs `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription`.
974
+ *
975
+ * Until the answer settles, the page's next file request waits.
976
+ * @android
977
+ */
978
+ onFileRequest?: (
979
+ request: FileRequest,
980
+ signal: AbortSignal
981
+ ) => string[] | null | Promise<string[] | null>;
982
+ /**
983
+ * The page entered or left fullscreen (`active`).
984
+ *
985
+ * Fullscreen works without it: the page's view covers the window, the system bars hide and back exits. iOS shows
986
+ * WebKit's own fullscreen, not reported.
987
+ * @android
988
+ */
989
+ onFullscreenChange?: (event: FullscreenChangeEvent) => void;
990
+ /**
991
+ * Camera, microphone and, on Android, location and protected media (DRM) for the main frame.
992
+ *
993
+ * Answer true to grant, having asked the OS first (expo-camera, expo-location): without OS permission the page's
994
+ * request fails anyway. On iOS, true also skips WebKit's own prompt.
995
+ *
996
+ * Without this prop, Android denies and iOS shows WebKit's prompt (location always does). iOS needs
997
+ * `NSCameraUsageDescription` and `NSMicrophoneUsageDescription`, Android the `CAMERA` and `RECORD_AUDIO` manifest
998
+ * permissions. Android keeps a location answer until the page changes.
999
+ *
1000
+ * Anything but true denies. `signal` also aborts when Android withdraws the request. Until the answer settles, the
1001
+ * page's next request of the same kind waits.
1002
+ */
1003
+ onPermissionRequest?: (
1004
+ request: PermissionRequest,
1005
+ signal: AbortSignal
1006
+ ) => boolean | Promise<boolean>;
1007
+ /**
1008
+ * A download finished ({@link Download}) or failed ({@link DownloadFailure}).
1009
+ *
1010
+ * With this prop the core saves the file: iOS downloads it in the page's session; Android fetches it again with the
1011
+ * host's cookies (whatever their SameSite) and the page's user agent. That fetch sends no POST body, `source` headers
1012
+ * or HTTP auth, so a download that needs them can fail, or save the server's login page as the file, and it fails
1013
+ * above 100 MB, on a redirect off https, and for `blob:` on a WebView older than 83.
1014
+ *
1015
+ * Without this prop, an http(s) download opens externally (`onOpenExternal` or the system browser, without the page's
1016
+ * session), and a `data:` or `blob:` one is dropped. A PDF is a download on Android; iOS shows it inline.
1017
+ *
1018
+ * On iOS a file response is a download only in the main frame; an `<a download>` link is one from any frame.
1019
+ *
1020
+ * On Android a native hook's `WebViewContext.onDownloadStart` is offered each download first, and one it takes
1021
+ * reaches neither this prop nor the external fallback.
1022
+ */
1023
+ onDownload?: (result: DownloadResult) => void;
1024
+ /**
1025
+ * Every navigation the rules, or their defaults, decided.
1026
+ *
1027
+ * Not reported: the `source` load, reloads, back/forward, and a navigation a native hook decides.
1028
+ */
1029
+ onNavigation?: (event: NavigationEvent) => void;
1030
+ /**
1031
+ * Every change to the navigation state.
1032
+ *
1033
+ * Changes that arrive together may be combined into one call; `loading` going true is never combined away, so a load
1034
+ * that starts and fails at once still reports both.
1035
+ */
1036
+ onNavigationStateChange?: (state: NavigationState) => void;
1037
+ /**
1038
+ * A main-frame load failed, or got an HTTP error status.
1039
+ *
1040
+ * After a failed load iOS keeps the page before it on screen, and Android shows WebView's own error page. On Android
1041
+ * with a WebView older than 146, an SSL error on a back/forward load isn't reported.
1042
+ *
1043
+ * A renderer crash isn't reported here: it makes the cut-off load's `outcome` `failed` and calls `onProcessGone`.
1044
+ */
1045
+ onError?: (event: LoadErrorEvent) => void;
1046
+ /**
1047
+ * The renderer died; see {@link ProcessGoneEvent} for the recovery.
1048
+ *
1049
+ * Android's WebViews share one renderer, so each of them reports its death.
1050
+ */
1051
+ onProcessGone?: (event: ProcessGoneEvent) => void;
1052
+ /**
1053
+ * `loading` went true.
1054
+ *
1055
+ * On Android with a WebView older than 146, a load that never commits fires neither this nor `onLoadEnd`.
1056
+ */
1057
+ onLoadStart?: (state: NavigationState) => void;
1058
+ /** `loading` went false: `state.outcome` says how the load ended. */
1059
+ onLoadEnd?: (state: NavigationState) => void;
1060
+ /**
1061
+ * Gets the {@link WebViewRef}.
1062
+ *
1063
+ * Give each mounted WebView its own ref: one shared by two points at the last mounted (with a warning in
1064
+ * development), and can turn null when either unmounts.
1065
+ */
1066
+ ref?: Ref<WebViewRef>;
1067
+ }
1068
+
1069
+ /**
1070
+ * The methods a WebView's `ref` gets: navigation, scripts, and platform and hook calls.
1071
+ *
1072
+ * A handle kept after its WebView unmounted is safe to call: the navigation methods do nothing, and `evaluate`, `get`,
1073
+ * `call` and `hook` reject with `unavailable`. One still pending when the WebView unmounts rejects with `navigated`.
1074
+ *
1075
+ * Those four wait up to about a second for a WebView that has just mounted (on Android, a call from the parent's first
1076
+ * effect can come before the view exists), then reject with `unavailable`; in the background they don't wait.
1077
+ * @group WebView
1078
+ */
1079
+ export type WebViewRef = {
1080
+ /**
1081
+ * Goes back one page; does nothing unless `canGoBack`.
1082
+ *
1083
+ * On Android, as Chrome's back button, it also skips the history entries a page added without a user gesture
1084
+ * (`pushState`, a hash change) and the page that added them.
1085
+ */
1086
+ goBack(): void;
1087
+ /** Goes forward one page; does nothing unless `canGoForward`. */
1088
+ goForward(): void;
1089
+ /**
1090
+ * Reloads the page; after a failed load, retries it (the `source` again, with its headers, when that failed), and
1091
+ * loads the `source` when nothing is loaded.
1092
+ *
1093
+ * Sends a POST `source` again, and lifts the limit on {@link ProcessGoneEvent.recovered | crash recovery}.
1094
+ */
1095
+ reload(): void;
1096
+ /** Stops the load: its `outcome` is `cancelled`, or on Android `finished` once the page has arrived. */
1097
+ stopLoading(): void;
1098
+ /**
1099
+ * Runs an expression (not statements) in the page's main frame and awaits it.
1100
+ *
1101
+ * Resolves with its value through JSON: `null` for what JSON can't encode (a function, `NaN`, a cycle), a `Date` as
1102
+ * its ISO string. The value is the page's, so treat it as page data. Rejects with a {@link CodedError}:
1103
+ * `script_error`, `navigated` or `unavailable`. There is no timeout: a page can hold a call until it navigates. On
1104
+ * Android with a WebView older than 83 it rejects with `unavailable`.
1105
+ */
1106
+ evaluate(script: string): Promise<unknown>;
1107
+ /**
1108
+ * Reads a platform setting, `root.key`, and resolves with its value through JSON, as {@link WebViewRef.call | call}
1109
+ * converts results.
1110
+ *
1111
+ * The roots and keys are those of {@link IOSSettings} and {@link AndroidSettings}.
1112
+ *
1113
+ * It reads the WebView as it is when the call arrives: a navigation doesn't reject it. Rejects with a
1114
+ * {@link CodedError}: `not_found`, `unavailable` (Android) or `native_error`.
1115
+ * @example
1116
+ * ```ts
1117
+ * const bounces = await ref.current?.get('scrollView.bounces'); // iOS
1118
+ * const textZoom = await ref.current?.get('settings.textZoom'); // Android
1119
+ * ```
1120
+ */
1121
+ get(key: string): Promise<unknown>;
1122
+ /**
1123
+ * Calls a platform method, `root.method`, and resolves with its result through JSON. It acts on the WebView as it is
1124
+ * when the call arrives: a navigation doesn't reject it.
1125
+ *
1126
+ * The roots are those of {@link IOSSettings} and {@link AndroidSettings}. On Android `method` is a public method of
1127
+ * the root's object; on iOS an Objective-C selector.
1128
+ *
1129
+ * Rejects with a {@link CodedError}: `not_found`, `unavailable` (Android) or `native_error`.
1130
+ *
1131
+ * The core owns, and so rejects:
1132
+ *
1133
+ * - iOS: every selector that loads, navigates (`setInteractionState:` too), runs a script, starts a download or sets
1134
+ * a delegate, and private (`_`), KVC, `willChange…`, `didChange…`, `performSelector`, `init…`, `copy…`,
1135
+ * `mutable…`, `new…` and reference-counting selectors.
1136
+ * - Android: the loads, navigations, clients, JavaScript interfaces, web message listeners,
1137
+ * document-start scripts, the touch, scroll-change and navigation listeners, `destroy`, `removeAllViews`,
1138
+ * `pauseTimers`, `resumeTimers`, `evaluateJavascript` and remote debugging
1139
+ * ({@link AndroidWebView.setWebContentsDebuggingEnabled}).
1140
+ *
1141
+ * A trailing completion handler (iOS) or `ValueCallback` (Android) is left out of `args`: the call resolves with what
1142
+ * it reports, or on iOS rejects with its error. On iOS, a selector whose completion handler isn't in this package's
1143
+ * SDK headers, or reports something other than an object, an error or an integer, rejects with `native_error`. On
1144
+ * Android, a method that takes `args` as they are wins over one that also takes a callback, and a `null` in the
1145
+ * callback's place passes none.
1146
+ *
1147
+ * One mistake the signature can't catch crashes the app: on iOS an object argument of the wrong class, and on Android
1148
+ * a `null` listener or callback other than the trailing `ValueCallback`, once WebView calls it. For a method that
1149
+ * takes another object, write a native hook.
1150
+ *
1151
+ * @param args The method's arguments: booleans, numbers, strings and `null`. On iOS also the structs as objects, and
1152
+ * `{ set: [...] }`, `{ date: seconds }`, `{ data: base64 }` or `{ cookie: properties }` for an `NSSet`, `NSDate`,
1153
+ * `NSData` or `NSHTTPCookie`; any other string stays an `NSString`. A cookie's properties are `NSHTTPCookie`'s keys:
1154
+ * `Name`, `Value`, `Domain` and `Path` are required; `Max-Age` (seconds, as a string), `Secure`, `HttpOnly` and
1155
+ * `SameSite` are some of the optional ones. A tag that can't make its object (`{ data }` that isn't base64, a
1156
+ * `{ cookie }` without a required key) rejects with `native_error`.
1157
+ * @returns The result: primitives, strings, and collections of them; on iOS also the structs as objects, an `NSURL`
1158
+ * as a string, an `NSDate` as seconds, `NSData` as base64, a `UIImage` as a base64 PNG and an `NSHTTPCookie` as its
1159
+ * properties (`Expires` in seconds). Any other object is `null`.
1160
+ * @example
1161
+ * ```ts
1162
+ * await ref.current?.call('webView.clearCache', [true]); // Android
1163
+ * await ref.current?.call('scrollView.setContentOffset:animated:', [{ x: 0, y: 100 }, true]); // iOS
1164
+ * ```
1165
+ */
1166
+ call(method: string, args?: unknown[]): Promise<unknown>;
1167
+ /**
1168
+ * Calls the `method` handler the native hook `name` registered with `context.handle`, with `args`, and resolves with
1169
+ * its reply; both cross as JSON.
1170
+ *
1171
+ * The reply converts as {@link WebViewRef.call | call}'s results do. Rejects with a {@link CodedError}:
1172
+ * `not_found`, `unavailable` (Android), `handler_error` when the handler fails the call (`reply.fail(message)`, or a
1173
+ * throw on Android), or `native_error` for a reply JSON can't encode. A navigation or a crash doesn't settle a call
1174
+ * whose handler hasn't replied; only an unmount does.
1175
+ */
1176
+ hook(name: string, method: string, args?: unknown[]): Promise<unknown>;
1177
+ };
1178
+
1179
+ /**
1180
+ * What `createWebViewRef()` returns: a ref that outlives the WebViews mounted with it.
1181
+ * @group WebView
1182
+ */
1183
+ export type WebViewRefObject = {
1184
+ /** The mounted WebView's ref, or null while none is mounted. */
1185
+ readonly current: WebViewRef | null;
1186
+ /** The mounted WebView's navigation state, read synchronously. */
1187
+ getState(): NavigationState;
1188
+ /**
1189
+ * Calls `listener` on every state change, including a WebView mounting or unmounting, and returns the unsubscribe.
1190
+ *
1191
+ * A subscriber stays across remounts.
1192
+ */
1193
+ subscribe(listener: () => void): () => void;
1194
+ };