react-native-minimal-webview 1.2.0 → 1.3.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 (98) hide show
  1. package/README.md +35 -31
  2. package/android/build.gradle +1 -1
  3. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +83 -125
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +18 -19
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
  10. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  11. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +41 -37
  12. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  16. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  17. package/build/WebView.d.ts +11 -2
  18. package/build/WebView.d.ts.map +1 -1
  19. package/build/WebView.js +45 -71
  20. package/build/WebView.js.map +1 -1
  21. package/build/bridge/createBridge.d.ts +1 -5
  22. package/build/bridge/createBridge.d.ts.map +1 -1
  23. package/build/bridge/createBridge.js +3 -15
  24. package/build/bridge/createBridge.js.map +1 -1
  25. package/build/bridge/endpoint.d.ts +1 -2
  26. package/build/bridge/endpoint.d.ts.map +1 -1
  27. package/build/bridge/endpoint.js +5 -6
  28. package/build/bridge/endpoint.js.map +1 -1
  29. package/build/bridge/matchesOrigin.d.ts +11 -0
  30. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  31. package/build/bridge/matchesOrigin.js +26 -0
  32. package/build/bridge/matchesOrigin.js.map +1 -0
  33. package/build/bridge/origins.d.ts +2 -13
  34. package/build/bridge/origins.d.ts.map +1 -1
  35. package/build/bridge/origins.js +1 -30
  36. package/build/bridge/origins.js.map +1 -1
  37. package/build/bridge/pageClient.generated.d.ts +1 -1
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  39. package/build/bridge/pageClient.generated.js +2 -2
  40. package/build/bridge/pageClient.generated.js.map +1 -1
  41. package/build/bridge/protocol.d.ts +3 -5
  42. package/build/bridge/protocol.d.ts.map +1 -1
  43. package/build/bridge/protocol.js +12 -14
  44. package/build/bridge/protocol.js.map +1 -1
  45. package/build/index.d.ts +1 -1
  46. package/build/index.js +1 -1
  47. package/build/navigationRules.d.ts +0 -5
  48. package/build/navigationRules.d.ts.map +1 -1
  49. package/build/navigationRules.js +3 -12
  50. package/build/navigationRules.js.map +1 -1
  51. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  52. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  53. package/build/reactNativeWebViewDefaults.js +0 -4
  54. package/build/reactNativeWebViewDefaults.js.map +1 -1
  55. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  56. package/build/reactNativeWebViewMessages.js +0 -1
  57. package/build/reactNativeWebViewMessages.js.map +1 -1
  58. package/build/refStore.d.ts +0 -2
  59. package/build/refStore.d.ts.map +1 -1
  60. package/build/refStore.js +0 -6
  61. package/build/refStore.js.map +1 -1
  62. package/build/types.d.ts +55 -39
  63. package/build/types.d.ts.map +1 -1
  64. package/ios/Asks.swift +6 -9
  65. package/ios/DelegateProxy.swift +4 -18
  66. package/ios/DownloadName.swift +0 -2
  67. package/ios/Downloads.swift +0 -2
  68. package/ios/Hooks.swift +4 -6
  69. package/ios/Loads.swift +37 -19
  70. package/ios/MinimalWebView+Dialogs.swift +5 -7
  71. package/ios/MinimalWebView+Navigation.swift +23 -49
  72. package/ios/MinimalWebView+Scripts.swift +10 -17
  73. package/ios/MinimalWebView.podspec +1 -2
  74. package/ios/MinimalWebView.swift +63 -128
  75. package/ios/MinimalWebViewModule.swift +1 -18
  76. package/ios/NavigationRules.swift +2 -9
  77. package/ios/OriginRules.swift +4 -13
  78. package/ios/PlatformSettings.swift +9 -30
  79. package/ios/ReadAccess.swift +0 -2
  80. package/ios/Records.swift +18 -0
  81. package/ios/Recovery.swift +2 -8
  82. package/ios/SharedCookies.swift +10 -25
  83. package/mocks/MinimalWebView.ts +5 -0
  84. package/package.json +11 -10
  85. package/src/WebView.tsx +58 -80
  86. package/src/bridge/createBridge.ts +5 -20
  87. package/src/bridge/endpoint.ts +6 -9
  88. package/src/bridge/matchesOrigin.ts +27 -0
  89. package/src/bridge/origins.ts +2 -30
  90. package/src/bridge/pageClient.generated.ts +2 -2
  91. package/src/bridge/pageClient.ts +1 -7
  92. package/src/bridge/protocol.ts +16 -18
  93. package/src/index.ts +1 -1
  94. package/src/navigationRules.ts +6 -12
  95. package/src/reactNativeWebViewDefaults.ts +0 -4
  96. package/src/reactNativeWebViewMessages.ts +0 -1
  97. package/src/refStore.ts +0 -7
  98. package/src/types.ts +55 -39
package/src/WebView.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { requireNativeModule, requireNativeView } from 'expo';
1
+ import { requireNativeModule, requireNativeView, requireOptionalNativeModule } from 'expo';
2
2
  import { type Ref, useEffect, useMemo, useRef, useState } from 'react';
3
3
  import { AppState, Platform, type ViewProps } from 'react-native';
4
4
 
@@ -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>;
@@ -135,11 +128,22 @@ const nativeModule = () =>
135
128
  setWebContentsDebuggingEnabled(enabled: boolean): Promise<void>;
136
129
  }>('MinimalWebView');
137
130
 
131
+ let linked = false;
132
+ // pod install leaves the pod out below the iOS floor with only a warning, which `expo run:ios` hides; without this the
133
+ // view renders as React Native's "Unimplemented component".
134
+ function assertLinked() {
135
+ linked ||= requireOptionalNativeModule('MinimalWebView') != null;
136
+ if (!linked)
137
+ throw new Error(
138
+ '[react-native-minimal-webview] this build has no MinimalWebView native module. On iOS, pod install leaves ' +
139
+ 'it out below the deployment target 17.0: set it to 17.0 or later, then rebuild. Otherwise, rebuild the app.'
140
+ );
141
+ }
142
+
138
143
  /** Android rejects a view function with this until Expo has registered the view. */
139
144
  const notRegistered = (error: unknown) =>
140
145
  (error as { code?: string } | null)?.code === 'ERR_VIEW_NOT_FOUND';
141
146
 
142
- /** A native call nothing awaits: a rejection is logged, bar one for a view not registered yet, where it does nothing. */
143
147
  const unawaited = (call: Promise<unknown> | undefined, name: string) =>
144
148
  void call?.catch((error: unknown) => {
145
149
  if (!notRegistered(error))
@@ -155,9 +159,12 @@ const isJavaScriptUrl = (url: string) => /^[\0- ]*javascript:/i.test(url.replace
155
159
  /**
156
160
  * A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
157
161
  * {@link WebViewRef}.
162
+ * @throws An `Error` as it renders when the app was built without the package's native module: on iOS, below the
163
+ * deployment target 17.0.
158
164
  * @group WebView
159
165
  */
160
166
  export function WebView(props: WebViewProps) {
167
+ assertLinked();
161
168
  useBridgeChangeWarning(props.bridge);
162
169
  return <WebViewInstance key={creationKey(props)} {...props} />;
163
170
  }
@@ -177,12 +184,9 @@ function useBridgeChangeWarning(bridge: WebViewProps['bridge']) {
177
184
  }, [bridge]);
178
185
  }
179
186
 
180
- /** One native WebView's life: a new creation key remounts it, so its state, ref attachment and bridge start over. */
181
187
  function WebViewInstance({ ref, ...props }: WebViewProps) {
182
188
  const native = useRef<NativeMethods>(null);
183
189
 
184
- // The rejecters of native calls not settled yet. An unmount rejects them: native may never answer (a hook handler
185
- // that never replies), and a late answer then settles nothing.
186
190
  const [inFlight] = useState(() => new Set<(error: Error) => void>());
187
191
  useEffect(
188
192
  () => () => {
@@ -197,8 +201,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
197
201
  const gone = (): never => {
198
202
  throw codedError({ code: 'unavailable', message: 'the WebView is gone' });
199
203
  };
200
- const settled = (promise: Promise<string>) =>
201
- new Promise<string>((resolve, reject) => {
204
+ const settled = <T,>(promise: Promise<T>) =>
205
+ new Promise<T>((resolve, reject) => {
202
206
  inFlight.add(reject);
203
207
  promise.then(
204
208
  (value) => {
@@ -211,11 +215,10 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
211
215
  }
212
216
  );
213
217
  });
214
- // Retries each frame until Expo has registered the view.
215
- const mounted = async (call: () => Promise<string> | undefined) => {
218
+ const retriedUntilViewRegistered = async <T,>(call: () => Promise<T> | undefined) => {
216
219
  for (let frame = 0; ; frame++) {
217
220
  try {
218
- return JSON.parse(await settled(call() ?? gone())) as unknown;
221
+ return await settled(call() ?? gone());
219
222
  } catch (error) {
220
223
  if (!notRegistered(error)) throw error;
221
224
  if (frame === 60 || AppState.currentState === 'background') gone();
@@ -223,6 +226,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
223
226
  }
224
227
  }
225
228
  };
229
+ const jsonResultOf = async (call: () => Promise<string> | undefined) =>
230
+ JSON.parse(await retriedUntilViewRegistered(call)) as unknown;
226
231
  return {
227
232
  goBack: () => unawaited(native.current?.goBack(), 'goBack'),
228
233
  goForward: () => unawaited(native.current?.goForward(), 'goForward'),
@@ -234,10 +239,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
234
239
  );
235
240
  return;
236
241
  }
237
- // mounted() parses a JSON result, and load has none. A view that went away or never came loads nothing, as
238
- // a navigation method does after an unmount.
239
242
  unawaited(
240
- mounted(() => native.current?.load(url).then(() => 'null')).catch((error: unknown) => {
243
+ retriedUntilViewRegistered(() => native.current?.load(url)).catch((error: unknown) => {
241
244
  const code = (error as { code?: string } | null)?.code;
242
245
  if (code !== 'unavailable' && code !== 'navigated') throw error;
243
246
  }),
@@ -246,12 +249,12 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
246
249
  },
247
250
  reload: () => unawaited(native.current?.reload(), 'reload'),
248
251
  stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
249
- evaluate: (script) => mounted(() => native.current?.evaluate(script)),
250
- get: (key) => mounted(() => native.current?.get(key)),
252
+ evaluate: (script) => jsonResultOf(() => native.current?.evaluate(script)),
253
+ get: (key) => jsonResultOf(() => native.current?.get(key)),
251
254
  call: (method, args = []) =>
252
- mounted(() => native.current?.call(method, JSON.stringify(args))),
255
+ jsonResultOf(() => native.current?.call(method, JSON.stringify(args))),
253
256
  hook: (name, method, args = []) =>
254
- mounted(() => native.current?.hook(name, method, JSON.stringify(args))),
257
+ jsonResultOf(() => native.current?.hook(name, method, JSON.stringify(args))),
255
258
  };
256
259
  });
257
260
  const publish = useAttach(ref, handle);
@@ -264,7 +267,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
264
267
  if (was.loading && !state.loading) props.onLoadEnd?.(state);
265
268
  };
266
269
 
267
- // The same string while nothing in it changed, so a re-render sends native nothing.
268
270
  const settings = JSON.stringify(platformSettings(props));
269
271
  const injectedScripts = useMemo(
270
272
  () => nativeScripts(props.injectedScripts),
@@ -281,7 +283,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
281
283
  const hookOptions = useHookOptions(props.extensions);
282
284
  const navigationRules = useNavigationRules(props.navigationRules);
283
285
 
284
- // One per ask in flight, by id: aborted when native stops waiting (the core's `askCancelled`) or at unmount.
285
286
  const [asks] = useState(() => new Map<number, AbortController>());
286
287
  useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
287
288
 
@@ -289,33 +290,36 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
289
290
  nativeEvent: { key, name, payload, askId },
290
291
  }: Native<AskableEvent>) => {
291
292
  const core = key === 'core';
292
- // The core's own events: a warning for the developer, and an ask native stopped waiting for.
293
293
  if (core && name === 'warning')
294
- return console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
295
- if (core && name === 'askCancelled') return asks.get(payload['askId'] as number)?.abort();
296
- const request = REQUESTS.find((prop) => core && prop === name);
297
- // The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
294
+ return console.warn(
295
+ `[react-native-minimal-webview] ${(payload as CoreEventPayloads['warning']).message}`
296
+ );
297
+ if (core && name === 'askCancelled')
298
+ return asks.get((payload as CoreEventPayloads['askCancelled']).askId)?.abort();
299
+ const request = REQUEST_HANDLER_PROPS.find((prop) => core && prop === name);
298
300
  const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
299
301
  const handler = request
300
302
  ? (props[request] as ((payload: unknown, signal?: AbortSignal) => unknown) | undefined)
301
- : (_: unknown, signal?: AbortSignal) => owner?.onEvent?.({ name, payload }, signal);
302
- // Only an ask can be cancelled, so only an ask gets a signal.
303
+ : (_: unknown, signal?: AbortSignal) =>
304
+ signal && owner?.onAsk
305
+ ? owner.onAsk({ name, payload }, signal)
306
+ : owner?.onEvent?.({ name, payload }, signal);
303
307
  let controller: AbortController | undefined;
304
308
  if (askId !== undefined) {
305
309
  controller = new AbortController();
306
310
  asks.set(askId, controller);
307
311
  }
308
- const failure = request ? `${request} failed` : `onEvent failed for ${key}.${name}`;
312
+ const failure = request
313
+ ? `${request} failed`
314
+ : `${hookHandlerName(owner, askId)} failed for ${key}.${name}`;
309
315
  let value: unknown = null;
310
316
  try {
311
317
  value = await handler?.(payload, controller?.signal);
312
318
  } catch (error) {
313
- // Native waits on this handler: one that throws still answers, with null (native's safe default).
314
319
  console.error(`[react-native-minimal-webview] ${failure}`, error);
315
320
  }
316
321
  if (askId === undefined) return;
317
322
  asks.delete(askId);
318
- // Native already answered a cancelled ask with null; a late answer would find nothing.
319
323
  if (!controller?.signal.aborted) await native.current?.answer(askId, answerJson(value));
320
324
  };
321
325
 
@@ -343,7 +347,9 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
343
347
  );
344
348
  }
345
349
 
346
- /** An ask's answer for native: null for one JSON can't encode (a function, a cycle, a BigInt), so the ask settles. */
350
+ const hookHandlerName = (owner: HookExtension | undefined, askId: number | undefined) =>
351
+ askId !== undefined && owner?.onAsk ? 'onAsk' : 'onEvent';
352
+
347
353
  function answerJson(value: unknown) {
348
354
  try {
349
355
  return JSON.stringify(value) ?? 'null';
@@ -352,10 +358,6 @@ function answerJson(value: unknown) {
352
358
  }
353
359
  }
354
360
 
355
- /**
356
- * The scripts as native runs them: one whose `origins` lack `*` runs inside a function, so that even its function
357
- * declarations take effect only where the guard lets it run.
358
- */
359
361
  function nativeScripts(scripts: InjectedScript[] | undefined) {
360
362
  return scripts?.map(({ code, allFrames, origins }) => {
361
363
  if (!Array.isArray(origins))
@@ -365,10 +367,6 @@ function nativeScripts(scripts: InjectedScript[] | undefined) {
365
367
  });
366
368
  }
367
369
 
368
- /**
369
- * The rules as the core gets them (`checkNavigationRules`), and a development warning for each malformed one. The same
370
- * array when none is malformed.
371
- */
372
370
  function useNavigationRules(rules: WebViewProps['navigationRules']) {
373
371
  const { checked, warnings } = useMemo(
374
372
  () => checkNavigationRules(rules ?? defaultNavigationRules),
@@ -378,7 +376,6 @@ function useNavigationRules(rules: WebViewProps['navigationRules']) {
378
376
  return checked;
379
377
  }
380
378
 
381
- /** Logs each warning in development, again only when the list changes. */
382
379
  function useDevWarnings(warnings: string[]) {
383
380
  const json = JSON.stringify(warnings);
384
381
  useEffect(() => {
@@ -388,17 +385,11 @@ function useDevWarnings(warnings: string[]) {
388
385
  }, [json]);
389
386
  }
390
387
 
391
- /** The `REQUESTS` with a prop set, as a new array only when that set changes. */
392
388
  function useRequestHandlers(props: WebViewProps) {
393
- const key = REQUESTS.filter((prop) => props[prop]).join();
389
+ const key = REQUEST_HANDLER_PROPS.filter((prop) => props[prop]).join();
394
390
  return useMemo(() => (key ? key.split(',') : []), [key]);
395
391
  }
396
392
 
397
- /**
398
- * The core's `hookOptions`: each extension's `options` by its key, the later of two extensions with one key winning (a
399
- * development warning). The same object while the JSON is the same, so a render with new handlers sends the core
400
- * nothing.
401
- */
402
393
  function useHookOptions(extensions: WebViewProps['extensions']) {
403
394
  const on = (extensions ?? []).filter((extension) => !!extension);
404
395
  const keys = on.map(({ key }) => key);
@@ -408,24 +399,14 @@ function useHookOptions(extensions: WebViewProps['extensions']) {
408
399
  )
409
400
  );
410
401
  const json = JSON.stringify(
411
- withoutOff(
412
- Object.fromEntries(
413
- // An unset `options` is `true` (HookExtension.options).
414
- on.map(({ key, options = true }) => [key, options])
415
- )
416
- )
402
+ withoutOff(Object.fromEntries(on.map(({ key, options = true }) => [key, options])))
417
403
  );
418
404
  return useMemo(() => JSON.parse(json) as Record<string, unknown>, [json]);
419
405
  }
420
406
 
421
- /** Bridges by identity, for the creation key. */
422
407
  const bridgeIds = new WeakMap<object, number>();
423
408
  let lastBridgeId = 0;
424
409
 
425
- /**
426
- * What native sets up once, at creation (the bridge, `ios.configuration`). As WebViewInstance's `key`, a change
427
- * remounts it.
428
- */
429
410
  function creationKey(props: WebViewProps) {
430
411
  const bridge = props.bridge;
431
412
  let id = bridge && bridgeIds.get(bridge);
@@ -436,13 +417,11 @@ function creationKey(props: WebViewProps) {
436
417
  );
437
418
  }
438
419
 
439
- /** A null or false value is off, and its key is left out: native treats a present key as on. */
440
420
  const withoutOff = (options: Record<string, unknown>) =>
441
421
  Object.fromEntries(
442
422
  Object.entries(options).filter(([, value]) => value != null && value !== false)
443
423
  );
444
424
 
445
- /** A JSON.stringify replacer: the same options in another key order are the same key. */
446
425
  const sortedKeys = (_: string, value: unknown) =>
447
426
  value && typeof value === 'object' && !Array.isArray(value)
448
427
  ? Object.fromEntries(Object.entries(value).sort())
@@ -452,7 +431,6 @@ function viewPropsOf(props: WebViewProps): ViewProps {
452
431
  return Object.fromEntries(Object.entries(props).filter(([key]) => !OWN_SET.has(key)));
453
432
  }
454
433
 
455
- /** Each root's keys with its `other` ones among them, as native takes them; a generated key wins. */
456
434
  const flattened = (
457
435
  roots: Record<string, { other?: NativeSettings[string] } | undefined> = {}
458
436
  ): NativeSettings =>
@@ -460,18 +438,12 @@ const flattened = (
460
438
  Object.entries(roots).map(([name, { other, ...keys } = {}]) => [name, { ...other, ...keys }])
461
439
  );
462
440
 
463
- /** Each layer's roots over the earlier layers', key by key. */
464
441
  const layered = (...layers: NativeSettings[]) =>
465
442
  layers.reduce<NativeSettings>((out, layer) => {
466
443
  for (const [root, keys] of Object.entries(layer)) out[root] = { ...out[root], ...keys };
467
444
  return out;
468
445
  }, {});
469
446
 
470
- /**
471
- * The platform's settings for native: the package's defaults, react-native-webview's over them, the app's `ios` or
472
- * `android` roots over those, and `userAgent` on top. Native restores the key of a removed `userAgent`. Android's
473
- * own defaults are written natively.
474
- */
475
447
  function platformSettings(props: WebViewProps): NativeSettings {
476
448
  const [defaults, rnw, app, userAgent] =
477
449
  Platform.OS === 'ios'
@@ -502,11 +474,17 @@ export const AndroidWebView = {
502
474
  * Android's default user agent, for `android.settings.userAgentString` with a suffix.
503
475
  *
504
476
  * The first read loads WebView's code, on the JS thread: read it once `warmUp()` has had time or a WebView is
505
- * mounted.
477
+ * mounted. It is null while Android System WebView is missing, disabled or updating, and a later read tries again.
506
478
  * @android
507
479
  */
508
480
  get defaultUserAgent(): string | null {
509
- return Platform.OS === 'android' ? nativeModule().defaultUserAgent : null;
481
+ if (Platform.OS !== 'android') return null;
482
+ try {
483
+ return nativeModule().defaultUserAgent;
484
+ } catch {
485
+ // Caught here, not natively: Expo caches a value the native getter returns, a null too, but not a throw.
486
+ return null;
487
+ }
510
488
  },
511
489
  /**
512
490
  * Starts WebView before any WebView mounts, so the first WebView mounts sooner.
@@ -7,9 +7,7 @@ import { type BridgeMessage, parseBridgeMessage } from './protocol';
7
7
 
8
8
  /**
9
9
  * What native reports to the bridge: a page's message with its origin as native verified it (`location.origin` form);
10
- * a new document committed, so messages queue until its page client says `ready`; the renderer crashed, so no document
11
- * is shown until the next commit; or the platform lacks the WebView features the bridge needs, so calls reject with
12
- * `unavailable`.
10
+ * a new document committed; the renderer crashed; or the platform lacks the WebView features the bridge needs.
13
11
  */
14
12
  export type BridgeEvent =
15
13
  | { message: string; origin: string }
@@ -17,10 +15,8 @@ export type BridgeEvent =
17
15
  | { crashed: true }
18
16
  | { unavailable: true };
19
17
 
20
- /** What `<WebView>` needs from a bridge: `Bridge`'s `[CONNECTION]`, a key the package doesn't export. */
21
18
  export type BridgeConnection = {
22
19
  allowedOrigins: string[];
23
- /** The page client to inject at document start. */
24
20
  script: string;
25
21
  attach(post: (message: string) => void): void;
26
22
  detach(): void;
@@ -31,6 +27,8 @@ export const CONNECTION = Symbol('bridgeConnection');
31
27
 
32
28
  const MAX_QUEUE = 1000;
33
29
 
30
+ const throwIfNotJson = (message: BridgeMessage) => void JSON.stringify(message);
31
+
34
32
  /**
35
33
  * Creates a {@link Bridge} to the pages of `allowedOrigins`, for one WebView's `bridge` prop.
36
34
  *
@@ -52,11 +50,8 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
52
50
  );
53
51
  }
54
52
  let post: ((message: string) => void) | null = null;
55
- // idle: no document shown (none committed since attach, or it crashed). loading: one committed and hasn't said `ready` yet.
56
53
  let phase: 'idle' | 'loading' | 'ready' = 'idle';
57
- // The token of the document that last said `ready` (protocol.ts `doc`).
58
54
  let doc: string | undefined;
59
- // Messages for the next document that says `ready`. Only the latest document's: see `receive`.
60
55
  let queue: BridgeMessage[] = [];
61
56
  let unavailable = false;
62
57
 
@@ -66,8 +61,7 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
66
61
  (message) => {
67
62
  if (post && phase === 'ready') deliver(message);
68
63
  else {
69
- // Throws now, at the caller, for what JSON can't encode, rather than in the flush, losing the rest of the queue.
70
- JSON.stringify(message);
64
+ throwIfNotJson(message);
71
65
  queue.push(message);
72
66
  const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
73
67
  if (dropped?.kind === 'call')
@@ -82,7 +76,6 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
82
76
  'n'
83
77
  );
84
78
 
85
- // A pending call not in the queue was posted to a document.
86
79
  const rejectSent = (message: string) => {
87
80
  const queued = new Set(
88
81
  queue.map((queuedMessage) => queuedMessage.kind === 'call' && queuedMessage.id)
@@ -100,20 +93,16 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
100
93
  return;
101
94
  }
102
95
  if (message.kind !== 'ready') {
103
- // Answers skip the ready queue: a module script may await one before DOMContentLoaded, and native can deliver
104
- // it, as the page has posted.
105
96
  const reply = (answer: BridgeMessage) =>
106
97
  post?.(JSON.stringify({ ...answer, doc: message.doc }));
107
98
  void endpoint.receive(message, reply, { origin });
108
99
  return;
109
100
  }
110
- // A new document: calls posted to the previous one can no longer be answered. Queued ones are for this one.
111
101
  rejectSent('the page navigated');
112
102
  phase = 'ready';
113
103
  doc = message.doc;
114
104
  const flushing = queue;
115
105
  queue = [];
116
- // A queued call that already timed out is not sent: nobody waits for its answer.
117
106
  for (const queued of flushing)
118
107
  if (queued.kind !== 'call' || endpoint.pending.has(queued.id)) deliver(queued);
119
108
  };
@@ -122,7 +111,6 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
122
111
  allowedOrigins: options.allowedOrigins,
123
112
  script: `${guard ? `if (${guard}) ` : ''}(${PAGE_CLIENT})(window, ${Number(timeoutMs)});`,
124
113
  attach(next) {
125
- // Two WebViews would steal each other's replies, and either one's detach would cut off the other.
126
114
  if (post)
127
115
  throw new Error(
128
116
  'createBridge: this bridge is already attached to a mounted WebView; give each WebView its own bridge'
@@ -144,13 +132,10 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
144
132
  endpoint.rejectPending('unavailable', unavailableMessage);
145
133
  } else {
146
134
  rejectSent('the page navigated');
147
- // The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
148
- // carry over to an unrelated next one.
149
135
  if (phase === 'loading') {
150
136
  endpoint.rejectPending('unavailable', 'the page navigated before the bridge was ready');
151
137
  queue = [];
152
138
  }
153
- // What is queued after a crash is for the reload.
154
139
  phase = 'crashed' in event ? 'idle' : 'loading';
155
140
  }
156
141
  },
@@ -166,5 +151,5 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
166
151
  emit: endpoint.emit,
167
152
  on: endpoint.on,
168
153
  [CONNECTION]: connection,
169
- } as Bridge as unknown as Bridge<Schema>; // the schema types only what callers pass
154
+ } satisfies Bridge as Bridge<Schema>;
170
155
  }
@@ -1,6 +1,3 @@
1
- // One side of the bridge, the same in RN (createBridge.ts) and in the page (pageClient.ts): calls with timeouts,
2
- // handlers and events. The transport, the `ready` handshake and the document tokens are each side's own. The page
3
- // client is compiled with this file into one script (.github/scripts/build-page-client.mts).
4
1
  import type { CodedError, ErrorCode } from '../types';
5
2
  import type { BridgeErrorCode, BridgeMessage } from './protocol';
6
3
 
@@ -13,9 +10,10 @@ type Pending = {
13
10
  export const codedError = ({ code, message }: { code: ErrorCode; message: string }): CodedError =>
14
11
  Object.assign(new Error(message), { code });
15
12
 
13
+ const reportUnhandled = (error: unknown) => void Promise.reject(error);
14
+
16
15
  /**
17
- * `send` posts a message to the other side; ids get `idPrefix`, so the two sides' calls never share an id. `Sender` is
18
- * what handlers and listeners get beside the params: RN's `{ origin }`, nothing in the page.
16
+ * `send` posts a message to the other side; ids get `idPrefix`, so the two sides' calls never share an id.
19
17
  */
20
18
  export function createEndpoint<Sender = void>(
21
19
  send: (message: BridgeMessage) => void,
@@ -59,7 +57,7 @@ export function createEndpoint<Sender = void>(
59
57
  });
60
58
  },
61
59
  emit(event: string, payload?: unknown) {
62
- send({ kind: 'event', method: event, params: payload });
60
+ send({ kind: 'event', event, params: payload });
63
61
  },
64
62
  handle(method: string, handler: (params: unknown, sender: Sender) => unknown) {
65
63
  handlers.set(method, handler);
@@ -96,12 +94,11 @@ export function createEndpoint<Sender = void>(
96
94
  return;
97
95
  }
98
96
  case 'event':
99
- listeners.get(message.method)?.forEach((listener) => {
100
- // An unhandled rejection reports the error without stopping the other listeners.
97
+ listeners.get(message.event)?.forEach((listener) => {
101
98
  try {
102
99
  listener(message.params, sender);
103
100
  } catch (error) {
104
- void Promise.reject(error);
101
+ reportUnhandled(error);
105
102
  }
106
103
  });
107
104
  return;
@@ -0,0 +1,27 @@
1
+ export type OriginForms = {
2
+ any: boolean;
3
+ exact: string[];
4
+ wild: [prefix: string, suffix: string][];
5
+ };
6
+
7
+ function hasAt(text: string, part: string, at: number) {
8
+ for (let k = 0; k < part.length; k++) if (text[at + k] !== part[k]) return false;
9
+ return true;
10
+ }
11
+
12
+ /**
13
+ * Whether `origin`, as `location.origin` serializes it, matches `forms`. Only `===`, indexing and `length`, no
14
+ * built-in method: it runs at document start in frames whose built-ins another same-origin frame may have patched.
15
+ */
16
+ export function matchesOrigin(forms: OriginForms, origin: string) {
17
+ if (forms.any) return true;
18
+ for (let i = 0; i < forms.exact.length; i++) if (forms.exact[i] === origin) return true;
19
+ for (let i = 0; i < forms.wild.length; i++) {
20
+ const prefix = forms.wild[i]![0];
21
+ const suffix = forms.wild[i]![1];
22
+ const start = origin.length - suffix.length;
23
+ if (start > prefix.length && hasAt(origin, prefix, 0) && hasAt(origin, suffix, start))
24
+ return true;
25
+ }
26
+ return false;
27
+ }
@@ -1,10 +1,9 @@
1
- // The origin rules in RN: parser, the guard that createBridge and injectedScripts put around page code, and the
2
- // matcher whose text build-page-client.mts cuts out as MATCHES_ORIGIN for that guard.
1
+ import type { OriginForms } from './matchesOrigin';
3
2
  import { MATCHES_ORIGIN } from './pageClient.generated';
4
3
 
5
4
  /**
6
5
  * An origin rule (`http(s)://host[:port]`, `http(s)://*.host[:port]`) or a `location.origin`, parsed; null for anything
7
- * else, `*` included. OriginRules.swift matches the same way: both run src/__tests__/vectors/origin-rules.json.
6
+ * else, `*` included.
8
7
  */
9
8
  export const parseOrigin = (text: string) => {
10
9
  const m =
@@ -19,10 +18,6 @@ export const parseOrigin = (text: string) => {
19
18
  return { scheme, wildcard: !!wildcard, hostPort: `${host}${portSuffix}` };
20
19
  };
21
20
 
22
- /** Origin rules in `location.origin` form, for `matchesOrigin`: exact origins, and wildcards as prefix and suffix. */
23
- export type OriginForms = { any: boolean; exact: string[]; wild: [string, string][] };
24
-
25
- /** `rules` in the form `matchesOrigin` compares; a rule `parseOrigin` rejects is left out, so it matches nothing. */
26
21
  export const originForms = (rules: string[]): OriginForms => {
27
22
  const forms: OriginForms = { any: rules.includes('*'), exact: [], wild: [] };
28
23
  for (const rule of rules) {
@@ -34,29 +29,6 @@ export const originForms = (rules: string[]): OriginForms => {
34
29
  return forms;
35
30
  };
36
31
 
37
- function hasAt(text: string, part: string, at: number) {
38
- for (let k = 0; k < part.length; k++) if (text[at + k] !== part[k]) return false;
39
- return true;
40
- }
41
-
42
- /**
43
- * Whether `origin`, as `location.origin` serializes it, matches `forms`. Only `===`, indexing and `length`, no
44
- * built-in method: it runs at document start in frames whose built-ins another same-origin frame may have patched.
45
- */
46
- export function matchesOrigin(forms: OriginForms, origin: string) {
47
- if (forms.any) return true;
48
- for (let i = 0; i < forms.exact.length; i++) if (forms.exact[i] === origin) return true;
49
- for (let i = 0; i < forms.wild.length; i++) {
50
- const prefix = forms.wild[i]![0];
51
- const suffix = forms.wild[i]![1];
52
- const start = origin.length - suffix.length;
53
- // At least one character of subdomain between the two.
54
- if (start > prefix.length && hasAt(origin, prefix, 0) && hasAt(origin, suffix, start))
55
- return true;
56
- }
57
- return false;
58
- }
59
-
60
32
  /**
61
33
  * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
62
34
  * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
@@ -1,5 +1,5 @@
1
- // Generated by .github/scripts/build-page-client.mts from pageClient.ts, endpoint.ts and origins.ts. Do not edit.
1
+ // Generated by .github/scripts/build-page-client.mts from pageClient.ts, endpoint.ts and matchesOrigin.ts. Do not edit.
2
2
  export const PAGE_CLIENT =
3
- "function (w, timeoutMs) {\nconst codedError = ({ code, message }) => Object.assign(new Error(message), { code });\nfunction createEndpoint(send, timeoutMs, idPrefix) {\n const handlers = new Map();\n const listeners = new Map();\n const pending = new Map();\n let nextId = 0;\n return {\n pending,\n call(method, params, options) {\n const ms = options?.timeoutMs ?? timeoutMs;\n if (!(ms >= 0))\n return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));\n const id = `${idPrefix}${++nextId}`;\n return new Promise((resolve, reject) => {\n const timer = ms > 0 && ms < Infinity\n ? setTimeout(() => {\n pending.delete(id);\n reject(codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` }));\n }, Math.min(ms, 2 ** 31 - 1))\n : undefined;\n pending.set(id, { resolve, reject, timer });\n try {\n send({ id, kind: 'call', method, params });\n }\n catch (error) {\n clearTimeout(timer);\n pending.delete(id);\n throw error;\n }\n });\n },\n emit(event, payload) {\n send({ kind: 'event', method: event, params: payload });\n },\n handle(method, handler) {\n handlers.set(method, handler);\n return () => {\n if (handlers.get(method) === handler)\n handlers.delete(method);\n };\n },\n on(event, listener) {\n const set = listeners.get(event) ?? new Set();\n listeners.set(event, set.add(listener));\n return () => set.delete(listener);\n },\n rejectPending(code, message, only) {\n for (const [id, call] of pending) {\n if (only && !only(id))\n continue;\n clearTimeout(call.timer);\n call.reject(codedError({ code, message }));\n pending.delete(id);\n }\n },\n async receive(message, reply, sender) {\n switch (message.kind) {\n case 'call': {\n const { id, method } = message;\n const fail = (code, text) => reply({ id, kind: 'error', error: { code, message: text } });\n const handler = handlers.get(method);\n if (!handler)\n return fail('not_found', `no handler for ${method}`);\n try {\n reply({ id, kind: 'result', value: await handler(message.params, sender) });\n }\n catch (error) {\n fail('handler_error', error instanceof Error ? error.message : String(error));\n }\n return;\n }\n case 'event':\n listeners.get(message.method)?.forEach((listener) => {\n try {\n listener(message.params, sender);\n }\n catch (error) {\n void Promise.reject(error);\n }\n });\n return;\n case 'result':\n case 'error': {\n const call = pending.get(message.id);\n if (!call)\n return;\n pending.delete(message.id);\n clearTimeout(call.timer);\n if (message.kind === 'result')\n call.resolve(message.value);\n else\n call.reject(codedError(message.error));\n }\n }\n },\n };\n}\nfunction installPageClient(w, timeoutMs) {\n if (w.nativeBridge || w !== w.top)\n return;\n const doc = Math.random().toString(36).slice(2, 10);\n const ios = w.webkit?.messageHandlers?.nativeBridge;\n const android = w.nativeBridgeTransport;\n const send = (message) => {\n const text = JSON.stringify({ ...message, doc });\n (ios ?? android)?.postMessage(text);\n };\n const endpoint = createEndpoint(send, timeoutMs, 'p');\n const receive = async (text) => {\n const message = JSON.parse(text);\n if (message.doc === doc)\n await endpoint.receive(message, send);\n };\n if (android)\n android.onmessage = (event) => void receive(event.data);\n w.nativeBridge = Object.freeze({\n call: endpoint.call,\n emit: endpoint.emit,\n handle: endpoint.handle,\n on: endpoint.on,\n __receive: receive,\n });\n if (w.document.readyState === 'loading') {\n w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {\n once: true,\n });\n }\n else {\n send({ kind: 'ready' });\n }\n w.addEventListener('pageshow', (event) => {\n if (!event.persisted)\n return;\n endpoint.rejectPending('navigated', 'the page was left before the call was answered');\n send({ kind: 'ready' });\n });\n}\nreturn installPageClient(w, timeoutMs);\n}";
3
+ "function (w, timeoutMs) {\nconst codedError = ({ code, message }) => Object.assign(new Error(message), { code });\nconst reportUnhandled = (error) => void Promise.reject(error);\nfunction createEndpoint(send, timeoutMs, idPrefix) {\n const handlers = new Map();\n const listeners = new Map();\n const pending = new Map();\n let nextId = 0;\n return {\n pending,\n call(method, params, options) {\n const ms = options?.timeoutMs ?? timeoutMs;\n if (!(ms >= 0))\n return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));\n const id = `${idPrefix}${++nextId}`;\n return new Promise((resolve, reject) => {\n const timer = ms > 0 && ms < Infinity\n ? setTimeout(() => {\n pending.delete(id);\n reject(codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` }));\n }, Math.min(ms, 2 ** 31 - 1))\n : undefined;\n pending.set(id, { resolve, reject, timer });\n try {\n send({ id, kind: 'call', method, params });\n }\n catch (error) {\n clearTimeout(timer);\n pending.delete(id);\n throw error;\n }\n });\n },\n emit(event, payload) {\n send({ kind: 'event', event, params: payload });\n },\n handle(method, handler) {\n handlers.set(method, handler);\n return () => {\n if (handlers.get(method) === handler)\n handlers.delete(method);\n };\n },\n on(event, listener) {\n const set = listeners.get(event) ?? new Set();\n listeners.set(event, set.add(listener));\n return () => set.delete(listener);\n },\n rejectPending(code, message, only) {\n for (const [id, call] of pending) {\n if (only && !only(id))\n continue;\n clearTimeout(call.timer);\n call.reject(codedError({ code, message }));\n pending.delete(id);\n }\n },\n async receive(message, reply, sender) {\n switch (message.kind) {\n case 'call': {\n const { id, method } = message;\n const fail = (code, text) => reply({ id, kind: 'error', error: { code, message: text } });\n const handler = handlers.get(method);\n if (!handler)\n return fail('not_found', `no handler for ${method}`);\n try {\n reply({ id, kind: 'result', value: await handler(message.params, sender) });\n }\n catch (error) {\n fail('handler_error', error instanceof Error ? error.message : String(error));\n }\n return;\n }\n case 'event':\n listeners.get(message.event)?.forEach((listener) => {\n try {\n listener(message.params, sender);\n }\n catch (error) {\n reportUnhandled(error);\n }\n });\n return;\n case 'result':\n case 'error': {\n const call = pending.get(message.id);\n if (!call)\n return;\n pending.delete(message.id);\n clearTimeout(call.timer);\n if (message.kind === 'result')\n call.resolve(message.value);\n else\n call.reject(codedError(message.error));\n }\n }\n },\n };\n}\nfunction installPageClient(w, timeoutMs) {\n if (w.nativeBridge || w !== w.top)\n return;\n const doc = Math.random().toString(36).slice(2, 10);\n const ios = w.webkit?.messageHandlers?.nativeBridge;\n const android = w.nativeBridgeTransport;\n const send = (message) => {\n const text = JSON.stringify({ ...message, doc });\n (ios ?? android)?.postMessage(text);\n };\n const endpoint = createEndpoint(send, timeoutMs, 'p');\n const receive = async (text) => {\n const message = JSON.parse(text);\n if (message.doc === doc)\n await endpoint.receive(message, send);\n };\n if (android)\n android.onmessage = (event) => void receive(event.data);\n w.nativeBridge = Object.freeze({\n call: endpoint.call,\n emit: endpoint.emit,\n handle: endpoint.handle,\n on: endpoint.on,\n __receive: receive,\n });\n if (w.document.readyState === 'loading') {\n w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {\n once: true,\n });\n }\n else {\n send({ kind: 'ready' });\n }\n w.addEventListener('pageshow', (event) => {\n if (!event.persisted)\n return;\n endpoint.rejectPending('navigated', 'the page was left before the call was answered');\n send({ kind: 'ready' });\n });\n}\nreturn installPageClient(w, timeoutMs);\n}";
4
4
  export const MATCHES_ORIGIN =
5
5
  "(() => {\nfunction hasAt(text, part, at) {\n for (let k = 0; k < part.length; k++)\n if (text[at + k] !== part[k])\n return false;\n return true;\n}\nfunction matchesOrigin(forms, origin) {\n if (forms.any)\n return true;\n for (let i = 0; i < forms.exact.length; i++)\n if (forms.exact[i] === origin)\n return true;\n for (let i = 0; i < forms.wild.length; i++) {\n const prefix = forms.wild[i][0];\n const suffix = forms.wild[i][1];\n const start = origin.length - suffix.length;\n if (start > prefix.length && hasAt(origin, prefix, 0) && hasAt(origin, suffix, start))\n return true;\n }\n return false;\n}\nreturn matchesOrigin;\n})()";