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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -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 +487 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -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 +197 -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 +303 -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 +259 -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 +96 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +453 -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 +137 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +33 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +105 -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 +59 -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 +15 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +22 -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 +701 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +201 -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 +16 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +24 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +32 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +115 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1173 -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 +158 -0
  80. package/ios/DocumentEnd.swift +22 -0
  81. package/ios/DownloadName.swift +10 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +310 -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 +38 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +96 -0
  90. package/ios/MinimalWebView+Navigation.swift +243 -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 +513 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +36 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +252 -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 +99 -4
  104. package/src/WebView.tsx +626 -0
  105. package/src/bridge/createBridge.ts +178 -0
  106. package/src/bridge/endpoint.ts +123 -0
  107. package/src/bridge/origins.ts +61 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +67 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +24 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +693 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +26 -0
  116. package/src/refStore.ts +165 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1240 -0
@@ -0,0 +1,453 @@
1
+ import { requireNativeModule, requireNativeView } from 'expo';
2
+ import { useEffect, useMemo, useRef, useState } from 'react';
3
+ import { AppState, Platform } from 'react-native';
4
+ import { CONNECTION, originGuard } from './bridge/createBridge';
5
+ import { codedError } from './bridge/endpoint';
6
+ import { defaultNavigationRules } from './defaultNavigationRules';
7
+ import { REACT_NATIVE_WEBVIEW_DEFAULTS } from './reactNativeWebViewDefaults';
8
+ import { useAttach } from './refStore';
9
+ import { DEFAULTS } from './types.defaults';
10
+ /** The event without the `target` (the view's tag) React Native adds to every native event. */
11
+ const own = ({ target: _, ...event }) => event;
12
+ /**
13
+ * Page requests the core answers natively, by prop name, and `onNavigation`, for the decisions it reports. Native sends
14
+ * JS each only while its prop is set, and reads the set when it would send one, so a prop can come and go.
15
+ */
16
+ const REQUESTS = [
17
+ 'onNavigationRequest',
18
+ 'onOpenExternal',
19
+ 'onFileRequest',
20
+ 'onFullscreenChange',
21
+ 'onPermissionRequest',
22
+ 'onDownload',
23
+ 'onNavigation',
24
+ ];
25
+ /** Every prop that is not a `ViewProps` one, so it never reaches the outermost view. */
26
+ const OWN = [
27
+ 'source',
28
+ 'ios',
29
+ 'android',
30
+ 'userAgent',
31
+ 'navigationRules',
32
+ 'injectedScripts',
33
+ 'bridge',
34
+ 'pullToRefresh',
35
+ 'sharedCookies',
36
+ 'extensions',
37
+ 'onNavigationStateChange',
38
+ 'onError',
39
+ 'onProcessGone',
40
+ 'onLoadStart',
41
+ 'onLoadEnd',
42
+ ...REQUESTS,
43
+ 'ref',
44
+ 'children',
45
+ ];
46
+ // A prop missing from OWN fails to compile here, by name.
47
+ const OWN_SET = new Set(OWN);
48
+ const NativeWebView = requireNativeView('MinimalWebView');
49
+ const nativeModule = () => requireNativeModule('MinimalWebView');
50
+ /** Android rejects a view function with this until Expo has registered the view. */
51
+ const notRegistered = (error) => error?.code === 'ERR_VIEW_NOT_FOUND';
52
+ /** A native call nothing awaits: a rejection is logged, bar one for a view not registered yet, where it does nothing. */
53
+ const unawaited = (call, name) => void call?.catch((error) => {
54
+ if (!notRegistered(error))
55
+ console.error(`[react-native-minimal-webview] ${name} failed`, error);
56
+ });
57
+ /**
58
+ * A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
59
+ * {@link WebViewRef}.
60
+ * @group WebView
61
+ */
62
+ export function WebView(props) {
63
+ useBridgeChangeWarning(props.bridge);
64
+ return <WebViewInstance key={creationKey(props)} {...props}/>;
65
+ }
66
+ /**
67
+ * Warns in development, once per WebView, when another bridge replaces its bridge, which recreated it: a bridge made
68
+ * in render (`bridge={createBridge(…)}`) would reload the page at every render.
69
+ */
70
+ function useBridgeChangeWarning(bridge) {
71
+ const last = useRef(bridge);
72
+ const warned = useRef(false);
73
+ useEffect(() => {
74
+ if (__DEV__ && !warned.current && last.current && bridge && bridge !== last.current) {
75
+ warned.current = true;
76
+ console.warn('[react-native-minimal-webview] bridge: another bridge recreated the WebView, and its page loaded again; ' +
77
+ 'create the bridge once, at module scope or with useMemo');
78
+ }
79
+ last.current = bridge;
80
+ }, [bridge]);
81
+ }
82
+ /** One native WebView's life: a new creation key remounts it, so its state, ref attachment and bridge start over. */
83
+ function WebViewInstance({ ref, ...props }) {
84
+ const native = useRef(null);
85
+ // The rejecters of native calls not settled yet. An unmount rejects them: native may never answer (a hook handler
86
+ // that never replies), and a late answer then settles nothing.
87
+ const [inFlight] = useState(() => new Set());
88
+ useEffect(() => () => {
89
+ const message = 'the WebView unmounted before the call was answered';
90
+ inFlight.forEach((reject) => reject(codedError({ code: 'navigated', message })));
91
+ inFlight.clear();
92
+ }, [inFlight]);
93
+ // A handle can outlive its native view (one captured before an unmount): navigation is then a no-op, and what
94
+ // answers rejects with `unavailable`.
95
+ const [handle] = useState(() => {
96
+ const gone = () => {
97
+ throw codedError({ code: 'unavailable', message: 'the WebView is gone' });
98
+ };
99
+ const settled = (promise) => new Promise((resolve, reject) => {
100
+ inFlight.add(reject);
101
+ promise.then((value) => {
102
+ inFlight.delete(reject);
103
+ resolve(value);
104
+ }, (error) => {
105
+ inFlight.delete(reject);
106
+ reject(error);
107
+ });
108
+ });
109
+ // Retries each frame until Expo has registered the view.
110
+ const mounted = async (call) => {
111
+ for (let frame = 0;; frame++) {
112
+ try {
113
+ return JSON.parse(await settled(call() ?? gone()));
114
+ }
115
+ catch (error) {
116
+ if (!notRegistered(error))
117
+ throw error;
118
+ if (frame === 60 || AppState.currentState === 'background')
119
+ gone();
120
+ await new Promise((resolve) => requestAnimationFrame(resolve));
121
+ }
122
+ }
123
+ };
124
+ return {
125
+ goBack: () => unawaited(native.current?.goBack(), 'goBack'),
126
+ goForward: () => unawaited(native.current?.goForward(), 'goForward'),
127
+ reload: () => unawaited(native.current?.reload(), 'reload'),
128
+ stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
129
+ evaluate: (script) => mounted(() => native.current?.evaluate(script)),
130
+ get: (key) => mounted(() => native.current?.get(key)),
131
+ call: (method, args = []) => mounted(() => native.current?.call(method, JSON.stringify(args))),
132
+ hook: (name, method, args = []) => mounted(() => native.current?.hook(name, method, JSON.stringify(args))),
133
+ };
134
+ });
135
+ const publish = useAttach(ref, handle);
136
+ // onLoadStart and onLoadEnd are the edges of `loading`; native sets the ended load's `outcome`.
137
+ const onNavigationState = ({ nativeEvent }) => {
138
+ const state = own(nativeEvent);
139
+ const was = publish(state);
140
+ props.onNavigationStateChange?.(state);
141
+ if (!was.loading && state.loading)
142
+ props.onLoadStart?.(state);
143
+ if (was.loading && !state.loading)
144
+ props.onLoadEnd?.(state);
145
+ };
146
+ // The same string while nothing in it changed, so a re-render sends native nothing.
147
+ const settings = JSON.stringify(platformSettings(props));
148
+ const injectedScripts = useMemo(() => nativeScripts(props.injectedScripts), [props.injectedScripts]);
149
+ const connection = props.bridge?.[CONNECTION];
150
+ useEffect(() => {
151
+ if (!connection)
152
+ return undefined;
153
+ connection.attach((message) => unawaited(native.current?.bridgePost(message), 'bridgePost'));
154
+ return () => connection.detach();
155
+ }, [connection]);
156
+ const onBridge = ({ nativeEvent }) => {
157
+ if ('message' in nativeEvent)
158
+ connection?.receive(nativeEvent.message, nativeEvent.origin);
159
+ else if ('navigated' in nativeEvent)
160
+ connection?.navigated();
161
+ else
162
+ connection?.markUnavailable();
163
+ };
164
+ const requestHandlers = useRequestHandlers(props);
165
+ const hookOptions = useHookOptions(props.extensions);
166
+ const navigationRules = useNavigationRules(props.navigationRules);
167
+ // One per ask in flight, by id: aborted when native stops waiting (the core's `askCancelled`) or at unmount.
168
+ const [asks] = useState(() => new Map());
169
+ useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
170
+ // The core's own events: a warning for the developer, and an ask native stopped waiting for.
171
+ const onCoreEvent = (name, payload) => {
172
+ if (name === 'warning')
173
+ console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
174
+ else if (name === 'askCancelled')
175
+ asks.get(payload['askId'])?.abort();
176
+ else
177
+ return false;
178
+ return true;
179
+ };
180
+ const onHookEvent = async ({ nativeEvent: { key, name, payload, askId }, }) => {
181
+ const core = key === 'core';
182
+ if (core && onCoreEvent(name, payload))
183
+ return;
184
+ const request = REQUESTS.find((prop) => core && prop === name);
185
+ // The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
186
+ const owner = props.extensions?.findLast((e) => !!e && e.key === key);
187
+ const handler = request
188
+ ? props[request]
189
+ : (_, signal) => owner?.onEvent?.({ name, payload }, signal);
190
+ // Only an ask can be cancelled, so only an ask gets a signal.
191
+ let controller;
192
+ if (askId !== undefined) {
193
+ controller = new AbortController();
194
+ asks.set(askId, controller);
195
+ }
196
+ const failure = request ? `${request} failed` : `onEvent failed for ${key}.${name}`;
197
+ let value = null;
198
+ try {
199
+ value = await handler?.(payload, controller?.signal);
200
+ }
201
+ catch (error) {
202
+ // Native waits on this handler: one that throws still answers, with null (native's safe default).
203
+ console.error(`[react-native-minimal-webview] ${failure}`, error);
204
+ }
205
+ if (askId === undefined)
206
+ return;
207
+ asks.delete(askId);
208
+ // Native already answered a cancelled ask with null; a late answer would find nothing.
209
+ if (!controller?.signal.aborted)
210
+ await native.current?.answer(askId, answerJson(value));
211
+ };
212
+ return (<NativeWebView {...viewPropsOf(props)} ref={native} source={props.source} settings={settings} pullToRefresh={props.pullToRefresh} sharedCookies={Platform.OS === 'ios' ? props.sharedCookies : undefined} navigationRules={navigationRules} injectedScripts={injectedScripts} bridgeScript={connection?.script} bridgeOrigins={connection?.allowedOrigins} hookOptions={hookOptions} requestHandlers={requestHandlers} onNavigation={({ nativeEvent }) => props.onNavigation?.(own(nativeEvent))} onNavigationState={onNavigationState} onBridge={onBridge} onHookEvent={onHookEvent} onError={({ nativeEvent }) => props.onError?.(own(nativeEvent))} onProcessGone={({ nativeEvent }) => props.onProcessGone?.(own(nativeEvent))}/>);
213
+ }
214
+ /** An ask's answer for native: null for one JSON can't encode (a function, a cycle, a BigInt), so the ask settles. */
215
+ function answerJson(value) {
216
+ try {
217
+ return JSON.stringify(value) ?? 'null';
218
+ }
219
+ catch {
220
+ return 'null';
221
+ }
222
+ }
223
+ /**
224
+ * The scripts as native runs them: one whose `origins` lack `*` runs inside a function, so that even its function
225
+ * declarations take effect only where the guard lets it run.
226
+ */
227
+ function nativeScripts(scripts) {
228
+ return scripts?.map(({ code, allFrames, origins }) => {
229
+ if (!Array.isArray(origins))
230
+ throw new Error("injectedScripts: every script needs origins (['*'] for every origin)");
231
+ const guard = originGuard('injectedScripts: invalid origins', origins);
232
+ return { code: guard ? `if (${guard}) (() => {\n${code}\n})();` : code, allFrames };
233
+ });
234
+ }
235
+ /** Each rule field's kind, from its type, so that a field missing here, or not in the type, fails to compile. */
236
+ const RULE_FIELDS = new Map(Object.entries({
237
+ scheme: 'list',
238
+ host: 'list',
239
+ path: 'list',
240
+ query: 'list',
241
+ mainFrame: 'flag',
242
+ newWindow: 'flag',
243
+ userInitiated: 'flag',
244
+ action: 'action',
245
+ }));
246
+ const ACTIONS = Object.keys({
247
+ allow: 0,
248
+ block: 0,
249
+ external: 0,
250
+ ask: 0,
251
+ });
252
+ /** A value as a warning shows it. */
253
+ const shown = (value) => {
254
+ try {
255
+ return JSON.stringify(value) ?? String(value);
256
+ }
257
+ catch {
258
+ // A BigInt, a circular value or a throwing toJSON: the message runs in production too, so it must not throw.
259
+ return typeof value === 'bigint' ? String(value) : Object.prototype.toString.call(value);
260
+ }
261
+ };
262
+ /** What a field of each kind takes, as a warning says it, and the check. */
263
+ const FIELD_KINDS = {
264
+ list: {
265
+ takes: 'an array of strings',
266
+ ok: (value) => Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
267
+ },
268
+ flag: { takes: 'true or false', ok: (value) => typeof value === 'boolean' },
269
+ action: { takes: `one of ${shown(ACTIONS)}`, ok: (value) => ACTIONS.includes(value) },
270
+ };
271
+ function ruleProblem(rule) {
272
+ if (typeof rule !== 'object' || rule === null)
273
+ return `must be an object, not ${shown(rule)}`;
274
+ // A missing action is checked as an undefined one; any other field may be undefined (unset).
275
+ for (const [key, value] of Object.entries({ action: undefined, ...rule })) {
276
+ const kind = RULE_FIELDS.get(key);
277
+ if (!kind)
278
+ return `unknown key ${shown(key)}`;
279
+ if ((value !== undefined || kind === 'action') && !FIELD_KINDS[kind].ok(value))
280
+ return `${key} must be ${FIELD_KINDS[kind].takes}, not ${shown(value)}`;
281
+ }
282
+ return undefined;
283
+ }
284
+ /**
285
+ * The rules as the core gets them. The core skips an unknown key and a non-boolean flag, which would widen a rule
286
+ * (`hosts` would match every host), so a malformed rule becomes a `block` one. The same array when none is malformed.
287
+ */
288
+ function useNavigationRules(rules) {
289
+ const given = rules ?? defaultNavigationRules;
290
+ const { checked, warnings } = useMemo(() => {
291
+ if (!Array.isArray(given))
292
+ return {
293
+ checked: [],
294
+ warnings: [`navigationRules: must be an array, not ${shown(given)}; treated as []`],
295
+ };
296
+ // Array.from, not map: map skips a sparse array's holes, which would reach native unchecked.
297
+ const problems = Array.from(given, ruleProblem);
298
+ return {
299
+ checked: problems.some(Boolean)
300
+ ? Array.from(given, (rule, i) => (problems[i] ? { action: 'block' } : rule))
301
+ : given,
302
+ warnings: problems.flatMap((problem, i) => problem
303
+ ? [`navigationRules[${i}]: ${problem}; it blocks every navigation that reaches it`]
304
+ : []),
305
+ };
306
+ }, [given]);
307
+ const json = JSON.stringify(warnings);
308
+ useEffect(() => {
309
+ if (!__DEV__)
310
+ return;
311
+ for (const warning of JSON.parse(json))
312
+ console.warn(`[react-native-minimal-webview] ${warning}`);
313
+ }, [json]);
314
+ return checked;
315
+ }
316
+ /** The `REQUESTS` with a prop set, as a new array only when that set changes. */
317
+ function useRequestHandlers(props) {
318
+ const key = REQUESTS.filter((prop) => props[prop]).join();
319
+ return useMemo(() => (key ? key.split(',') : []), [key]);
320
+ }
321
+ /**
322
+ * The core's `hookOptions`: each extension's `options` by its key, the later of two extensions with one key winning (a
323
+ * development warning). The same object while the JSON is the same, so a render with new handlers sends the core
324
+ * nothing.
325
+ */
326
+ function useHookOptions(extensions) {
327
+ const on = (extensions ?? []).filter((extension) => !!extension);
328
+ const keys = on.map(({ key }) => key);
329
+ const repeated = JSON.stringify([...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))]);
330
+ useEffect(() => {
331
+ if (!__DEV__)
332
+ return;
333
+ for (const key of JSON.parse(repeated))
334
+ console.warn(`[react-native-minimal-webview] extensions: two extensions have the key ${key}; the later one wins`);
335
+ }, [repeated]);
336
+ const json = JSON.stringify(withoutOff(Object.fromEntries(
337
+ // An unset `options` is `true` (HookExtension.options).
338
+ on.map(({ key, options = true }) => [key, options]))));
339
+ return useMemo(() => JSON.parse(json), [json]);
340
+ }
341
+ /** Bridges by identity, for the creation key. */
342
+ const bridgeIds = new WeakMap();
343
+ let lastBridgeId = 0;
344
+ /**
345
+ * What native sets up once, at creation (the bridge, `ios.configuration`). As WebViewInstance's `key`, a change
346
+ * remounts it.
347
+ */
348
+ function creationKey(props) {
349
+ const bridge = props.bridge;
350
+ let id = bridge && bridgeIds.get(bridge);
351
+ if (bridge && id === undefined)
352
+ bridgeIds.set(bridge, (id = ++lastBridgeId));
353
+ return JSON.stringify([id ?? 0, Platform.OS === 'ios' ? props.ios?.configuration : undefined], sortedKeys);
354
+ }
355
+ /** A null or false value is off, and its key is left out: native treats a present key as on. */
356
+ const withoutOff = (options) => Object.fromEntries(Object.entries(options).filter(([, value]) => value != null && value !== false));
357
+ /** A JSON.stringify replacer: the same options in another key order are the same key. */
358
+ const sortedKeys = (_, value) => value && typeof value === 'object' && !Array.isArray(value)
359
+ ? Object.fromEntries(Object.entries(value).sort())
360
+ : value;
361
+ function viewPropsOf(props) {
362
+ return Object.fromEntries(Object.entries(props).filter(([key]) => !OWN_SET.has(key)));
363
+ }
364
+ /** Each root's keys with its `other` ones among them, as native takes them; a generated key wins. */
365
+ const flattened = (roots = {}) => Object.fromEntries(Object.entries(roots).map(([name, { other, ...keys } = {}]) => [name, { ...other, ...keys }]));
366
+ /** Each layer's roots over the earlier layers', key by key. */
367
+ const layered = (...layers) => layers.reduce((out, layer) => {
368
+ for (const [root, keys] of Object.entries(layer))
369
+ out[root] = { ...out[root], ...keys };
370
+ return out;
371
+ }, {});
372
+ /**
373
+ * The platform's settings for native: the package's defaults, react-native-webview's over them, the app's `ios` or
374
+ * `android` roots over those, and `userAgent` on top. Native restores the key of a removed `userAgent`. Android's
375
+ * own defaults are written natively.
376
+ */
377
+ function platformSettings(props) {
378
+ const [defaults, rnw, app, userAgent] = Platform.OS === 'ios'
379
+ ? [
380
+ flattened(DEFAULTS.IOSSettings),
381
+ REACT_NATIVE_WEBVIEW_DEFAULTS.ios,
382
+ flattened(props.ios),
383
+ { webView: { customUserAgent: props.userAgent } },
384
+ ]
385
+ : [
386
+ {},
387
+ REACT_NATIVE_WEBVIEW_DEFAULTS.android,
388
+ flattened(props.android),
389
+ { settings: { userAgentString: props.userAgent } },
390
+ ];
391
+ return layered(defaults, rnw, app, props.userAgent === undefined ? {} : userAgent);
392
+ }
393
+ /**
394
+ * Android's process-wide WebView functions, like the static methods of Android's `WebView`. On iOS they do nothing,
395
+ * and `defaultUserAgent` is null.
396
+ * @group WebView
397
+ * @android
398
+ * @namespace
399
+ */
400
+ export const AndroidWebView = {
401
+ /**
402
+ * Android's default user agent, for `android.settings.userAgentString` with a suffix.
403
+ *
404
+ * The first read loads WebView's code, on the JS thread: read it once `warmUp()` has had time or a WebView is
405
+ * mounted.
406
+ * @android
407
+ */
408
+ get defaultUserAgent() {
409
+ return Platform.OS === 'android' ? nativeModule().defaultUserAgent : null;
410
+ },
411
+ /**
412
+ * Starts WebView before any WebView mounts, so the first WebView mounts sooner.
413
+ *
414
+ * It helps only if it runs well before the first WebView mounts: at app start, or as the screen with the WebView is
415
+ * pushed. WebView starts once per app, and React Native's first `fetch` starts it too.
416
+ * @android
417
+ */
418
+ warmUp() {
419
+ if (Platform.OS === 'android')
420
+ nativeModule().warmUp();
421
+ },
422
+ /**
423
+ * Opens a connection to `url`'s origin (DNS, TCP, TLS) in WebView's default profile, ahead of a load.
424
+ *
425
+ * Call it before the load starts: as the screen with the WebView is pushed, or for the next page a mounted WebView
426
+ * will go to. A WebView connects to its `source` itself as it mounts.
427
+ *
428
+ * It starts WebView on the UI thread if nothing has yet, so call it once `warmUp()` has had time or a WebView is
429
+ * mounted.
430
+ *
431
+ * Needs the androidx.webkit features `MULTI_PROFILE` and `ENQUEUE_PRECONNECT` or `PRECONNECT`; without them it does
432
+ * nothing. For prefetch and prerender, a native hook uses `ProfileStore`.
433
+ * @android
434
+ */
435
+ preconnect(url) {
436
+ if (Platform.OS === 'android')
437
+ unawaited(nativeModule().preconnect(url), 'preconnect');
438
+ },
439
+ /**
440
+ * Turns remote debugging (`chrome://inspect`) of every WebView in the app on or off.
441
+ *
442
+ * Until it is called, it is on when the app is debuggable (a debug build) and off otherwise. Called before any
443
+ * WebView exists, it applies when the first one is made, so it doesn't start WebView. On iOS,
444
+ * `ios.webView.inspectable` sets it per WebView.
445
+ * @android
446
+ * @see [Debugging the page example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#debugging-the-page)
447
+ */
448
+ setWebContentsDebuggingEnabled(enabled) {
449
+ if (Platform.OS === 'android')
450
+ unawaited(nativeModule().setWebContentsDebuggingEnabled(enabled), 'setWebContentsDebuggingEnabled');
451
+ },
452
+ };
453
+ //# sourceMappingURL=WebView.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebView.js","sourceRoot":"","sources":["../src/WebView.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9D,OAAO,EAAY,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACvE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAkB,MAAM,cAAc,CAAC;AAElE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAavC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAM5C,+FAA+F;AAC/F,MAAM,GAAG,GAAG,CAAK,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG,KAAK,EAA4B,EAAE,EAAE,CAAC,KAAU,CAAC;AAiBlF;;;GAGG;AACH,MAAM,QAAQ,GAAG;IACf,qBAAqB;IACrB,gBAAgB;IAChB,eAAe;IACf,oBAAoB;IACpB,qBAAqB;IACrB,YAAY;IACZ,cAAc;CACN,CAAC;AAEX,wFAAwF;AACxF,MAAM,GAAG,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S,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,CAAC;IAC5E,CAAC;IACD;;;;;;OAMG;IACH,MAAM;QACJ,IAAI,QAAQ,CAAC,EAAE,KAAK,SAAS;YAAE,YAAY,EAAE,CAAC,MAAM,EAAE,CAAC;IACzD,CAAC;IACD;;;;;;;;;;;;OAYG;IACH,UAAU,CAAC,GAAW;QACpB,IAAI,QAAQ,CAAC,EAAE,KAAK,SAAS;YAAE,SAAS,CAAC,YAAY,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,YAAY,CAAC,CAAC;IACzF,CAAC;IACD;;;;;;;;OAQG;IACH,8BAA8B,CAAC,OAAgB;QAC7C,IAAI,QAAQ,CAAC,EAAE,KAAK,SAAS;YAC3B,SAAS,CACP,YAAY,EAAE,CAAC,8BAA8B,CAAC,OAAO,CAAC,EACtD,gCAAgC,CACjC,CAAC;IACN,CAAC;CACF,CAAC"}
@@ -0,0 +1,32 @@
1
+ import type { Bridge, BridgeOptions, BridgeSchema } from '../types';
2
+ /** What `<WebView>` needs from a bridge: `Bridge`'s `[CONNECTION]`, a key the package doesn't export. */
3
+ export type BridgeConnection = {
4
+ allowedOrigins: string[];
5
+ /** The page client to inject at document start. */
6
+ script: string;
7
+ attach(post: (message: string) => void): void;
8
+ detach(): void;
9
+ /** A message from the page, and its origin as native verified it. */
10
+ receive(message: string, origin: string): void;
11
+ /** The platform lacks the WebView features the bridge needs: calls reject with `unavailable`. */
12
+ markUnavailable(): void;
13
+ /** A new document committed: queue messages until its page client says `ready`. */
14
+ navigated(): void;
15
+ };
16
+ export declare const CONNECTION: unique symbol;
17
+ /**
18
+ * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
19
+ * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
20
+ */
21
+ export declare function originGuard(what: string, origins: string[]): string | null;
22
+ /**
23
+ * Creates a {@link Bridge} to the pages of `allowedOrigins`, for one WebView's `bridge` prop.
24
+ *
25
+ * The type argument, a {@link BridgeSchema}, types the methods and events of `handle`, `call`, `emit` and `on`.
26
+ * Nothing checks them at runtime, so a handler still validates what an untrusted page sends. Throws an `Error` for an
27
+ * invalid origin rule or timeout.
28
+ * @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#the-bridge)
29
+ * @group Bridge
30
+ */
31
+ export declare function createBridge<Schema extends BridgeSchema = BridgeSchema>(options: BridgeOptions): Bridge<Schema>;
32
+ //# sourceMappingURL=createBridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createBridge.d.ts","sourceRoot":"","sources":["../../src/bridge/createBridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,YAAY,EAAgB,MAAM,UAAU,CAAC;AAOlF,yGAAyG;AACzG,MAAM,MAAM,gBAAgB,GAAG;IAC7B,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;IAC9C,MAAM,IAAI,IAAI,CAAC;IACf,qEAAqE;IACrE,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/C,iGAAiG;IACjG,eAAe,IAAI,IAAI,CAAC;IACxB,mFAAmF;IACnF,SAAS,IAAI,IAAI,CAAC;CACnB,CAAC;AAEF,eAAO,MAAM,UAAU,eAA6B,CAAC;AAErD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,IAAI,CAS1E;AAID;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,MAAM,SAAS,YAAY,GAAG,YAAY,EACrE,OAAO,EAAE,aAAa,GACrB,MAAM,CAAC,MAAM,CAAC,CA6HhB"}
@@ -0,0 +1,137 @@
1
+ import { DEFAULTS } from '../types.defaults';
2
+ import { codedError, createEndpoint } from './endpoint';
3
+ import { invalidOrigins, originForms } from './origins';
4
+ import { MATCHES_ORIGIN, PAGE_CLIENT } from './pageClient.generated';
5
+ import { parseBridgeMessage } from './protocol';
6
+ export const CONNECTION = Symbol('bridgeConnection');
7
+ /**
8
+ * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
9
+ * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
10
+ */
11
+ export function originGuard(what, origins) {
12
+ const invalid = invalidOrigins(origins);
13
+ if (invalid.length) {
14
+ throw new Error(`${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`);
15
+ }
16
+ const forms = originForms(origins);
17
+ return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
18
+ }
19
+ const MAX_QUEUE = 1000;
20
+ /**
21
+ * Creates a {@link Bridge} to the pages of `allowedOrigins`, for one WebView's `bridge` prop.
22
+ *
23
+ * The type argument, a {@link BridgeSchema}, types the methods and events of `handle`, `call`, `emit` and `on`.
24
+ * Nothing checks them at runtime, so a handler still validates what an untrusted page sends. Throws an `Error` for an
25
+ * invalid origin rule or timeout.
26
+ * @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#the-bridge)
27
+ * @group Bridge
28
+ */
29
+ export function createBridge(options) {
30
+ // `*` or what origins.ts parses: addWebMessageListener's rules minus custom schemes.
31
+ const guard = originGuard('createBridge: invalid allowedOrigins', options.allowedOrigins);
32
+ const timeoutMs = options.timeoutMs ?? DEFAULTS.BridgeOptions.timeoutMs;
33
+ if (!(timeoutMs >= 0)) {
34
+ throw new Error(`createBridge: timeoutMs must be 0 or more (0 or Infinity for none), not ${timeoutMs}`);
35
+ }
36
+ let post = null;
37
+ // idle: no document committed since attach. loading: one committed and hasn't said `ready` yet.
38
+ let phase = 'idle';
39
+ // The token of the document that last said `ready` (protocol.ts `doc`).
40
+ let doc;
41
+ // Messages for the next document that says `ready`. Only the latest document's: see navigated().
42
+ let queue = [];
43
+ let unavailable = false;
44
+ const deliver = (message) => {
45
+ post?.(JSON.stringify({ ...message, doc }));
46
+ if (message.kind === 'call') {
47
+ const call = endpoint.pending.get(message.id);
48
+ if (call)
49
+ call.sent = true;
50
+ }
51
+ };
52
+ const endpoint = createEndpoint((message) => {
53
+ if (post && phase === 'ready')
54
+ deliver(message);
55
+ else {
56
+ // Throws now, at the caller, for what JSON can't encode, rather than in the flush, losing the rest of the queue.
57
+ JSON.stringify(message);
58
+ queue.push(message);
59
+ const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
60
+ if (dropped?.kind === 'call') {
61
+ const call = endpoint.pending.get(dropped.id);
62
+ endpoint.rejectPending('unavailable', 'the bridge queue was full', (pending) => pending === call);
63
+ }
64
+ }
65
+ }, timeoutMs, 'n');
66
+ const rejectSent = (message) => endpoint.rejectPending('navigated', message, (call) => call.sent);
67
+ const unavailableMessage = 'this WebView lacks the features the bridge needs; update Android System WebView';
68
+ const receive = (text, origin) => {
69
+ const message = parseBridgeMessage(text);
70
+ if (typeof message === 'string') {
71
+ if (__DEV__)
72
+ console.warn(`[react-native-minimal-webview] dropped a bridge message: ${message}`);
73
+ return;
74
+ }
75
+ if (message.kind !== 'ready') {
76
+ // Answers skip the ready queue: a module script may await one before DOMContentLoaded, and native can deliver
77
+ // it, as the page has posted.
78
+ const reply = (answer) => post?.(JSON.stringify({ ...answer, doc: message.doc }));
79
+ void endpoint.receive(message, reply, { origin });
80
+ return;
81
+ }
82
+ // A new document: calls posted to the previous one can no longer be answered. Queued ones are for this one.
83
+ rejectSent('the page navigated');
84
+ phase = 'ready';
85
+ doc = message.doc;
86
+ const flushing = queue;
87
+ queue = [];
88
+ // A queued call that already timed out is not sent: nobody waits for its answer.
89
+ for (const queued of flushing)
90
+ if (queued.kind !== 'call' || endpoint.pending.has(queued.id))
91
+ deliver(queued);
92
+ };
93
+ const connection = {
94
+ allowedOrigins: options.allowedOrigins,
95
+ script: `${guard ? `if (${guard}) ` : ''}(${PAGE_CLIENT})(window, ${Number(timeoutMs)});`,
96
+ attach(next) {
97
+ // Two WebViews would steal each other's replies, and either one's detach would cut off the other.
98
+ if (post)
99
+ throw new Error('createBridge: this bridge is already attached to a mounted WebView; give each WebView its own bridge');
100
+ post = next;
101
+ },
102
+ detach() {
103
+ post = null;
104
+ phase = 'idle';
105
+ queue = [];
106
+ endpoint.rejectPending('navigated', 'the WebView went away');
107
+ },
108
+ receive,
109
+ navigated() {
110
+ rejectSent('the page navigated');
111
+ // The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
112
+ // carry over to an unrelated next one.
113
+ if (phase === 'loading') {
114
+ endpoint.rejectPending('navigated', 'the page navigated before the bridge was ready');
115
+ queue = [];
116
+ }
117
+ phase = 'loading';
118
+ },
119
+ markUnavailable() {
120
+ unavailable = true;
121
+ queue = [];
122
+ endpoint.rejectPending('unavailable', unavailableMessage);
123
+ },
124
+ };
125
+ return {
126
+ handle: endpoint.handle,
127
+ call(method, params, callOptions) {
128
+ if (unavailable)
129
+ return Promise.reject(codedError({ code: 'unavailable', message: unavailableMessage }));
130
+ return endpoint.call(method, params, callOptions);
131
+ },
132
+ emit: endpoint.emit,
133
+ on: endpoint.on,
134
+ [CONNECTION]: connection,
135
+ }; // the schema types only what callers pass
136
+ }
137
+ //# sourceMappingURL=createBridge.js.map