@a16n/web-sim 0.0.0-stage → 0.1.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 (281) hide show
  1. package/README.md +13 -2
  2. package/bin/cli.ts +255 -0
  3. package/bin/web-sim.js +39 -0
  4. package/overrides/@backpackapp-io/react-native-toast/overrides.ts +15 -0
  5. package/overrides/@react-native-firebase/app/overrides.ts +34 -0
  6. package/overrides/@tiktok-for-business/react-native-sdk/NativeTiktokSdk.ts +29 -0
  7. package/overrides/@tiktok-for-business/react-native-sdk/overrides.ts +9 -0
  8. package/overrides/expo-application/ExpoApplication.ts +81 -0
  9. package/overrides/expo-application/overrides.ts +16 -0
  10. package/overrides/expo-background-task/ExpoBackgroundTaskModule.ts +30 -0
  11. package/overrides/expo-background-task/overrides.ts +9 -0
  12. package/overrides/expo-constants/ExponentConstants.ts +66 -0
  13. package/overrides/expo-constants/overrides.ts +9 -0
  14. package/overrides/expo-device/ExpoDevice.ts +104 -0
  15. package/overrides/expo-device/overrides.ts +9 -0
  16. package/overrides/expo-glass-effect/GlassContainer.tsx +9 -0
  17. package/overrides/expo-glass-effect/GlassView.tsx +95 -0
  18. package/overrides/expo-glass-effect/availability.ts +14 -0
  19. package/overrides/expo-glass-effect/overrides.ts +14 -0
  20. package/overrides/expo-haptics/Haptics.ts +67 -0
  21. package/overrides/expo-haptics/overrides.ts +5 -0
  22. package/overrides/expo-mail-composer/ExpoMailComposer.ts +40 -0
  23. package/overrides/expo-mail-composer/overrides.ts +9 -0
  24. package/overrides/expo-mesh-gradient/MeshGradientView.tsx +44 -0
  25. package/overrides/expo-mesh-gradient/overrides.ts +9 -0
  26. package/overrides/expo-modules-core/overrides.ts +12 -0
  27. package/overrides/expo-navigation-bar/ExpoNavigationBar.ts +29 -0
  28. package/overrides/expo-navigation-bar/NavigationBar.ts +43 -0
  29. package/overrides/expo-navigation-bar/overrides.ts +12 -0
  30. package/overrides/expo-router/NativeStackView.tsx +74 -0
  31. package/overrides/expo-router/NativeTabsView.tsx +263 -0
  32. package/overrides/expo-router/SafeAreaProvider.ts +6 -0
  33. package/overrides/expo-router/overrides.ts +23 -0
  34. package/overrides/expo-router/statusBarRequests.ts +51 -0
  35. package/overrides/expo-screen-orientation/ExpoScreenOrientation.ts +173 -0
  36. package/overrides/expo-screen-orientation/overrides.ts +21 -0
  37. package/overrides/expo-sharing/SharingNativeModule.ts +21 -0
  38. package/overrides/expo-sharing/overrides.ts +9 -0
  39. package/overrides/expo-sms/ExpoSMS.ts +24 -0
  40. package/overrides/expo-sms/overrides.ts +9 -0
  41. package/overrides/expo-splash-screen/SplashScreen.ts +25 -0
  42. package/overrides/expo-splash-screen/overrides.ts +5 -0
  43. package/overrides/expo-status-bar/StatusBar.tsx +44 -0
  44. package/overrides/expo-status-bar/overrides.ts +5 -0
  45. package/overrides/expo-store-review/ExpoStoreReview.ts +18 -0
  46. package/overrides/expo-store-review/overrides.ts +9 -0
  47. package/overrides/expo-symbols/SymbolView.tsx +192 -0
  48. package/overrides/expo-symbols/overrides.ts +9 -0
  49. package/overrides/expo-system-ui/ExpoSystemUI.ts +34 -0
  50. package/overrides/expo-system-ui/overrides.ts +9 -0
  51. package/overrides/expo-task-manager/ExpoTaskManager.ts +39 -0
  52. package/overrides/expo-task-manager/overrides.ts +9 -0
  53. package/overrides/expo-tracking-transparency/ExpoTrackingTransparency.ts +30 -0
  54. package/overrides/expo-tracking-transparency/overrides.ts +11 -0
  55. package/overrides/expo-video/ExpoVideo.ts +16 -0
  56. package/overrides/expo-video/overrides.ts +9 -0
  57. package/overrides/lottie-react-native/LottieView.tsx +87 -0
  58. package/overrides/lottie-react-native/overrides.ts +9 -0
  59. package/overrides/react-native-pager-view/PagerViewNativeComponent.tsx +254 -0
  60. package/overrides/react-native-pager-view/overrides.ts +9 -0
  61. package/overrides/react-native-reanimated/overrides.ts +28 -0
  62. package/overrides/react-native-safe-area-context/NativeSafeAreaProvider.tsx +40 -0
  63. package/overrides/react-native-safe-area-context/overrides.ts +12 -0
  64. package/overrides/react-native-share/NativeRNShare.ts +22 -0
  65. package/overrides/react-native-share/overrides.ts +12 -0
  66. package/overrides/react-native-share/platform.ts +14 -0
  67. package/overrides/react-native-turbo-image/TurboImage.tsx +101 -0
  68. package/overrides/react-native-turbo-image/overrides.ts +9 -0
  69. package/overrides/react-native-web/RefreshControl.tsx +57 -0
  70. package/overrides/react-native-web/overrides.ts +157 -0
  71. package/overrides/react-native-web/useElementLayout.ts +152 -0
  72. package/package.json +80 -4
  73. package/plugins/battery/overrides/expo-battery/ExpoBattery.ts +57 -0
  74. package/plugins/battery/overrides/expo-battery/overrides.ts +9 -0
  75. package/plugins/battery/plugin.ts +8 -0
  76. package/plugins/battery/shell.tsx +56 -0
  77. package/plugins/battery/state.ts +11 -0
  78. package/plugins/biometrics/overrides/expo-local-authentication/ExpoLocalAuthentication.ts +90 -0
  79. package/plugins/biometrics/overrides/expo-local-authentication/overrides.ts +11 -0
  80. package/plugins/biometrics/plugin.ts +8 -0
  81. package/plugins/biometrics/shell.tsx +88 -0
  82. package/plugins/biometrics/state.ts +41 -0
  83. package/plugins/brightness/app.ts +5 -0
  84. package/plugins/brightness/overrides/expo-brightness/Brightness.ts +98 -0
  85. package/plugins/brightness/overrides/expo-brightness/overrides.ts +10 -0
  86. package/plugins/brightness/plugin.ts +9 -0
  87. package/plugins/brightness/shell.tsx +55 -0
  88. package/plugins/brightness/state.ts +19 -0
  89. package/plugins/calendar/calendar.ts +299 -0
  90. package/plugins/calendar/overrides/expo-calendar/ExpoCalendar.ts +358 -0
  91. package/plugins/calendar/overrides/expo-calendar/LegacyExpoCalendar.ts +163 -0
  92. package/plugins/calendar/overrides/expo-calendar/overrides.ts +14 -0
  93. package/plugins/calendar/plugin.ts +8 -0
  94. package/plugins/calendar/shell.tsx +123 -0
  95. package/plugins/camera/overrides/expo-camera/ExpoCamera.tsx +269 -0
  96. package/plugins/camera/overrides/expo-camera/ExpoCameraManager.ts +56 -0
  97. package/plugins/camera/overrides/expo-camera/overrides.ts +12 -0
  98. package/plugins/camera/plugin.ts +9 -0
  99. package/plugins/camera/shell.tsx +107 -0
  100. package/plugins/camera/state.ts +61 -0
  101. package/plugins/clipboard/overrides/expo-clipboard/ExpoClipboard.ts +138 -0
  102. package/plugins/clipboard/overrides/expo-clipboard/overrides.ts +9 -0
  103. package/plugins/clipboard/plugin.ts +8 -0
  104. package/plugins/clipboard/shell.tsx +122 -0
  105. package/plugins/clipboard/state.ts +93 -0
  106. package/plugins/clock/app.ts +25 -0
  107. package/plugins/clock/plugin.ts +8 -0
  108. package/plugins/clock/shell.tsx +225 -0
  109. package/plugins/clock/state.ts +12 -0
  110. package/plugins/contacts/contacts.ts +125 -0
  111. package/plugins/contacts/overrides/expo-contacts/ExpoContacts.ts +153 -0
  112. package/plugins/contacts/overrides/expo-contacts/ExpoContactsNext.ts +232 -0
  113. package/plugins/contacts/overrides/expo-contacts/overrides.ts +12 -0
  114. package/plugins/contacts/plugin.ts +8 -0
  115. package/plugins/contacts/shell.tsx +109 -0
  116. package/plugins/home-indicator/app.ts +5 -0
  117. package/plugins/home-indicator/plugin.ts +9 -0
  118. package/plugins/home-indicator/requests.ts +48 -0
  119. package/plugins/home-indicator/shell.tsx +68 -0
  120. package/plugins/home-indicator/state.ts +31 -0
  121. package/plugins/keep-awake/app.ts +5 -0
  122. package/plugins/keep-awake/overrides/expo-keep-awake/ExpoKeepAwake.ts +27 -0
  123. package/plugins/keep-awake/overrides/expo-keep-awake/overrides.ts +9 -0
  124. package/plugins/keep-awake/plugin.ts +9 -0
  125. package/plugins/keep-awake/shell.tsx +80 -0
  126. package/plugins/keep-awake/state.ts +12 -0
  127. package/plugins/keyboard/Keyboard.tsx +354 -0
  128. package/plugins/keyboard/app.ts +90 -0
  129. package/plugins/keyboard/controller.ts +384 -0
  130. package/plugins/keyboard/fields.ts +244 -0
  131. package/plugins/keyboard/icons.tsx +283 -0
  132. package/plugins/keyboard/keyboard.css +362 -0
  133. package/plugins/keyboard/layouts/android.ts +175 -0
  134. package/plugins/keyboard/layouts/index.ts +10 -0
  135. package/plugins/keyboard/layouts/ios.ts +219 -0
  136. package/plugins/keyboard/layouts/types.ts +80 -0
  137. package/plugins/keyboard/overrides/react-native-keyboard-controller/KeyboardController.tsx +470 -0
  138. package/plugins/keyboard/overrides/react-native-keyboard-controller/overrides.ts +9 -0
  139. package/plugins/keyboard/plugin.ts +13 -0
  140. package/plugins/keyboard/shell.tsx +133 -0
  141. package/plugins/keyboard/state.ts +92 -0
  142. package/plugins/keyboard/suggestions.ts +63 -0
  143. package/plugins/keyboard/taps.ts +77 -0
  144. package/plugins/keyboard/typing.ts +112 -0
  145. package/plugins/locale/app.ts +232 -0
  146. package/plugins/locale/locale.ts +143 -0
  147. package/plugins/locale/overrides/expo-localization/ExpoLocalization.ts +41 -0
  148. package/plugins/locale/overrides/expo-localization/overrides.ts +9 -0
  149. package/plugins/locale/plugin.ts +9 -0
  150. package/plugins/locale/shell.tsx +147 -0
  151. package/plugins/locale/state.ts +36 -0
  152. package/plugins/location/geo.ts +56 -0
  153. package/plugins/location/overrides/expo-location/ExpoLocation.ts +235 -0
  154. package/plugins/location/overrides/expo-location/overrides.ts +11 -0
  155. package/plugins/location/places.ts +38 -0
  156. package/plugins/location/plugin.ts +8 -0
  157. package/plugins/location/shell.tsx +188 -0
  158. package/plugins/location/state.ts +51 -0
  159. package/plugins/motion/overrides/expo-sensors/DeviceSensor.ts +169 -0
  160. package/plugins/motion/overrides/expo-sensors/ExponentPedometer.ts +54 -0
  161. package/plugins/motion/overrides/expo-sensors/overrides.ts +14 -0
  162. package/plugins/motion/plugin.ts +8 -0
  163. package/plugins/motion/sensors.ts +116 -0
  164. package/plugins/motion/shell.tsx +136 -0
  165. package/plugins/motion/state.ts +46 -0
  166. package/plugins/network/app.ts +400 -0
  167. package/plugins/network/overrides/expo-network/ExpoNetwork.ts +51 -0
  168. package/plugins/network/overrides/expo-network/overrides.ts +9 -0
  169. package/plugins/network/plugin.ts +8 -0
  170. package/plugins/network/shell.tsx +67 -0
  171. package/plugins/network/state.ts +29 -0
  172. package/plugins/notifications/center.ts +255 -0
  173. package/plugins/notifications/content.ts +36 -0
  174. package/plugins/notifications/overrides/expo-notifications/NotificationsModule.ts +175 -0
  175. package/plugins/notifications/overrides/expo-notifications/channels.ts +108 -0
  176. package/plugins/notifications/overrides/expo-notifications/getDevicePushTokenAsync.ts +19 -0
  177. package/plugins/notifications/overrides/expo-notifications/getExpoPushTokenAsync.ts +16 -0
  178. package/plugins/notifications/overrides/expo-notifications/overrides.ts +36 -0
  179. package/plugins/notifications/plugin.ts +8 -0
  180. package/plugins/notifications/shell.tsx +192 -0
  181. package/plugins/notifications/state.ts +56 -0
  182. package/plugins/notifications/tokens.ts +47 -0
  183. package/plugins/notifications/trigger.ts +107 -0
  184. package/plugins/permissions/plugin.ts +6 -0
  185. package/plugins/permissions/shell.tsx +50 -0
  186. package/plugins/permissions/state.ts +38 -0
  187. package/plugins/photos/appLibrary.ts +114 -0
  188. package/plugins/photos/library.ts +322 -0
  189. package/plugins/photos/overrides/expo-image-picker/ExponentImagePicker.ts +153 -0
  190. package/plugins/photos/overrides/expo-image-picker/overrides.ts +13 -0
  191. package/plugins/photos/overrides/expo-media-library/ExpoMediaLibrary.ts +235 -0
  192. package/plugins/photos/overrides/expo-media-library/NativeMediaLibraryModule.ts +318 -0
  193. package/plugins/photos/overrides/expo-media-library/overrides.ts +19 -0
  194. package/plugins/photos/plugin.ts +8 -0
  195. package/plugins/photos/samples.ts +367 -0
  196. package/plugins/photos/shell.tsx +164 -0
  197. package/plugins/photos/state.ts +88 -0
  198. package/plugins/storage/files.ts +351 -0
  199. package/plugins/storage/overrides/expo-file-system/ExpoFileSystem.ts +770 -0
  200. package/plugins/storage/overrides/expo-file-system/ExponentFileSystem.ts +196 -0
  201. package/plugins/storage/overrides/expo-file-system/overrides.ts +13 -0
  202. package/plugins/storage/overrides/expo-secure-store/ExpoSecureStore.ts +75 -0
  203. package/plugins/storage/overrides/expo-secure-store/overrides.ts +9 -0
  204. package/plugins/storage/plugin.ts +8 -0
  205. package/plugins/storage/reset.ts +136 -0
  206. package/plugins/storage/secure.ts +71 -0
  207. package/plugins/storage/shell.tsx +365 -0
  208. package/plugins/storage/state.ts +13 -0
  209. package/src/client/app/appDocument.ts +129 -0
  210. package/src/client/app/appFocus.ts +97 -0
  211. package/src/client/app/console.ts +118 -0
  212. package/src/client/app/fonts.ts +76 -0
  213. package/src/client/app/main.tsx +99 -0
  214. package/src/client/app/routeContext.ts +45 -0
  215. package/src/client/app/touch.ts +640 -0
  216. package/src/client/entry.ts +20 -0
  217. package/src/client/modules.d.ts +8 -0
  218. package/src/client/react-native/app.ts +57 -0
  219. package/src/client/react-native/deep.ts +13 -0
  220. package/src/client/react-native/keyboard.tsx +192 -0
  221. package/src/client/react-native/library.ts +256 -0
  222. package/src/client/shell/Cookies.tsx +95 -0
  223. package/src/client/shell/LogDrawer.tsx +415 -0
  224. package/src/client/shell/PhotoPicker.tsx +174 -0
  225. package/src/client/shell/PluginOverlays.tsx +42 -0
  226. package/src/client/shell/PluginPanels.tsx +82 -0
  227. package/src/client/shell/ResetApp.tsx +87 -0
  228. package/src/client/shell/Resizer.tsx +99 -0
  229. package/src/client/shell/Shell.tsx +531 -0
  230. package/src/client/shell/SystemBars.tsx +376 -0
  231. package/src/client/shell/SystemCamera.tsx +181 -0
  232. package/src/client/shell/SystemOverlay.tsx +422 -0
  233. package/src/client/shell/SystemSheets.tsx +462 -0
  234. package/src/client/shell/backdrop.ts +229 -0
  235. package/src/client/shell/control.ts +91 -0
  236. package/src/client/shell/events.ts +226 -0
  237. package/src/client/shell/geometry.ts +68 -0
  238. package/src/client/shell/host.ts +492 -0
  239. package/src/client/shell/icons.tsx +34 -0
  240. package/src/client/shell/logFeed.ts +102 -0
  241. package/src/client/shell/main.tsx +22 -0
  242. package/src/client/shell/permissionCopy.ts +169 -0
  243. package/src/client/shell/plugins.ts +266 -0
  244. package/src/client/shell/popout.ts +185 -0
  245. package/src/client/shell/popover.ts +27 -0
  246. package/src/client/shell/shell.css +878 -0
  247. package/src/client/shell/statusTime.ts +31 -0
  248. package/src/client/shell/tooltips.ts +104 -0
  249. package/src/client/virtual.d.ts +23 -0
  250. package/src/devices/catalog.ts +223 -0
  251. package/src/devices/types.ts +83 -0
  252. package/src/node/appInfo.ts +188 -0
  253. package/src/node/appSource.ts +140 -0
  254. package/src/node/config.ts +180 -0
  255. package/src/node/control.ts +144 -0
  256. package/src/node/doctor.ts +199 -0
  257. package/src/node/events/cli.ts +206 -0
  258. package/src/node/events/shared.ts +238 -0
  259. package/src/node/events/store.ts +266 -0
  260. package/src/node/fonts.ts +377 -0
  261. package/src/node/index.ts +5 -0
  262. package/src/node/overrides/define.ts +56 -0
  263. package/src/node/overrides/packages.ts +136 -0
  264. package/src/node/overrides/platformPatch.ts +56 -0
  265. package/src/node/overrides/plugin.ts +169 -0
  266. package/src/node/overrides/registry.ts +258 -0
  267. package/src/node/paths.ts +18 -0
  268. package/src/node/platform.ts +171 -0
  269. package/src/node/plugins.ts +98 -0
  270. package/src/node/proxy.ts +421 -0
  271. package/src/node/server.ts +254 -0
  272. package/src/node/worklets.ts +86 -0
  273. package/src/plugin/index.ts +33 -0
  274. package/src/plugin/types.ts +127 -0
  275. package/src/plugin/ui.tsx +562 -0
  276. package/src/runtime/clock.ts +112 -0
  277. package/src/runtime/draw.ts +196 -0
  278. package/src/runtime/index.ts +519 -0
  279. package/src/runtime/media.ts +379 -0
  280. package/src/runtime/records.ts +76 -0
  281. package/src/runtime/timezone.ts +81 -0
@@ -0,0 +1,400 @@
1
+ import { getState, plugin } from 'web-sim/runtime'
2
+ import { INITIAL_NETWORK, type NetworkState, online } from './state.ts'
3
+
4
+ /**
5
+ * The app's requests obey the network panel: offline, they fail as React Native's do (`TypeError: Network request
6
+ * failed`); with latency, they wait first. The dev server's own requests are left alone.
7
+ *
8
+ * Each request is logged: `network.request` (debug), then `network.response` (a warning from 400 up) or
9
+ * `network.failed`, all with the request's span. Credentials in headers are always redacted; bodies are kept only
10
+ * with the panel's "Log bodies" (`captureBodies`), text only, the first 64 KB.
11
+ *
12
+ * Cross-origin requests go through the dev server's proxy (`src/node/proxy.ts`), as a phone makes them: no CORS, the
13
+ * headers the app sets, a cookie jar, and `Set-Cookie` readable on the response. The app sees the URL it asked for.
14
+ */
15
+ declare const __WEB_SIM_PROXY__: boolean
16
+ const network = plugin<NetworkState>('network', INITIAL_NETWORK)
17
+
18
+ function isDevServer(url: string): boolean {
19
+ const target = new URL(url, location.href)
20
+ return target.origin === location.origin && /^\/(@|__|node_modules\/)/.test(target.pathname)
21
+ }
22
+
23
+ const PROXY_PATH = '/__web-sim/proxy'
24
+
25
+ /** The proxy's URL for a request, or null for one the browser can make itself (same origin, data:, blob:). */
26
+ function proxyUrl(url: string): string | null {
27
+ if (!__WEB_SIM_PROXY__) {
28
+ return null
29
+ }
30
+ let target: URL
31
+ try {
32
+ target = new URL(url, location.href)
33
+ } catch {
34
+ return null
35
+ }
36
+ if ((target.protocol !== 'http:' && target.protocol !== 'https:') || target.origin === location.origin) {
37
+ return null
38
+ }
39
+ return `${location.origin}${PROXY_PATH}?url=${encodeURIComponent(target.href)}`
40
+ }
41
+
42
+ function proxyHeaders(headers: [string, string][]): Record<string, string> {
43
+ return { 'x-web-sim-headers': JSON.stringify(headers), 'x-web-sim-platform': getState().device.platform }
44
+ }
45
+
46
+ /** The response headers the app sees: the proxy's own taken out, and `Set-Cookie` back in, as React Native gives it. */
47
+ function appHeaders(proxied: Headers): Headers {
48
+ const headers = new Headers(proxied)
49
+ const setCookies = headers.get('x-web-sim-set-cookie')
50
+ headers.delete('x-web-sim-set-cookie')
51
+ headers.delete('x-web-sim-url')
52
+ if (setCookies !== null) {
53
+ for (const cookie of JSON.parse(setCookies) as string[]) {
54
+ // A Headers made in JS can hold Set-Cookie; only a network response's can't.
55
+ headers.append('set-cookie', cookie)
56
+ }
57
+ }
58
+ return headers
59
+ }
60
+
61
+ /** Gives a proxied response the headers and URL of the request the app made. */
62
+ function dress(response: Response, headers: Headers, url: string): Response {
63
+ const clone = response.clone.bind(response)
64
+ Object.defineProperties(response, {
65
+ headers: { value: headers },
66
+ url: { value: url },
67
+ clone: { value: () => dress(clone(), new Headers(headers), url) },
68
+ })
69
+ return response
70
+ }
71
+
72
+ async function proxiedFetch(target: string, input: RequestInfo | URL, init: RequestInit | undefined): Promise<Response> {
73
+ const request = typeof input === 'object' && !(input instanceof URL) ? input : undefined
74
+ const method = (init?.method ?? request?.method ?? 'GET').toUpperCase()
75
+ const headers = [...new Headers(init?.headers ?? request?.headers).entries()]
76
+ let body = init?.body
77
+ if (body === undefined && request !== undefined && method !== 'GET' && method !== 'HEAD') {
78
+ body = await request.arrayBuffer()
79
+ }
80
+ const response = await originalFetch(target, {
81
+ method,
82
+ headers: proxyHeaders(headers),
83
+ body,
84
+ signal: init?.signal ?? request?.signal,
85
+ ...(body instanceof ReadableStream ? { duplex: 'half' } : {}),
86
+ } as RequestInit)
87
+ if (response.headers.has('x-web-sim-proxy-error')) {
88
+ // What React Native's fetch throws when it can't reach the server; the log has the reason.
89
+ throw Object.assign(new TypeError('Network request failed'), { proxyReason: await response.text() })
90
+ }
91
+ return dress(response, appHeaders(response.headers), response.headers.get('x-web-sim-url') ?? new URL(target).searchParams.get('url') ?? '')
92
+ }
93
+
94
+ const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
95
+
96
+ const BODY_LIMIT = 64 * 1024
97
+ const REDACTED = new Set(['authorization', 'proxy-authorization', 'cookie', 'set-cookie'])
98
+
99
+ let nextRequest = 1
100
+ const requestSpan = () => `req-${Date.now().toString(36)}-${nextRequest++}`
101
+
102
+ function headerRecord(headers: Iterable<[string, string]>): Record<string, string> {
103
+ const record: Record<string, string> = {}
104
+ for (const [name, value] of headers) {
105
+ record[name.toLowerCase()] = REDACTED.has(name.toLowerCase()) ? '<redacted>' : value
106
+ }
107
+ return record
108
+ }
109
+
110
+ function parseRawHeaders(raw: string): Record<string, string> {
111
+ return headerRecord(parseHeaderLines(raw))
112
+ }
113
+
114
+ function textual(contentType: string | null | undefined): boolean {
115
+ if (contentType === null || contentType === undefined || contentType === '') {
116
+ return true
117
+ }
118
+ const type = contentType.toLowerCase()
119
+ if (type.startsWith('text/event-stream')) {
120
+ return false
121
+ }
122
+ return type.startsWith('text/') || /json|xml|javascript|x-www-form-urlencoded|graphql/.test(type)
123
+ }
124
+
125
+ function cut(text: string): string {
126
+ return text.length > BODY_LIMIT ? `${text.slice(0, BODY_LIMIT)}… <${Math.round(text.length / 1024)} KB in all>` : text
127
+ }
128
+
129
+ /** A request body as text, or a note of what it was when it is not text. */
130
+ function requestBody(body: unknown): string | undefined {
131
+ if (body === undefined || body === null) {
132
+ return undefined
133
+ }
134
+ if (typeof body === 'string') {
135
+ return cut(body)
136
+ }
137
+ const tag = Object.prototype.toString.call(body).slice(8, -1)
138
+ if (tag === 'URLSearchParams') {
139
+ return cut(String(body))
140
+ }
141
+ const size = (body as { size?: number; byteLength?: number }).size ?? (body as { byteLength?: number }).byteLength
142
+ return `<${tag}${size === undefined ? '' : ` ${size} bytes`}>`
143
+ }
144
+
145
+ function shortUrl(url: string): string {
146
+ try {
147
+ const target = new URL(url, location.href)
148
+ return target.origin === location.origin ? target.pathname + target.search : target.href
149
+ } catch {
150
+ return url
151
+ }
152
+ }
153
+
154
+ type Started = { span: string; method: string; url: string; start: number; latency: number }
155
+
156
+ function logRequest(method: string, url: string, headers: Record<string, string>, body: unknown): Started {
157
+ const state = network.get()
158
+ const started: Started = { span: requestSpan(), method, url, start: performance.now(), latency: state.latency }
159
+ network.log(
160
+ 'request',
161
+ `${method} ${shortUrl(url)}`,
162
+ {
163
+ method,
164
+ url,
165
+ headers,
166
+ ...(state.captureBodies ? { body: requestBody(body) } : {}),
167
+ ...(state.latency > 0 ? { latency: state.latency } : {}),
168
+ ...(online(state) ? {} : { offline: true }),
169
+ },
170
+ { level: 'debug', span: started.span, maxString: BODY_LIMIT + 100 },
171
+ )
172
+ return started
173
+ }
174
+
175
+ function logResponse(started: Started, status: number, statusText: string, headers: Record<string, string>, body: string | undefined) {
176
+ const duration = Math.round(performance.now() - started.start)
177
+ const length = headers['content-length']
178
+ network.log(
179
+ 'response',
180
+ `${started.method} ${shortUrl(started.url)} → ${status} (${duration} ms)`,
181
+ {
182
+ method: started.method,
183
+ url: started.url,
184
+ status,
185
+ statusText,
186
+ duration,
187
+ headers,
188
+ ...(length === undefined ? {} : { size: Number(length) }),
189
+ ...(body === undefined ? {} : { body }),
190
+ ...(started.latency > 0 ? { latency: started.latency } : {}),
191
+ },
192
+ { level: status >= 400 ? 'warn' : 'info', span: started.span, maxString: BODY_LIMIT + 100 },
193
+ )
194
+ }
195
+
196
+ function logFailure(started: Started, reason: string, offline: boolean) {
197
+ const duration = Math.round(performance.now() - started.start)
198
+ network.log(
199
+ 'failed',
200
+ `${started.method} ${shortUrl(started.url)} failed: ${reason}${offline ? ' (offline in the network panel)' : ''} (${duration} ms)`,
201
+ { method: started.method, url: started.url, reason, offline, duration },
202
+ { level: offline ? 'warn' : 'error', span: started.span },
203
+ )
204
+ }
205
+
206
+ const originalFetch = window.fetch.bind(window)
207
+ window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
208
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
209
+ if (isDevServer(url)) {
210
+ return originalFetch(input, init)
211
+ }
212
+ const request = typeof input === 'object' && !(input instanceof URL) ? input : undefined
213
+ const method = (init?.method ?? request?.method ?? 'GET').toUpperCase()
214
+ const headers = headerRecord(new Headers(init?.headers ?? request?.headers))
215
+ const started = logRequest(method, url, headers, init?.body)
216
+ const { latency } = network.get()
217
+ if (latency > 0) {
218
+ await wait(latency)
219
+ }
220
+ if (!online(network.get())) {
221
+ logFailure(started, 'Network request failed', true)
222
+ throw new TypeError('Network request failed')
223
+ }
224
+ let response: Response
225
+ try {
226
+ const target = proxyUrl(url)
227
+ response = await (target === null ? originalFetch(input, init) : proxiedFetch(target, input, init))
228
+ } catch (error) {
229
+ if (!(error instanceof DOMException && error.name === 'AbortError')) {
230
+ const reason = (error as { proxyReason?: string }).proxyReason ?? (error instanceof Error ? error.message : String(error))
231
+ logFailure(started, reason, false)
232
+ } else {
233
+ logFailure(started, 'aborted', false)
234
+ }
235
+ throw error
236
+ }
237
+ const responseHeaders = headerRecord(response.headers)
238
+ if (network.get().captureBodies && textual(response.headers.get('content-type'))) {
239
+ // Read from a copy, after the app has its response; the event waits for the body.
240
+ response
241
+ .clone()
242
+ .text()
243
+ .then(
244
+ (text) => logResponse(started, response.status, response.statusText, responseHeaders, cut(text)),
245
+ () => logResponse(started, response.status, response.statusText, responseHeaders, undefined),
246
+ )
247
+ } else {
248
+ logResponse(started, response.status, response.statusText, responseHeaders, undefined)
249
+ }
250
+ return response
251
+ }
252
+
253
+ const send = XMLHttpRequest.prototype.send
254
+ const open = XMLHttpRequest.prototype.open
255
+ const setRequestHeader = XMLHttpRequest.prototype.setRequestHeader
256
+ const getResponseHeader = XMLHttpRequest.prototype.getResponseHeader
257
+ const getAllResponseHeaders = XMLHttpRequest.prototype.getAllResponseHeaders
258
+ const requests = new WeakMap<XMLHttpRequest, { method: string; url: string; headers: [string, string][]; proxied: boolean }>()
259
+
260
+ XMLHttpRequest.prototype.open = function (this: XMLHttpRequest, ...args: Parameters<XMLHttpRequest['open']>) {
261
+ const url = new URL(String(args[1]), location.href).href
262
+ const target = proxyUrl(url)
263
+ requests.set(this, { method: String(args[0]).toUpperCase(), url: String(args[1]), headers: [], proxied: target !== null })
264
+ if (target === null) {
265
+ return open.apply(this, args)
266
+ }
267
+ const xhr = this
268
+ // The app reads the response as the server sent it, with Set-Cookie, from the URL it asked for.
269
+ Object.defineProperties(xhr, {
270
+ responseURL: { configurable: true, get: () => getResponseHeader.call(xhr, 'x-web-sim-url') ?? url },
271
+ getAllResponseHeaders: {
272
+ configurable: true,
273
+ value: () => {
274
+ const raw = getAllResponseHeaders.call(xhr)
275
+ if (raw === '') {
276
+ return raw
277
+ }
278
+ const lines: string[] = []
279
+ appHeaders(new Headers(parseHeaderLines(raw))).forEach((value, name) => lines.push(`${name}: ${value}`))
280
+ return `${lines.join('\r\n')}\r\n`
281
+ },
282
+ },
283
+ getResponseHeader: {
284
+ configurable: true,
285
+ value: (name: string) => (getAllResponseHeaders.call(xhr) === '' ? null : appHeaders(new Headers(parseHeaderLines(getAllResponseHeaders.call(xhr)))).get(name)),
286
+ },
287
+ })
288
+ return open.call(this, args[0], target, args[2] ?? true, args[3], args[4])
289
+ } as XMLHttpRequest['open']
290
+
291
+ XMLHttpRequest.prototype.setRequestHeader = function (this: XMLHttpRequest, name: string, value: string) {
292
+ const request = requests.get(this)
293
+ request?.headers.push([name, value])
294
+ // A proxied request's headers go to the proxy as one, so the ones a browser forbids (Cookie, User-Agent) get there.
295
+ return request?.proxied ? undefined : setRequestHeader.call(this, name, value)
296
+ }
297
+
298
+ function parseHeaderLines(raw: string): [string, string][] {
299
+ return raw
300
+ .trim()
301
+ .split(/[\r\n]+/)
302
+ .filter(Boolean)
303
+ .map((line) => {
304
+ const at = line.indexOf(':')
305
+ return [line.slice(0, at).trim(), line.slice(at + 1).trim()]
306
+ })
307
+ }
308
+
309
+ XMLHttpRequest.prototype.send = function (this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null) {
310
+ const request = requests.get(this) ?? { method: 'GET', url: '', headers: [] as [string, string][], proxied: false }
311
+ if (isDevServer(request.url)) {
312
+ return send.call(this, body)
313
+ }
314
+ const started = logRequest(request.method, request.url, headerRecord(request.headers), body)
315
+ if (request.proxied) {
316
+ for (const [name, value] of Object.entries(proxyHeaders(request.headers))) {
317
+ setRequestHeader.call(this, name, value)
318
+ }
319
+ }
320
+ let offline = false
321
+ this.addEventListener('loadend', () => {
322
+ if (this.status === 0) {
323
+ logFailure(started, offline ? 'Network request failed' : 'no response', offline)
324
+ return
325
+ }
326
+ const headers = parseRawHeaders(this.getAllResponseHeaders())
327
+ let text: string | undefined
328
+ if (network.get().captureBodies && textual(headers['content-type']) && (this.responseType === '' || this.responseType === 'text')) {
329
+ text = cut(this.responseText)
330
+ }
331
+ logResponse(started, this.status, this.statusText, headers, text)
332
+ })
333
+ const go = () => {
334
+ if (online(network.get())) {
335
+ send.call(this, body)
336
+ } else {
337
+ // What a failed connection looks like to XHR: status 0, then `error`.
338
+ offline = true
339
+ this.dispatchEvent(new ProgressEvent('error'))
340
+ this.dispatchEvent(new ProgressEvent('loadend'))
341
+ }
342
+ }
343
+ const { latency } = network.get()
344
+ if (latency > 0) {
345
+ setTimeout(go, latency)
346
+ } else {
347
+ go()
348
+ }
349
+ }
350
+
351
+ const BrowserWebSocket = window.WebSocket
352
+ const WEBSOCKET_PATH = '/__web-sim/websocket'
353
+
354
+ /**
355
+ * React Native's WebSocket: one to another server goes through the dev server (`src/node/proxy.ts`), which opens it
356
+ * as the phone would, without the page's `Origin`, with the phone's cookies and the headers given as the third
357
+ * argument (`{ headers }`, which React Native accepts and browsers don't). Offline in the network panel, it fails as
358
+ * a phone's does: `error`, then `close`. Each socket is logged as `network.websocket` and `network.websocket-closed`.
359
+ */
360
+ class SimWebSocket extends BrowserWebSocket {
361
+ private readonly appUrl: string
362
+
363
+ constructor(url: string | URL, protocols?: string | string[], options?: { headers?: Record<string, string> }) {
364
+ const target = new URL(String(url), location.href)
365
+ const proxied = __WEB_SIM_PROXY__ && target.host !== location.host && (target.protocol === 'ws:' || target.protocol === 'wss:')
366
+ const isOnline = online(network.get())
367
+ let socketUrl = target.href
368
+ if (proxied || !isOnline) {
369
+ const query = new URLSearchParams({ url: target.href, platform: getState().device.platform })
370
+ if (options?.headers !== undefined) {
371
+ query.set('headers', JSON.stringify(options.headers))
372
+ }
373
+ if (!isOnline) {
374
+ query.set('offline', '1')
375
+ }
376
+ socketUrl = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}${WEBSOCKET_PATH}?${query}`
377
+ }
378
+ super(socketUrl, protocols)
379
+ this.appUrl = target.href
380
+ const span = requestSpan()
381
+ const start = performance.now()
382
+ network.log('websocket', `WebSocket ${shortUrl(target.href)}`, { url: target.href, ...(isOnline ? {} : { offline: true }) }, { level: 'debug', span })
383
+ this.addEventListener('open', () => network.log('websocket-open', `WebSocket ${shortUrl(target.href)} open`, { url: target.href }, { span }))
384
+ this.addEventListener('close', (event) => {
385
+ const duration = Math.round(performance.now() - start)
386
+ network.log(
387
+ 'websocket-closed',
388
+ `WebSocket ${shortUrl(target.href)} closed: ${event.code}${event.reason ? ` ${event.reason}` : ''}${isOnline ? '' : ' (offline in the network panel)'} (${duration} ms)`,
389
+ { url: target.href, code: event.code, reason: event.reason, clean: event.wasClean, duration },
390
+ { level: event.code === 1000 || event.code === 1001 ? 'info' : 'warn', span },
391
+ )
392
+ })
393
+ }
394
+
395
+ get url(): string {
396
+ return this.appUrl
397
+ }
398
+ }
399
+
400
+ window.WebSocket = SimWebSocket as unknown as typeof WebSocket
@@ -0,0 +1,51 @@
1
+ import { NativeModule, registerWebModule } from 'expo'
2
+ import { platform, plugin } from 'web-sim/runtime'
3
+ import { INITIAL_NETWORK, type NetworkState, online } from '../../state.ts'
4
+
5
+ const EVENT = 'onNetworkStateChanged'
6
+
7
+ const TYPES = { wifi: 'WIFI', cellular: 'CELLULAR', none: 'NONE' } as const
8
+
9
+ const network = () => plugin<NetworkState>('network', INITIAL_NETWORK)
10
+
11
+ function report(state: NetworkState) {
12
+ const connected = state.connection !== 'none' && !state.airplaneMode
13
+ return { type: connected ? TYPES[state.connection] : 'NONE', isConnected: connected, isInternetReachable: online(state) }
14
+ }
15
+
16
+ /** `ExpoNetwork`, reporting the network panel. */
17
+ class ExpoNetworkModule extends NativeModule<{ [EVENT]: (state: ReturnType<typeof report>) => void }> {
18
+ private stop: (() => void) | null = null
19
+
20
+ async getNetworkStateAsync() {
21
+ return report(network().get())
22
+ }
23
+
24
+ async getIpAddressAsync() {
25
+ const state = network().get()
26
+ return state.connection === 'none' || state.airplaneMode ? '0.0.0.0' : state.ipAddress
27
+ }
28
+
29
+ startObserving() {
30
+ this.stop ??= network().watch((next, previous) => {
31
+ const [a, b] = [report(next), report(previous)]
32
+ if (a.type !== b.type || a.isConnected !== b.isConnected || a.isInternetReachable !== b.isInternetReachable) {
33
+ this.emit(EVENT, a)
34
+ }
35
+ })
36
+ }
37
+
38
+ stopObserving() {
39
+ this.stop?.()
40
+ this.stop = null
41
+ }
42
+ }
43
+
44
+ /** Android only, as on the devices: the JS layer throws `UnavailabilityError` on iOS. */
45
+ class ExpoNetworkAndroidModule extends ExpoNetworkModule {
46
+ async isAirplaneModeEnabledAsync() {
47
+ return network().get().airplaneMode
48
+ }
49
+ }
50
+
51
+ export default registerWebModule(platform() === 'android' ? ExpoNetworkAndroidModule : ExpoNetworkModule, 'ExpoNetwork')
@@ -0,0 +1,9 @@
1
+ import { defineOverrides } from '../../../../src/node/overrides/define.ts'
2
+
3
+ export default defineOverrides('expo-network', [
4
+ {
5
+ versions: '>=58 <59',
6
+ note: 'reports the network panel; its changes reach the listeners',
7
+ files: { 'build/ExpoNetwork.web.js': './ExpoNetwork.ts' },
8
+ },
9
+ ])
@@ -0,0 +1,8 @@
1
+ import { definePlugin } from '../../src/node/plugins.ts'
2
+
3
+ export default definePlugin({
4
+ name: 'network',
5
+ overrides: './overrides',
6
+ shell: './shell.tsx',
7
+ app: './app.ts',
8
+ })
@@ -0,0 +1,67 @@
1
+ import { WifiHighIcon } from '@phosphor-icons/react'
2
+ import { defineShellPlugin, Field, Segmented, Slider, TextField, Toggle } from 'web-sim/shell'
3
+ import { INITIAL_NETWORK, type NetworkState } from './state.ts'
4
+
5
+ /**
6
+ * The dev server's cookie jar, which the proxy keeps for the app's requests (see `src/node/proxy.ts`). The toolbar's
7
+ * cookie button shows it; these actions are its CLI half, and its clears go through `clearCookies` to be logged.
8
+ */
9
+ const COOKIES_PATH = '/__web-sim/cookies'
10
+
11
+ async function cookieJar(method: 'GET' | 'DELETE', domain?: string): Promise<unknown> {
12
+ const query = domain === undefined ? '' : `?domain=${encodeURIComponent(domain)}`
13
+ const response = await fetch(`${COOKIES_PATH}${query}`, { method })
14
+ if (!response.ok || !(response.headers.get('content-type') ?? '').includes('json')) {
15
+ throw new Error('No cookie jar: the network proxy is off (proxy: false in the config)')
16
+ }
17
+ return response.json()
18
+ }
19
+
20
+ const plural = (n: number) => `${n} cookie${n === 1 ? '' : 's'}`
21
+
22
+ export default defineShellPlugin<NetworkState>({
23
+ id: 'network',
24
+ title: 'Network',
25
+ icon: WifiHighIcon,
26
+ initialState: INITIAL_NETWORK,
27
+ statusBar: (state) => ({
28
+ connection: state.airplaneMode && state.connection === 'cellular' ? 'none' : state.connection,
29
+ airplaneMode: state.airplaneMode,
30
+ }),
31
+ actions: {
32
+ offline: (context) => context.set({ connection: 'none' }),
33
+ online: (context) => context.set({ connection: 'wifi', airplaneMode: false, internetReachable: true }),
34
+ /** The phone's cookies, by domain: names, paths and expiry, not values. */
35
+ cookies: () => cookieJar('GET'),
36
+ /** Empties the phone's cookie jar, or one domain's cookies with `{"domain": "api.example.com"}`. */
37
+ clearCookies: async (context, args) => {
38
+ const domain = (args as { domain?: string } | undefined)?.domain
39
+ const { cleared } = (await cookieJar('DELETE', domain)) as { cleared: number }
40
+ context.log('cookies.cleared', `Cleared ${plural(cleared)}${domain === undefined ? '' : ` for ${domain}`}`, { domain: domain ?? null, cleared })
41
+ return { cleared }
42
+ },
43
+ },
44
+ Panel: ({ state, set }) => (
45
+ <>
46
+ <Segmented
47
+ label="Connection"
48
+ value={state.connection}
49
+ options={[
50
+ { value: 'wifi', label: 'Wi-Fi' },
51
+ { value: 'cellular', label: 'Cellular' },
52
+ { value: 'none', label: 'None' },
53
+ ]}
54
+ onChange={(connection) => set({ connection })}
55
+ />
56
+ <Toggle label="Internet reachable" checked={state.internetReachable} onChange={(internetReachable) => set({ internetReachable })} />
57
+ <Toggle label="Airplane mode" checked={state.airplaneMode} onChange={(airplaneMode) => set({ airplaneMode })} />
58
+ <Field label="Latency" value={state.latency === 0 ? 'None' : `${state.latency} ms`}>
59
+ <Slider label="Latency" value={state.latency} min={0} max={3000} step={50} onChange={(latency) => set({ latency })} />
60
+ </Field>
61
+ <Field label="IP address">
62
+ <TextField label="IP address" value={state.ipAddress} onChange={(ipAddress) => set({ ipAddress })} />
63
+ </Field>
64
+ <Toggle label="Log bodies" checked={state.captureBodies} onChange={(captureBodies) => set({ captureBodies })} />
65
+ </>
66
+ ),
67
+ })
@@ -0,0 +1,29 @@
1
+ /** The phone's connection, set in the panel. `expo-network` reports it, and the app's requests obey it. */
2
+ export type NetworkState = {
3
+ connection: 'wifi' | 'cellular' | 'none'
4
+ /** Connected, but the internet is out of reach: a captive portal, a dead router. */
5
+ internetReachable: boolean
6
+ airplaneMode: boolean
7
+ /** Added to every request the app makes, in milliseconds. */
8
+ latency: number
9
+ ipAddress: string
10
+ /**
11
+ * Whether the event log keeps request and response bodies (text only, the first 64 KB). Off by default: the log is
12
+ * kept on disk, and a body can hold anything.
13
+ */
14
+ captureBodies: boolean
15
+ }
16
+
17
+ export const INITIAL_NETWORK: NetworkState = {
18
+ connection: 'wifi',
19
+ internetReachable: true,
20
+ airplaneMode: false,
21
+ latency: 0,
22
+ ipAddress: '192.168.1.42',
23
+ captureBodies: false,
24
+ }
25
+
26
+ /** Whether a request can get out: a connection, not airplane mode, and the internet reachable. */
27
+ export function online(state: NetworkState): boolean {
28
+ return state.connection !== 'none' && !state.airplaneMode && state.internetReachable
29
+ }