react-native-minimal-webview 1.1.0 → 1.2.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 (70) hide show
  1. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +1 -6
  2. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +34 -22
  3. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -2
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +2 -1
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +3 -3
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
  7. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +29 -34
  8. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +2 -2
  9. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +7 -8
  10. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +2 -2
  11. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +4 -5
  12. package/build/WebView.d.ts +1 -9
  13. package/build/WebView.d.ts.map +1 -1
  14. package/build/WebView.js +37 -100
  15. package/build/WebView.js.map +1 -1
  16. package/build/bridge/createBridge.d.ts +17 -11
  17. package/build/bridge/createBridge.d.ts.map +1 -1
  18. package/build/bridge/createBridge.js +32 -44
  19. package/build/bridge/createBridge.js.map +1 -1
  20. package/build/bridge/endpoint.d.ts +1 -3
  21. package/build/bridge/endpoint.d.ts.map +1 -1
  22. package/build/bridge/endpoint.js +2 -2
  23. package/build/bridge/endpoint.js.map +1 -1
  24. package/build/bridge/origins.d.ts +5 -2
  25. package/build/bridge/origins.d.ts.map +1 -1
  26. package/build/bridge/origins.js +15 -4
  27. package/build/bridge/origins.js.map +1 -1
  28. package/build/bridge/pageClient.generated.d.ts +1 -1
  29. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  30. package/build/bridge/pageClient.generated.js +1 -1
  31. package/build/bridge/pageClient.generated.js.map +1 -1
  32. package/build/index.d.ts +1 -1
  33. package/build/index.d.ts.map +1 -1
  34. package/build/index.js +1 -1
  35. package/build/index.js.map +1 -1
  36. package/build/{defaultNavigationRules.d.ts → navigationRules.d.ts} +10 -1
  37. package/build/navigationRules.d.ts.map +1 -0
  38. package/build/navigationRules.js +93 -0
  39. package/build/navigationRules.js.map +1 -0
  40. package/build/refStore.d.ts.map +1 -1
  41. package/build/refStore.js +13 -17
  42. package/build/refStore.js.map +1 -1
  43. package/build/types.d.ts +39 -16
  44. package/build/types.d.ts.map +1 -1
  45. package/ios/DelegateProxy.swift +32 -30
  46. package/ios/Loads.swift +4 -4
  47. package/ios/MRWInvoke.h +8 -0
  48. package/ios/MRWInvoke.m +39 -24
  49. package/ios/MinimalWebView+Navigation.swift +17 -14
  50. package/ios/MinimalWebView.swift +72 -28
  51. package/ios/MinimalWebViewModule.swift +1 -0
  52. package/ios/NavigationRules.swift +15 -15
  53. package/ios/PlatformSettings.swift +2 -13
  54. package/ios/SharedCookies.swift +1 -2
  55. package/package.json +1 -1
  56. package/src/WebView.tsx +50 -114
  57. package/src/bridge/createBridge.ts +45 -53
  58. package/src/bridge/endpoint.ts +3 -5
  59. package/src/bridge/origins.ts +18 -6
  60. package/src/bridge/pageClient.generated.ts +1 -1
  61. package/src/index.ts +1 -1
  62. package/src/navigationRules.ts +111 -0
  63. package/src/refStore.ts +15 -19
  64. package/src/types.ts +39 -16
  65. package/build/defaultNavigationRules.d.ts.map +0 -1
  66. package/build/defaultNavigationRules.js +0 -22
  67. package/build/defaultNavigationRules.js.map +0 -1
  68. package/ios/MRWExceptions.h +0 -9
  69. package/ios/MRWExceptions.m +0 -10
  70. package/src/defaultNavigationRules.ts +0 -24
package/src/WebView.tsx CHANGED
@@ -2,9 +2,10 @@ import { requireNativeModule, requireNativeView } 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
 
5
- import { CONNECTION, originGuard } from './bridge/createBridge';
5
+ import { type BridgeEvent, CONNECTION } from './bridge/createBridge';
6
6
  import { codedError } from './bridge/endpoint';
7
- import { defaultNavigationRules } from './defaultNavigationRules';
7
+ import { originGuard } from './bridge/origins';
8
+ import { checkNavigationRules, defaultNavigationRules } from './navigationRules';
8
9
  import { REACT_NATIVE_WEBVIEW_DEFAULTS } from './reactNativeWebViewDefaults';
9
10
  import { useAttach } from './refStore';
10
11
  import type {
@@ -12,7 +13,6 @@ import type {
12
13
  InjectedScript,
13
14
  LoadErrorEvent,
14
15
  NavigationEvent,
15
- NavigationRule,
16
16
  NavigationState,
17
17
  ProcessGoneEvent,
18
18
  SettingValue,
@@ -27,10 +27,6 @@ type NativeHandlers<E> = { [K in keyof E]: (event: Native<E[K]>) => void };
27
27
  /** The event without the `target` (the view's tag) React Native adds to every native event. */
28
28
  const own = <T,>({ target: _, ...event }: T & { target?: unknown }) => event as T;
29
29
 
30
- /** A page's message comes with its origin, as native verified it (`location.origin` form). */
31
- export type BridgeEvent =
32
- { message: string; origin: string } | { navigated: true } | { unavailable: true };
33
-
34
30
  /**
35
31
  * An event as native sends it: `key` is the hook's key, `core` for the core's own. `askId` is set when native waits for
36
32
  * the answer.
@@ -111,6 +107,7 @@ type NativeProps = ViewProps &
111
107
  export type NativeMethods = {
112
108
  goBack(): Promise<void>;
113
109
  goForward(): Promise<void>;
110
+ load(url: string): Promise<void>;
114
111
  reload(): Promise<void>;
115
112
  stopLoading(): Promise<void>;
116
113
  bridgePost(message: string): Promise<void>;
@@ -149,6 +146,12 @@ const unawaited = (call: Promise<unknown> | undefined, name: string) =>
149
146
  console.error(`[react-native-minimal-webview] ${name} failed`, error);
150
147
  });
151
148
 
149
+ /**
150
+ * Whether `url` is a `javascript:` URL as a URL parser reads it (leading controls and spaces skipped, tabs and newlines
151
+ * dropped): Android's loadUrl would run its script.
152
+ */
153
+ const isJavaScriptUrl = (url: string) => /^[\0- ]*javascript:/i.test(url.replace(/[\t\n\r]/g, ''));
154
+
152
155
  /**
153
156
  * A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
154
157
  * {@link WebViewRef}.
@@ -223,6 +226,24 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
223
226
  return {
224
227
  goBack: () => unawaited(native.current?.goBack(), 'goBack'),
225
228
  goForward: () => unawaited(native.current?.goForward(), 'goForward'),
229
+ load: (url) => {
230
+ if (isJavaScriptUrl(url)) {
231
+ if (__DEV__)
232
+ console.warn(
233
+ '[react-native-minimal-webview] load: a javascript: URL loads nothing; run a script with evaluate'
234
+ );
235
+ return;
236
+ }
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
+ unawaited(
240
+ mounted(() => native.current?.load(url).then(() => 'null')).catch((error: unknown) => {
241
+ const code = (error as { code?: string } | null)?.code;
242
+ if (code !== 'unavailable' && code !== 'navigated') throw error;
243
+ }),
244
+ 'load'
245
+ );
246
+ },
226
247
  reload: () => unawaited(native.current?.reload(), 'reload'),
227
248
  stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
228
249
  evaluate: (script) => mounted(() => native.current?.evaluate(script)),
@@ -256,12 +277,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
256
277
  return () => connection.detach();
257
278
  }, [connection]);
258
279
 
259
- const onBridge = ({ nativeEvent }: Native<BridgeEvent>) => {
260
- if ('message' in nativeEvent) connection?.receive(nativeEvent.message, nativeEvent.origin);
261
- else if ('navigated' in nativeEvent) connection?.navigated();
262
- else connection?.markUnavailable();
263
- };
264
-
265
280
  const requestHandlers = useRequestHandlers(props);
266
281
  const hookOptions = useHookOptions(props.extensions);
267
282
  const navigationRules = useNavigationRules(props.navigationRules);
@@ -270,20 +285,14 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
270
285
  const [asks] = useState(() => new Map<number, AbortController>());
271
286
  useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
272
287
 
273
- // The core's own events: a warning for the developer, and an ask native stopped waiting for.
274
- const onCoreEvent = (name: string, payload: Record<string, unknown>) => {
275
- if (name === 'warning')
276
- console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
277
- else if (name === 'askCancelled') asks.get(payload['askId'] as number)?.abort();
278
- else return false;
279
- return true;
280
- };
281
-
282
288
  const onHookEvent = async ({
283
289
  nativeEvent: { key, name, payload, askId },
284
290
  }: Native<AskableEvent>) => {
285
291
  const core = key === 'core';
286
- if (core && onCoreEvent(name, payload)) return;
292
+ // The core's own events: a warning for the developer, and an ask native stopped waiting for.
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();
287
296
  const request = REQUESTS.find((prop) => core && prop === name);
288
297
  // The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
289
298
  const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
@@ -326,7 +335,7 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
326
335
  requestHandlers={requestHandlers}
327
336
  onNavigation={({ nativeEvent }) => props.onNavigation?.(own(nativeEvent))}
328
337
  onNavigationState={onNavigationState}
329
- onBridge={onBridge}
338
+ onBridge={({ nativeEvent }) => connection?.receive(nativeEvent)}
330
339
  onHookEvent={onHookEvent}
331
340
  onError={({ nativeEvent }) => props.onError?.(own(nativeEvent))}
332
341
  onProcessGone={({ nativeEvent }) => props.onProcessGone?.(own(nativeEvent))}
@@ -356,97 +365,27 @@ function nativeScripts(scripts: InjectedScript[] | undefined) {
356
365
  });
357
366
  }
358
367
 
359
- /** Each rule field's kind, from its type, so that a field missing here, or not in the type, fails to compile. */
360
- const RULE_FIELDS = new Map(
361
- Object.entries({
362
- scheme: 'list',
363
- host: 'list',
364
- path: 'list',
365
- query: 'list',
366
- mainFrame: 'flag',
367
- newWindow: 'flag',
368
- userInitiated: 'flag',
369
- action: 'action',
370
- } satisfies {
371
- [K in keyof NavigationRule]-?: NonNullable<NavigationRule[K]> extends readonly string[]
372
- ? 'list'
373
- : NonNullable<NavigationRule[K]> extends boolean
374
- ? 'flag'
375
- : 'action';
376
- })
377
- );
378
- const ACTIONS: unknown[] = Object.keys({
379
- allow: 0,
380
- block: 0,
381
- external: 0,
382
- ask: 0,
383
- } satisfies Record<NavigationRule['action'], 0>);
384
-
385
- /** A value as a warning shows it. */
386
- const shown = (value: unknown) => {
387
- try {
388
- return JSON.stringify(value) ?? String(value);
389
- } catch {
390
- // A BigInt, a circular value or a throwing toJSON: the message runs in production too, so it must not throw.
391
- return typeof value === 'bigint' ? String(value) : Object.prototype.toString.call(value);
392
- }
393
- };
394
-
395
- /** What a field of each kind takes, as a warning says it, and the check. */
396
- const FIELD_KINDS = {
397
- list: {
398
- takes: 'an array of strings',
399
- ok: (value: unknown) =>
400
- Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
401
- },
402
- flag: { takes: 'true or false', ok: (value: unknown) => typeof value === 'boolean' },
403
- action: { takes: `one of ${shown(ACTIONS)}`, ok: (value: unknown) => ACTIONS.includes(value) },
404
- };
405
-
406
- function ruleProblem(rule: unknown) {
407
- if (typeof rule !== 'object' || rule === null) return `must be an object, not ${shown(rule)}`;
408
- // A missing action is checked as an undefined one; any other field may be undefined (unset).
409
- for (const [key, value] of Object.entries({ action: undefined, ...rule })) {
410
- const kind = RULE_FIELDS.get(key);
411
- if (!kind) return `unknown key ${shown(key)}`;
412
- if ((value !== undefined || kind === 'action') && !FIELD_KINDS[kind].ok(value))
413
- return `${key} must be ${FIELD_KINDS[kind].takes}, not ${shown(value)}`;
414
- }
415
- return undefined;
416
- }
417
-
418
368
  /**
419
- * The rules as the core gets them. The core skips an unknown key and a non-boolean flag, which would widen a rule
420
- * (`hosts` would match every host), so a malformed rule becomes a `block` one. The same array when none is malformed.
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.
421
371
  */
422
372
  function useNavigationRules(rules: WebViewProps['navigationRules']) {
423
- const given: unknown = rules ?? defaultNavigationRules;
424
- const { checked, warnings } = useMemo(() => {
425
- if (!Array.isArray(given))
426
- return {
427
- checked: [],
428
- warnings: [`navigationRules: must be an array, not ${shown(given)}; treated as []`],
429
- };
430
- // Array.from, not map: map skips a sparse array's holes, which would reach native unchecked.
431
- const problems = Array.from(given, ruleProblem);
432
- return {
433
- checked: problems.some(Boolean)
434
- ? Array.from(given, (rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
435
- : given,
436
- warnings: problems.flatMap((problem, i) =>
437
- problem
438
- ? [`navigationRules[${i}]: ${problem}; it blocks every navigation that reaches it`]
439
- : []
440
- ),
441
- };
442
- }, [given]);
373
+ const { checked, warnings } = useMemo(
374
+ () => checkNavigationRules(rules ?? defaultNavigationRules),
375
+ [rules]
376
+ );
377
+ useDevWarnings(warnings);
378
+ return checked;
379
+ }
380
+
381
+ /** Logs each warning in development, again only when the list changes. */
382
+ function useDevWarnings(warnings: string[]) {
443
383
  const json = JSON.stringify(warnings);
444
384
  useEffect(() => {
445
385
  if (!__DEV__) return;
446
386
  for (const warning of JSON.parse(json) as string[])
447
387
  console.warn(`[react-native-minimal-webview] ${warning}`);
448
388
  }, [json]);
449
- return checked as NavigationRule[];
450
389
  }
451
390
 
452
391
  /** The `REQUESTS` with a prop set, as a new array only when that set changes. */
@@ -463,14 +402,11 @@ function useRequestHandlers(props: WebViewProps) {
463
402
  function useHookOptions(extensions: WebViewProps['extensions']) {
464
403
  const on = (extensions ?? []).filter((extension) => !!extension);
465
404
  const keys = on.map(({ key }) => key);
466
- const repeated = JSON.stringify([...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))]);
467
- useEffect(() => {
468
- if (!__DEV__) return;
469
- for (const key of JSON.parse(repeated) as string[])
470
- console.warn(
471
- `[react-native-minimal-webview] extensions: two extensions have the key ${key}; the later one wins`
472
- );
473
- }, [repeated]);
405
+ useDevWarnings(
406
+ [...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))].map(
407
+ (key) => `extensions: two extensions have the key ${key}; the later one wins`
408
+ )
409
+ );
474
410
  const json = JSON.stringify(
475
411
  withoutOff(
476
412
  Object.fromEntries(
@@ -1,10 +1,22 @@
1
1
  import type { Bridge, BridgeOptions, BridgeSchema, BridgeSender, SchemaOf } from '../types';
2
2
  import { DEFAULTS } from '../types.defaults';
3
3
  import { codedError, createEndpoint } from './endpoint';
4
- import { invalidOrigins, originForms } from './origins';
5
- import { MATCHES_ORIGIN, PAGE_CLIENT } from './pageClient.generated';
4
+ import { originGuard } from './origins';
5
+ import { PAGE_CLIENT } from './pageClient.generated';
6
6
  import { type BridgeMessage, parseBridgeMessage } from './protocol';
7
7
 
8
+ /**
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`.
13
+ */
14
+ export type BridgeEvent =
15
+ | { message: string; origin: string }
16
+ | { navigated: true }
17
+ | { crashed: true }
18
+ | { unavailable: true };
19
+
8
20
  /** What `<WebView>` needs from a bridge: `Bridge`'s `[CONNECTION]`, a key the package doesn't export. */
9
21
  export type BridgeConnection = {
10
22
  allowedOrigins: string[];
@@ -12,31 +24,11 @@ export type BridgeConnection = {
12
24
  script: string;
13
25
  attach(post: (message: string) => void): void;
14
26
  detach(): void;
15
- /** A message from the page, and its origin as native verified it. */
16
- receive(message: string, origin: string): void;
17
- /** The platform lacks the WebView features the bridge needs: calls reject with `unavailable`. */
18
- markUnavailable(): void;
19
- /** A new document committed: queue messages until its page client says `ready`. */
20
- navigated(): void;
27
+ receive(event: BridgeEvent): void;
21
28
  };
22
29
 
23
30
  export const CONNECTION = Symbol('bridgeConnection');
24
31
 
25
- /**
26
- * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
27
- * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
28
- */
29
- export function originGuard(what: string, origins: string[]): string | null {
30
- const invalid = invalidOrigins(origins);
31
- if (invalid.length) {
32
- throw new Error(
33
- `${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`
34
- );
35
- }
36
- const forms = originForms(origins);
37
- return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
38
- }
39
-
40
32
  const MAX_QUEUE = 1000;
41
33
 
42
34
  /**
@@ -60,21 +52,15 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
60
52
  );
61
53
  }
62
54
  let post: ((message: string) => void) | null = null;
63
- // idle: no document committed since attach. loading: one committed and hasn't said `ready` yet.
55
+ // idle: no document shown (none committed since attach, or it crashed). loading: one committed and hasn't said `ready` yet.
64
56
  let phase: 'idle' | 'loading' | 'ready' = 'idle';
65
57
  // The token of the document that last said `ready` (protocol.ts `doc`).
66
58
  let doc: string | undefined;
67
- // Messages for the next document that says `ready`. Only the latest document's: see navigated().
59
+ // Messages for the next document that says `ready`. Only the latest document's: see `receive`.
68
60
  let queue: BridgeMessage[] = [];
69
61
  let unavailable = false;
70
62
 
71
- const deliver = (message: BridgeMessage) => {
72
- post?.(JSON.stringify({ ...message, doc }));
73
- if (message.kind === 'call') {
74
- const call = endpoint.pending.get(message.id);
75
- if (call) call.sent = true;
76
- }
77
- };
63
+ const deliver = (message: BridgeMessage) => post?.(JSON.stringify({ ...message, doc }));
78
64
 
79
65
  const endpoint = createEndpoint<BridgeSender>(
80
66
  (message) => {
@@ -84,26 +70,29 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
84
70
  JSON.stringify(message);
85
71
  queue.push(message);
86
72
  const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
87
- if (dropped?.kind === 'call') {
88
- const call = endpoint.pending.get(dropped.id);
73
+ if (dropped?.kind === 'call')
89
74
  endpoint.rejectPending(
90
75
  'unavailable',
91
76
  'the bridge queue was full',
92
- (pending) => pending === call
77
+ (id) => id === dropped.id
93
78
  );
94
- }
95
79
  }
96
80
  },
97
81
  timeoutMs,
98
82
  'n'
99
83
  );
100
84
 
101
- const rejectSent = (message: string) =>
102
- endpoint.rejectPending('navigated', message, (call) => call.sent);
85
+ // A pending call not in the queue was posted to a document.
86
+ const rejectSent = (message: string) => {
87
+ const queued = new Set(
88
+ queue.map((queuedMessage) => queuedMessage.kind === 'call' && queuedMessage.id)
89
+ );
90
+ endpoint.rejectPending('navigated', message, (id) => !queued.has(id));
91
+ };
103
92
  const unavailableMessage =
104
93
  'this WebView lacks the features the bridge needs; update Android System WebView';
105
94
 
106
- const receive = (text: string, origin: string) => {
95
+ const receiveMessage = (text: string, origin: string) => {
107
96
  const message = parseBridgeMessage(text);
108
97
  if (typeof message === 'string') {
109
98
  if (__DEV__)
@@ -143,24 +132,27 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
143
132
  detach() {
144
133
  post = null;
145
134
  phase = 'idle';
135
+ rejectSent('the WebView went away');
146
136
  queue = [];
147
- endpoint.rejectPending('navigated', 'the WebView went away');
137
+ endpoint.rejectPending('unavailable', 'the WebView went away');
148
138
  },
149
- receive,
150
- navigated() {
151
- rejectSent('the page navigated');
152
- // The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
153
- // carry over to an unrelated next one.
154
- if (phase === 'loading') {
155
- endpoint.rejectPending('navigated', 'the page navigated before the bridge was ready');
139
+ receive(event) {
140
+ if ('message' in event) receiveMessage(event.message, event.origin);
141
+ else if ('unavailable' in event) {
142
+ unavailable = true;
156
143
  queue = [];
144
+ endpoint.rejectPending('unavailable', unavailableMessage);
145
+ } else {
146
+ 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
+ if (phase === 'loading') {
150
+ endpoint.rejectPending('unavailable', 'the page navigated before the bridge was ready');
151
+ queue = [];
152
+ }
153
+ // What is queued after a crash is for the reload.
154
+ phase = 'crashed' in event ? 'idle' : 'loading';
157
155
  }
158
- phase = 'loading';
159
- },
160
- markUnavailable() {
161
- unavailable = true;
162
- queue = [];
163
- endpoint.rejectPending('unavailable', unavailableMessage);
164
156
  },
165
157
  };
166
158
 
@@ -8,8 +8,6 @@ type Pending = {
8
8
  resolve(value: unknown): void;
9
9
  reject(error: Error): void;
10
10
  timer: ReturnType<typeof setTimeout> | undefined;
11
- /** Posted to a document, not just queued for the next one (RN). */
12
- sent: boolean;
13
11
  };
14
12
 
15
13
  export const codedError = ({ code, message }: { code: ErrorCode; message: string }): CodedError =>
@@ -50,7 +48,7 @@ export function createEndpoint<Sender = void>(
50
48
  Math.min(ms, 2 ** 31 - 1)
51
49
  )
52
50
  : undefined;
53
- pending.set(id, { resolve, reject, timer, sent: false });
51
+ pending.set(id, { resolve, reject, timer });
54
52
  try {
55
53
  send({ id, kind: 'call', method, params });
56
54
  } catch (error) {
@@ -74,9 +72,9 @@ export function createEndpoint<Sender = void>(
74
72
  listeners.set(event, set.add(listener));
75
73
  return () => set.delete(listener);
76
74
  },
77
- rejectPending(code: BridgeErrorCode, message: string, only?: (call: Pending) => boolean) {
75
+ rejectPending(code: BridgeErrorCode, message: string, only?: (id: string) => boolean) {
78
76
  for (const [id, call] of pending) {
79
- if (only && !only(call)) continue;
77
+ if (only && !only(id)) continue;
80
78
  clearTimeout(call.timer);
81
79
  call.reject(codedError({ code, message }));
82
80
  pending.delete(id);
@@ -1,5 +1,6 @@
1
- // The origin rules in RN: parser, validator, and the matcher whose text build-page-client.mts cuts out as MATCHES_ORIGIN
2
- // for the guards that createBridge and injectedScripts put around page code.
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.
3
+ import { MATCHES_ORIGIN } from './pageClient.generated';
3
4
 
4
5
  /**
5
6
  * An origin rule (`http(s)://host[:port]`, `http(s)://*.host[:port]`) or a `location.origin`, parsed; null for anything
@@ -18,10 +19,6 @@ export const parseOrigin = (text: string) => {
18
19
  return { scheme, wildcard: !!wildcard, hostPort: `${host}${portSuffix}` };
19
20
  };
20
21
 
21
- /** The rules that are neither `*` nor what `parseOrigin` takes. */
22
- export const invalidOrigins = (rules: string[]) =>
23
- rules.filter((rule) => rule !== '*' && !parseOrigin(rule));
24
-
25
22
  /** Origin rules in `location.origin` form, for `matchesOrigin`: exact origins, and wildcards as prefix and suffix. */
26
23
  export type OriginForms = { any: boolean; exact: string[]; wild: [string, string][] };
27
24
 
@@ -59,3 +56,18 @@ export function matchesOrigin(forms: OriginForms, origin: string) {
59
56
  }
60
57
  return false;
61
58
  }
59
+
60
+ /**
61
+ * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
62
+ * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
63
+ */
64
+ export function originGuard(what: string, origins: string[]): string | null {
65
+ const invalid = origins.filter((rule) => rule !== '*' && !parseOrigin(rule));
66
+ if (invalid.length) {
67
+ throw new Error(
68
+ `${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`
69
+ );
70
+ }
71
+ const forms = originForms(origins);
72
+ return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
73
+ }
@@ -1,5 +1,5 @@
1
1
  // Generated by .github/scripts/build-page-client.mts from pageClient.ts, endpoint.ts and origins.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, sent: false });\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(call))\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 });\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}";
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})()";
package/src/index.ts CHANGED
@@ -23,7 +23,7 @@
23
23
  export { AndroidWebView, WebView } from './WebView';
24
24
  export { createWebViewRef, useWebViewState } from './refStore';
25
25
  export { createBridge } from './bridge/createBridge';
26
- export { defaultNavigationRules } from './defaultNavigationRules';
26
+ export { defaultNavigationRules } from './navigationRules';
27
27
  export { reactNativeWebViewMessages } from './reactNativeWebViewMessages';
28
28
  export { AndroidConstants, IOSConstants } from './platform.generated';
29
29
  export type {
@@ -0,0 +1,111 @@
1
+ import type { NavigationRule } from './types';
2
+
3
+ const freeze = <T extends object>(value: T): T => {
4
+ Object.values(value).forEach((field) => typeof field === 'object' && freeze(field as object));
5
+ return Object.freeze(value);
6
+ };
7
+
8
+ /**
9
+ * The rules `navigationRules` has when it is unset: `file:` is blocked, http(s) loads in place, and any other scheme
10
+ * opens externally from the main frame when a user gesture started it ({@link NavigationRule.userInitiated}).
11
+ *
12
+ * Anything else, an iframe's or one without a gesture, is blocked, so a page opens an app only right after the user's
13
+ * tap, click or key press, as each platform counts them. On iOS that leaves out the redirect after a form POST, such
14
+ * as an OAuth `myapp://callback`: an `external` rule for its scheme before these opens it.
15
+ *
16
+ * Frozen; spread it after your own rules to keep it.
17
+ * @see [Navigation rules example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#navigation-rules)
18
+ * @group Navigation
19
+ */
20
+ export const defaultNavigationRules: readonly NavigationRule[] = freeze<NavigationRule[]>([
21
+ { scheme: ['file'], action: 'block' },
22
+ { scheme: ['http', 'https'], action: 'allow' },
23
+ { mainFrame: true, userInitiated: true, action: 'external' },
24
+ ]);
25
+
26
+ /** Each rule field's kind, from its type, so that a field missing here, or not in the type, fails to compile. */
27
+ const RULE_FIELDS = new Map(
28
+ Object.entries({
29
+ scheme: 'list',
30
+ host: 'list',
31
+ path: 'list',
32
+ query: 'list',
33
+ mainFrame: 'flag',
34
+ newWindow: 'flag',
35
+ userInitiated: 'flag',
36
+ action: 'action',
37
+ } satisfies {
38
+ [K in keyof NavigationRule]-?: NonNullable<NavigationRule[K]> extends readonly string[]
39
+ ? 'list'
40
+ : NonNullable<NavigationRule[K]> extends boolean
41
+ ? 'flag'
42
+ : 'action';
43
+ })
44
+ );
45
+ const ACTIONS: unknown[] = Object.keys({
46
+ allow: 0,
47
+ block: 0,
48
+ external: 0,
49
+ ask: 0,
50
+ } satisfies Record<NavigationRule['action'], 0>);
51
+
52
+ /** A value as a warning shows it. */
53
+ const shown = (value: unknown) => {
54
+ try {
55
+ return JSON.stringify(value) ?? String(value);
56
+ } catch {
57
+ // A BigInt, a circular value or a throwing toJSON: the message runs in production too, so it must not throw.
58
+ return typeof value === 'bigint' ? String(value) : Object.prototype.toString.call(value);
59
+ }
60
+ };
61
+
62
+ /** What a field of each kind takes, as a warning says it, and the check. */
63
+ const FIELD_KINDS = {
64
+ list: {
65
+ takes: 'an array of strings',
66
+ ok: (value: unknown) =>
67
+ Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
68
+ },
69
+ flag: { takes: 'true or false', ok: (value: unknown) => typeof value === 'boolean' },
70
+ action: { takes: `one of ${shown(ACTIONS)}`, ok: (value: unknown) => ACTIONS.includes(value) },
71
+ };
72
+
73
+ function ruleProblem(rule: unknown) {
74
+ if (typeof rule !== 'object' || rule === null) return `must be an object, not ${shown(rule)}`;
75
+ // A missing action is checked as an undefined one; any other field may be undefined (unset).
76
+ for (const [key, value] of Object.entries({ action: undefined, ...rule })) {
77
+ const kind = RULE_FIELDS.get(key);
78
+ if (!kind) return `unknown key ${shown(key)}`;
79
+ if ((value !== undefined || kind === 'action') && !FIELD_KINDS[kind].ok(value))
80
+ return `${key} must be ${FIELD_KINDS[kind].takes}, not ${shown(value)}`;
81
+ }
82
+ return undefined;
83
+ }
84
+
85
+ /**
86
+ * The rules as the core gets them, and a warning for each malformed one. The core skips an unknown key and a
87
+ * non-boolean flag, which would widen a rule (`hosts` would match every host), so a malformed rule becomes a `block`
88
+ * one. The same array when none is malformed.
89
+ */
90
+ export function checkNavigationRules(given: unknown): {
91
+ checked: NavigationRule[];
92
+ warnings: string[];
93
+ } {
94
+ if (!Array.isArray(given))
95
+ return {
96
+ checked: [],
97
+ warnings: [`navigationRules: must be an array, not ${shown(given)}; treated as []`],
98
+ };
99
+ // Array.from, not map: map skips a sparse array's holes, which would reach native unchecked.
100
+ const problems = Array.from(given, ruleProblem);
101
+ return {
102
+ checked: (problems.some(Boolean)
103
+ ? Array.from(given, (rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
104
+ : given) as NavigationRule[],
105
+ warnings: problems.flatMap((problem, i) =>
106
+ problem
107
+ ? [`navigationRules[${i}]: ${problem}; it blocks every navigation that reaches it`]
108
+ : []
109
+ ),
110
+ };
111
+ }