@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,206 @@
1
+ import { EVENTS_PATH } from './store.ts'
2
+ import { type Actor, type EventQuery, type Level, parseDuration, queryToParams, type SimEvent } from './shared.ts'
3
+
4
+ /** The options `web-sim logs` and `web-sim wait` share, as `parseArgs` gives them. */
5
+ export type LogOptions = {
6
+ level?: string
7
+ since?: string
8
+ until?: string
9
+ run?: string
10
+ actor?: string
11
+ span?: string
12
+ where?: string[]
13
+ text?: string
14
+ limit?: string
15
+ json?: boolean
16
+ follow?: boolean
17
+ kinds?: boolean
18
+ clear?: boolean
19
+ timeout?: string
20
+ }
21
+
22
+ class CliError extends Error {}
23
+
24
+ function query(kinds: string[], options: LogOptions, defaults: { level?: Level; limit?: number }): EventQuery {
25
+ const run = options.run
26
+ return {
27
+ kind: kinds.length > 0 ? kinds.flatMap((kind) => kind.split(',')) : undefined,
28
+ level: (options.level as Level | undefined) ?? defaults.level,
29
+ actor: options.actor?.split(',') as Actor[] | undefined,
30
+ run: run === undefined ? undefined : run === 'current' || run === 'previous' ? run : Number(run),
31
+ span: options.span,
32
+ since: options.since,
33
+ until: options.until,
34
+ text: options.text,
35
+ where: options.where,
36
+ limit: options.limit !== undefined ? Number(options.limit) : defaults.limit,
37
+ }
38
+ }
39
+
40
+ async function request(base: string, path: string, init?: RequestInit): Promise<Response> {
41
+ let response: Response
42
+ try {
43
+ response = await fetch(`${base}${EVENTS_PATH}${path}`, init)
44
+ } catch {
45
+ throw new CliError(`No web-sim dev server at ${base}. Start one with 'web-sim dev', or pass --port.`)
46
+ }
47
+ if (!response.ok) {
48
+ const body = (await response.json().catch(() => ({}))) as { error?: string }
49
+ throw new CliError(body.error ?? `${response.status} ${response.statusText}`)
50
+ }
51
+ return response
52
+ }
53
+
54
+ async function fetchEvents(base: string, eventQuery: EventQuery): Promise<SimEvent[]> {
55
+ const response = await request(base, `?${queryToParams(eventQuery)}`)
56
+ return ((await response.json()) as { events: SimEvent[] }).events
57
+ }
58
+
59
+ /**
60
+ * Reads a stream of events: `onEvent` for each, `onLive` once the history is through. Resolves when the stream ends
61
+ * or `signal` aborts.
62
+ */
63
+ async function streamEvents(base: string, eventQuery: EventQuery, onEvent: (event: SimEvent) => void, onLive: () => void, signal: AbortSignal): Promise<void> {
64
+ let response: Response
65
+ try {
66
+ response = await request(base, `/stream?${queryToParams(eventQuery)}`, { signal })
67
+ } catch (error) {
68
+ if (signal.aborted) {
69
+ return
70
+ }
71
+ throw error
72
+ }
73
+ const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader()
74
+ let buffer = ''
75
+ try {
76
+ for (;;) {
77
+ const { value, done } = await reader.read()
78
+ if (done) {
79
+ throw new CliError('The dev server stopped.')
80
+ }
81
+ buffer += value
82
+ let end: number
83
+ while ((end = buffer.indexOf('\n\n')) !== -1) {
84
+ const message = buffer.slice(0, end)
85
+ buffer = buffer.slice(end + 2)
86
+ const lines = message.split('\n')
87
+ const type = lines.find((line) => line.startsWith('event: '))?.slice(7) ?? 'message'
88
+ const data = lines.filter((line) => line.startsWith('data: ')).map((line) => line.slice(6)).join('\n')
89
+ if (type === 'live') {
90
+ onLive()
91
+ } else if (data !== '') {
92
+ onEvent(JSON.parse(data) as SimEvent)
93
+ }
94
+ }
95
+ }
96
+ } catch (error) {
97
+ if (signal.aborted) {
98
+ return
99
+ }
100
+ throw error
101
+ }
102
+ }
103
+
104
+ const color = process.stdout.isTTY && process.env.NO_COLOR === undefined
105
+ const paint = (code: string, text: string) => (color ? `\x1b[${code}m${text}\x1b[0m` : text)
106
+ const LEVEL_COLOR: Record<Level, string> = { debug: '2', info: '0', warn: '33', error: '31' }
107
+
108
+ function clock(time: number): string {
109
+ const date = new Date(time)
110
+ const pad = (value: number, size = 2) => String(value).padStart(size, '0')
111
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
112
+ }
113
+
114
+ /** One event as a line: time, kind, summary, and who caused it when that was not the app. */
115
+ export function formatEvent(event: SimEvent): string {
116
+ if (event.kind === 'sim.launch') {
117
+ return paint('36', `── run ${event.run} ${'─'.repeat(4)} ${clock(event.time)} ${event.summary}`)
118
+ }
119
+ const actor = event.actor === 'app' ? '' : ` ${paint('35', `[${event.actor}]`)}`
120
+ const line = `${paint('2', clock(event.time))} ${event.kind.padEnd(20)} ${event.summary}`
121
+ return event.level === 'info' ? `${line}${actor}` : `${paint(LEVEL_COLOR[event.level], line)}${actor}`
122
+ }
123
+
124
+ function print(event: SimEvent, json: boolean): void {
125
+ console.log(json ? JSON.stringify(event) : formatEvent(event))
126
+ }
127
+
128
+ /**
129
+ * `web-sim logs [kind...]`: the newest events, oldest first. Without a kind or a span, debug events are left out;
130
+ * naming a kind (`web-sim logs battery`) or a span shows every level.
131
+ */
132
+ export async function logsCommand(base: string, kinds: string[], options: LogOptions): Promise<void> {
133
+ if (options.clear) {
134
+ await request(base, '', { method: 'DELETE' })
135
+ console.log('Cleared the event log.')
136
+ return
137
+ }
138
+ if (options.kinds) {
139
+ const response = await request(base, '/kinds')
140
+ const { kinds: seen } = (await response.json()) as { kinds: { kind: string; count: number; last: number }[] }
141
+ if (options.json) {
142
+ console.log(JSON.stringify(seen, null, 2))
143
+ } else {
144
+ seen.forEach(({ kind, count, last }) => console.log(`${kind.padEnd(28)} ${String(count).padStart(6)} last ${clock(last)}`))
145
+ }
146
+ return
147
+ }
148
+ const level: Level | undefined = kinds.length === 0 && options.span === undefined ? 'info' : undefined
149
+ const eventQuery = query(kinds, options, { level, limit: 50 })
150
+ const json = options.json ?? false
151
+ if (!options.follow) {
152
+ ;(await fetchEvents(base, eventQuery)).forEach((event) => print(event, json))
153
+ return
154
+ }
155
+ const controller = new AbortController()
156
+ process.once('SIGINT', () => controller.abort())
157
+ await streamEvents(base, eventQuery, (event) => print(event, json), () => undefined, controller.signal)
158
+ }
159
+
160
+ /**
161
+ * `web-sim wait <kind>`: blocks until a matching event arrives, prints it and exits 0, or exits 1 after the timeout
162
+ * (default 10s). It also takes a match that came after the last CLI command that changed something, so
163
+ * `web-sim run notifications push '{...}' && web-sim wait ui.banner.shown` holds even when the banner beat it.
164
+ * `--since` overrides where it looks back to; `--since now` takes only new events.
165
+ */
166
+ export async function waitCommand(base: string, kinds: string[], options: LogOptions): Promise<boolean> {
167
+ if (kinds.length === 0) {
168
+ throw new CliError('Usage: web-sim wait <kind> [--where path<op>value] [--timeout 10s]')
169
+ }
170
+ const timeout = options.timeout === undefined ? 10_000 : parseDuration(options.timeout)
171
+ if (timeout === undefined) {
172
+ throw new CliError(`'${options.timeout}' is not a duration such as 10s`)
173
+ }
174
+ let since = options.since
175
+ if (since === undefined || since === 'now') {
176
+ const [last] = await fetchEvents(base, { limit: 1 })
177
+ const [command] = since === 'now' ? [] : await fetchEvents(base, { kind: ['cli.command'], level: 'info', limit: 1 })
178
+ since = String(command !== undefined ? command.id : (last?.id ?? 0))
179
+ }
180
+ const eventQuery = { ...query(kinds, { ...options, since }, {}), limit: 1 }
181
+ const controller = new AbortController()
182
+ let found: SimEvent | undefined
183
+ const timer = setTimeout(() => controller.abort(), timeout)
184
+ process.once('SIGINT', () => controller.abort())
185
+ await streamEvents(
186
+ base,
187
+ eventQuery,
188
+ (event) => {
189
+ found ??= event
190
+ controller.abort()
191
+ },
192
+ () => undefined,
193
+ controller.signal,
194
+ )
195
+ clearTimeout(timer)
196
+ if (found === undefined) {
197
+ console.error(`No ${kinds.join(' or ')} event${options.where === undefined ? '' : ` where ${options.where.join(' and ')}`} within ${options.timeout ?? '10s'}.`)
198
+ return false
199
+ }
200
+ print(found, options.json ?? false)
201
+ return true
202
+ }
203
+
204
+ export function isCliError(error: unknown): error is Error {
205
+ return error instanceof CliError
206
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The event log's types and its one filter, shared by the shell (which produces events), the dev server (which keeps
3
+ * them and answers queries) and the CLI. Plain functions only: the shell's bundle and Node both load this file.
4
+ */
5
+
6
+ export type Level = 'debug' | 'info' | 'warn' | 'error'
7
+
8
+ /**
9
+ * Who caused an event: the app's code, the person at the panel or the device, a CLI command or script, or the
10
+ * simulator itself (timers, a plugin's setup, a new run).
11
+ */
12
+ export type Actor = 'app' | 'user' | 'cli' | 'system'
13
+
14
+ export const LEVELS: readonly Level[] = ['debug', 'info', 'warn', 'error']
15
+ export const ACTORS: readonly Actor[] = ['app', 'user', 'cli', 'system']
16
+
17
+ /** One thing that happened in the simulator. */
18
+ export type SimEvent = {
19
+ /** Global and increasing; the dev server assigns it. */
20
+ id: number
21
+ /** Milliseconds since the epoch, on the computer's clock. */
22
+ time: number
23
+ /** Which app launch or reload; the dev server numbers them across tabs. */
24
+ run: number
25
+ /** The shell tab it came from; empty for the dev server's own events (`cli.*`). */
26
+ tab: string
27
+ /** Dotted and source-first: `network.response`, `sim.orientation`, `console.warn`, `battery.state`. */
28
+ kind: string
29
+ level: Level
30
+ actor: Actor
31
+ /** One readable line. */
32
+ summary: string
33
+ data?: unknown
34
+ /** Ties related events: a request, a dialog, a notification, a command or action and what it did. */
35
+ span?: string
36
+ /** The span of the command or action that led to this event. */
37
+ cause?: string
38
+ }
39
+
40
+ /** What a producer gives the log; the rest is stamped on. */
41
+ export type EventInput = {
42
+ kind: string
43
+ summary: string
44
+ level?: Level
45
+ actor?: Actor
46
+ data?: unknown
47
+ span?: string
48
+ cause?: string
49
+ }
50
+
51
+ /** The one filter shape, used by the HTTP endpoints and the CLI. */
52
+ export type EventQuery = {
53
+ /** Kind globs: `network` (that kind and `network.*`), `ui.dialog.*`, `*.state`. */
54
+ kind?: string[]
55
+ /** The lowest level shown. */
56
+ level?: Level
57
+ actor?: Actor[]
58
+ run?: number | 'current' | 'previous'
59
+ /** A span, and every event it caused, and those events' effects in turn. */
60
+ span?: string
61
+ /** An event id, epoch milliseconds, a duration back from now (`30s`, `5m`, `2h`), or `now`. */
62
+ since?: number | string
63
+ until?: number | string
64
+ /** Text in the summary or the data, any case. */
65
+ text?: string
66
+ /** `status>=400`, `url~/api`, `data.method=POST`: a path into the event (or its data), an operator, a value. */
67
+ where?: string[]
68
+ /** The newest this many, oldest first. */
69
+ limit?: number
70
+ }
71
+
72
+ const TOP_LEVEL = new Set(['id', 'time', 'run', 'tab', 'kind', 'level', 'actor', 'summary', 'span', 'cause'])
73
+
74
+ export function levelAtLeast(level: Level, minimum: Level): boolean {
75
+ return LEVELS.indexOf(level) >= LEVELS.indexOf(minimum)
76
+ }
77
+
78
+ /** Whether a kind matches a glob: `network` matches `network` and `network.response`; `*` matches within a dotted kind. */
79
+ export function kindMatches(kind: string, glob: string): boolean {
80
+ if (!glob.includes('*')) {
81
+ return kind === glob || kind.startsWith(`${glob}.`)
82
+ }
83
+ const pattern = glob.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')
84
+ return new RegExp(`^${pattern}$`).test(kind)
85
+ }
86
+
87
+ /** `500ms`, `30s`, `5m`, `2h`, `1d` in milliseconds, or undefined when it is not a duration. */
88
+ export function parseDuration(text: string): number | undefined {
89
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(text.trim())
90
+ if (match === null) {
91
+ return undefined
92
+ }
93
+ const unit = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[match[2] as 'ms' | 's' | 'm' | 'h' | 'd']
94
+ return Number(match[1]) * unit
95
+ }
96
+
97
+ /**
98
+ * A bound on time or id: a number under 10^12 is an event id, a larger one epoch ms; a string is a duration back from
99
+ * `now`, or a number.
100
+ */
101
+ export function parseBound(bound: number | string, now: number): { id: number } | { time: number } {
102
+ if (bound === 'now') {
103
+ return { time: now }
104
+ }
105
+ if (typeof bound === 'string') {
106
+ const duration = parseDuration(bound)
107
+ if (duration !== undefined) {
108
+ return { time: now - duration }
109
+ }
110
+ const number = Number(bound)
111
+ if (bound.trim() === '' || Number.isNaN(number)) {
112
+ throw new Error(`'${bound}' is not an event id, a time or a duration such as 5m`)
113
+ }
114
+ bound = number
115
+ }
116
+ return bound < 1e12 ? { id: bound } : { time: bound }
117
+ }
118
+
119
+ type Where = { path: string[]; op: '=' | '!=' | '>' | '>=' | '<' | '<=' | '~'; value: string }
120
+
121
+ export function parseWhere(text: string): Where {
122
+ const match = /^([\w.$-]+)\s*(>=|<=|!=|=|>|<|~)\s*(.*)$/.exec(text.trim())
123
+ if (match === null) {
124
+ throw new Error(`'${text}' is not path<op>value; the operators are = != > >= < <= ~`)
125
+ }
126
+ const segments = match[1].split('.')
127
+ const path = segments[0] === 'data' ? segments : TOP_LEVEL.has(segments[0]) ? segments : ['data', ...segments]
128
+ return { path, op: match[2] as Where['op'], value: match[3] }
129
+ }
130
+
131
+ function resolve(event: SimEvent, path: string[]): unknown {
132
+ let value: unknown = event
133
+ for (const segment of path) {
134
+ if (value === null || typeof value !== 'object') {
135
+ return undefined
136
+ }
137
+ value = (value as Record<string, unknown>)[segment]
138
+ }
139
+ return value
140
+ }
141
+
142
+ function compare(actual: unknown, where: Where): boolean {
143
+ if (actual === undefined) {
144
+ return where.op === '!='
145
+ }
146
+ const text = typeof actual === 'string' ? actual : JSON.stringify(actual)
147
+ if (where.op === '~') {
148
+ return text.toLowerCase().includes(where.value.toLowerCase())
149
+ }
150
+ const a = Number(actual)
151
+ const b = Number(where.value)
152
+ const numeric = typeof actual !== 'boolean' && text.trim() !== '' && where.value.trim() !== '' && !Number.isNaN(a) && !Number.isNaN(b)
153
+ switch (where.op) {
154
+ case '=':
155
+ return numeric ? a === b : text === where.value
156
+ case '!=':
157
+ return numeric ? a !== b : text !== where.value
158
+ case '>':
159
+ return numeric ? a > b : text > where.value
160
+ case '>=':
161
+ return numeric ? a >= b : text >= where.value
162
+ case '<':
163
+ return numeric ? a < b : text < where.value
164
+ case '<=':
165
+ return numeric ? a <= b : text <= where.value
166
+ }
167
+ }
168
+
169
+ /** The parts of a query that test one event on its own (not `span`, `run` or `limit`, which need the whole log). */
170
+ export type CompiledQuery = (event: SimEvent) => boolean
171
+
172
+ export function compileQuery(query: EventQuery, now = Date.now()): CompiledQuery {
173
+ const since = query.since === undefined ? undefined : parseBound(query.since, now)
174
+ const until = query.until === undefined ? undefined : parseBound(query.until, now)
175
+ const where = (query.where ?? []).map(parseWhere)
176
+ const text = query.text?.toLowerCase()
177
+ return (event) => {
178
+ if (query.kind !== undefined && query.kind.length > 0 && !query.kind.some((glob) => kindMatches(event.kind, glob))) {
179
+ return false
180
+ }
181
+ if (query.level !== undefined && !levelAtLeast(event.level, query.level)) {
182
+ return false
183
+ }
184
+ if (query.actor !== undefined && query.actor.length > 0 && !query.actor.includes(event.actor)) {
185
+ return false
186
+ }
187
+ if (since !== undefined && ('id' in since ? event.id <= since.id : event.time < since.time)) {
188
+ return false
189
+ }
190
+ if (until !== undefined && ('id' in until ? event.id > until.id : event.time > until.time)) {
191
+ return false
192
+ }
193
+ if (text !== undefined && !event.summary.toLowerCase().includes(text) && !JSON.stringify(event.data ?? '').toLowerCase().includes(text)) {
194
+ return false
195
+ }
196
+ return where.every((condition) => compare(resolve(event, condition.path), condition))
197
+ }
198
+ }
199
+
200
+ /** A query as URL parameters, for the HTTP endpoints; `queryFromParams` reads it back. */
201
+ export function queryToParams(query: EventQuery): URLSearchParams {
202
+ const params = new URLSearchParams()
203
+ for (const [key, value] of Object.entries(query)) {
204
+ if (Array.isArray(value)) {
205
+ value.forEach((item) => params.append(key, String(item)))
206
+ } else if (value !== undefined) {
207
+ params.set(key, String(value))
208
+ }
209
+ }
210
+ return params
211
+ }
212
+
213
+ export function queryFromParams(params: URLSearchParams): EventQuery {
214
+ const list = (key: string) => (params.has(key) ? params.getAll(key).flatMap((value) => (key === 'where' ? [value] : value.split(','))).filter(Boolean) : undefined)
215
+ const level = params.get('level') ?? undefined
216
+ if (level !== undefined && !LEVELS.includes(level as Level)) {
217
+ throw new Error(`No level '${level}'. Levels: ${LEVELS.join(', ')}`)
218
+ }
219
+ const actor = list('actor')
220
+ const unknownActor = actor?.find((value) => !ACTORS.includes(value as Actor))
221
+ if (unknownActor !== undefined) {
222
+ throw new Error(`No actor '${unknownActor}'. Actors: ${ACTORS.join(', ')}`)
223
+ }
224
+ const run = params.get('run') ?? undefined
225
+ const limit = params.get('limit') ?? undefined
226
+ return {
227
+ kind: list('kind'),
228
+ level: level as Level | undefined,
229
+ actor: actor as Actor[] | undefined,
230
+ run: run === undefined ? undefined : run === 'current' || run === 'previous' ? run : Number(run),
231
+ span: params.get('span') ?? undefined,
232
+ since: params.get('since') ?? undefined,
233
+ until: params.get('until') ?? undefined,
234
+ text: params.get('text') ?? undefined,
235
+ where: list('where'),
236
+ limit: limit === undefined ? undefined : Number(limit),
237
+ }
238
+ }