@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,351 @@
1
+ import { app, getState, plugin, sessionValue, shellWindow } from 'web-sim/runtime'
2
+ import { INITIAL_STORAGE, type StorageState } from './state.ts'
3
+
4
+ /**
5
+ * The phone's file system: the store behind expo-file-system's override (both of its APIs) and the storage panel.
6
+ *
7
+ * Files live in memory on the shell, so every copy of this module, every reload of the app and the panel see the same
8
+ * files, and the native API's synchronous calls (`exists`, `textSync`, `list()`) can answer at once. Each change is
9
+ * written through to IndexedDB (`web-sim:expo-file-system:<app slug>`), which fills the memory again when the shell
10
+ * reloads, and bumps the storage plugin's revision, so the panel redraws. The async calls wait for the load; the sync
11
+ * ones see what has loaded so far.
12
+ *
13
+ * Paths are the device's own: the app's container under `/var/mobile/Containers/Data/Application/<id>` on iOS,
14
+ * `/data/user/0/<package>` on Android.
15
+ */
16
+
17
+ export type Node = { kind: 'file' | 'directory'; data?: Uint8Array; created: number; modified: number }
18
+
19
+ type Store = {
20
+ nodes: Map<string, Node>
21
+ ready: Promise<void>
22
+ db: Promise<IDBDatabase | null>
23
+ }
24
+
25
+ // ---------------------------------------------------------------------------------------------------------------
26
+ // Where things are
27
+
28
+ export function hash(text: string, seed: number): number {
29
+ let h = seed
30
+ for (let i = 0; i < text.length; i++) {
31
+ h = Math.imul(h ^ text.charCodeAt(i), 2654435761)
32
+ }
33
+ return (h ^ (h >>> 16)) >>> 0
34
+ }
35
+
36
+ /** A UUID that is the same for an app every time, as its container's is until it is reinstalled. */
37
+ export function containerId(salt: string): string {
38
+ const hex = [1, 2, 3, 4].map((seed) => hash(app().slug + salt, seed).toString(16).padStart(8, '0')).join('').toUpperCase()
39
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-A${hex.slice(17, 20)}-${hex.slice(20, 32)}`
40
+ }
41
+
42
+ export function packageName(): string {
43
+ const config = app().config ?? {}
44
+ return config.android?.package ?? config.ios?.bundleIdentifier ?? app().bundleId
45
+ }
46
+
47
+ export function roots(): { document: string; cache: string; bundle: string } {
48
+ if (getState().device.platform === 'ios') {
49
+ const container = `/var/mobile/Containers/Data/Application/${containerId('data')}`
50
+ return {
51
+ document: `${container}/Documents`,
52
+ cache: `${container}/Library/Caches`,
53
+ bundle: `/var/containers/Bundle/Application/${containerId('bundle')}/${app().name.replace(/[^\w.-]/g, '')}.app`,
54
+ }
55
+ }
56
+ const data = `/data/user/0/${packageName()}`
57
+ return { document: `${data}/files`, cache: `${data}/cache`, bundle: '/android_asset' }
58
+ }
59
+
60
+ /** A `file://` URI, or a path, as a normalised absolute path: decoded, no trailing slash, no `.` or `..`. */
61
+ export function toPath(uri: string): string {
62
+ let path = uri.replace(/^file:\/\//, '').replace(/^asset:\/\//, '/android_asset')
63
+ try {
64
+ path = decodeURIComponent(path)
65
+ } catch {
66
+ // Already decoded.
67
+ }
68
+ const parts: string[] = []
69
+ for (const part of path.split('/')) {
70
+ if (part === '' || part === '.') {
71
+ continue
72
+ }
73
+ if (part === '..') {
74
+ parts.pop()
75
+ } else {
76
+ parts.push(part)
77
+ }
78
+ }
79
+ return `/${parts.join('/')}`
80
+ }
81
+
82
+ export function toUri(path: string, directory: boolean): string {
83
+ const encoded = path.split('/').map(encodeURIComponent).join('/')
84
+ return `file://${encoded}${directory && path !== '/' ? '/' : ''}`
85
+ }
86
+
87
+ export function parentOf(path: string): string {
88
+ return path.slice(0, path.lastIndexOf('/')) || '/'
89
+ }
90
+
91
+ export function nameOf(path: string): string {
92
+ return path.slice(path.lastIndexOf('/') + 1)
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------------------------------------------
96
+ // The store
97
+
98
+ export function store(): Store {
99
+ return sessionValue(`expo-file-system:${app().slug}`, () => {
100
+ const nodes = new Map<string, Node>()
101
+ const db = openDatabase()
102
+ const ready = db.then((database) => (database === null ? undefined : hydrate(database, nodes))).then(changed)
103
+ return { nodes, db, ready }
104
+ })
105
+ }
106
+
107
+ export function openDatabase(): Promise<IDBDatabase | null> {
108
+ return new Promise((resolve) => {
109
+ try {
110
+ const request = getHostWindow().indexedDB.open(`web-sim:expo-file-system:${app().slug}`, 1)
111
+ request.onupgradeneeded = () => request.result.createObjectStore('nodes')
112
+ request.onsuccess = () => resolve(request.result)
113
+ request.onerror = () => resolve(null)
114
+ } catch {
115
+ resolve(null)
116
+ }
117
+ })
118
+ }
119
+
120
+ /** The shell's window, which outlives the app's, so the database connection does too. */
121
+ export function getHostWindow(): Window {
122
+ return shellWindow()
123
+ }
124
+
125
+ export function hydrate(database: IDBDatabase, nodes: Map<string, Node>): Promise<void> {
126
+ return new Promise((resolve) => {
127
+ const request = database.transaction('nodes').objectStore('nodes').openCursor()
128
+ request.onsuccess = () => {
129
+ const cursor = request.result
130
+ if (cursor === null) {
131
+ resolve()
132
+ return
133
+ }
134
+ // A change made before the stored files loaded is newer than them.
135
+ if (!nodes.has(cursor.key as string)) {
136
+ nodes.set(cursor.key as string, cursor.value as Node)
137
+ }
138
+ cursor.continue()
139
+ }
140
+ request.onerror = () => resolve()
141
+ })
142
+ }
143
+
144
+ /** Tells the panel the files changed. */
145
+ function changed(): void {
146
+ const storage = plugin<StorageState>('storage', INITIAL_STORAGE)
147
+ storage.set({ files: storage.get().files + 1 })
148
+ }
149
+
150
+ /** Writes changes through to IndexedDB. A null node deletes. */
151
+ export function persist(changes: [string, Node | null][]): void {
152
+ changed()
153
+ void store().db.then((database) => {
154
+ if (database === null || changes.length === 0) {
155
+ return
156
+ }
157
+ const objects = database.transaction('nodes', 'readwrite').objectStore('nodes')
158
+ for (const [path, node] of changes) {
159
+ if (node === null) {
160
+ objects.delete(path)
161
+ } else {
162
+ objects.put(node, path)
163
+ }
164
+ }
165
+ })
166
+ }
167
+
168
+ /** Deletes every file, as uninstalling the app does. */
169
+ export function clearFiles(): void {
170
+ store().nodes.clear()
171
+ changed()
172
+ void store().db.then((database) => database?.transaction('nodes', 'readwrite').objectStore('nodes').clear())
173
+ }
174
+
175
+ /** The roots and the folders above them exist without being created, as the OS made them. */
176
+ export function isSystemDirectory(path: string): boolean {
177
+ return Object.values(roots()).some((root) => root === path || root.startsWith(`${path}/`)) || path === '/'
178
+ }
179
+
180
+ export function node(path: string): Node | undefined {
181
+ return store().nodes.get(path)
182
+ }
183
+
184
+ export function isFile(path: string): boolean {
185
+ return node(path)?.kind === 'file'
186
+ }
187
+
188
+ export function isDirectory(path: string): boolean {
189
+ return node(path)?.kind === 'directory' || isSystemDirectory(path)
190
+ }
191
+
192
+ export function exists(path: string): boolean {
193
+ return store().nodes.has(path) || isSystemDirectory(path)
194
+ }
195
+
196
+ /** Every path inside a directory, at any depth. */
197
+ export function descendants(path: string): string[] {
198
+ const prefix = path === '/' ? '/' : `${path}/`
199
+ return [...store().nodes.keys()].filter((candidate) => candidate.startsWith(prefix))
200
+ }
201
+
202
+ export function children(path: string): string[] {
203
+ const prefix = path === '/' ? '/' : `${path}/`
204
+ const names = new Set<string>()
205
+ for (const candidate of store().nodes.keys()) {
206
+ if (candidate.startsWith(prefix)) {
207
+ names.add(candidate.slice(prefix.length).split('/')[0])
208
+ }
209
+ }
210
+ // System folders show inside their parents too.
211
+ for (const root of Object.values(roots())) {
212
+ if (root.startsWith(prefix)) {
213
+ names.add(root.slice(prefix.length).split('/')[0])
214
+ }
215
+ }
216
+ return [...names].sort().map((name) => `${prefix}${name}`)
217
+ }
218
+
219
+ export function requireParent(path: string, intermediates = false): void {
220
+ const parent = parentOf(path)
221
+ if (isDirectory(parent)) {
222
+ return
223
+ }
224
+ if (isFile(parent) || !intermediates) {
225
+ throw new Error(`The parent directory of '${toUri(path, false)}' does not exist`)
226
+ }
227
+ makeDirectory(parent, true)
228
+ }
229
+
230
+ export function makeDirectory(path: string, intermediates: boolean): void {
231
+ requireParent(path, intermediates)
232
+ if (!exists(path)) {
233
+ const now = Date.now()
234
+ const created: Node = { kind: 'directory', created: now, modified: now }
235
+ store().nodes.set(path, created)
236
+ persist([[path, created]])
237
+ }
238
+ }
239
+
240
+ export function writeFile(path: string, data: Uint8Array, append = false): void {
241
+ if (isDirectory(path)) {
242
+ throw new Error(`'${toUri(path, true)}' is a directory`)
243
+ }
244
+ requireParent(path)
245
+ const now = Date.now()
246
+ const previous = node(path)
247
+ const contents = append && previous?.data ? concat(previous.data, data) : data.slice()
248
+ const written: Node = { kind: 'file', data: contents, created: previous?.created ?? now, modified: now }
249
+ store().nodes.set(path, written)
250
+ persist([[path, written]])
251
+ }
252
+
253
+ export function readFile(path: string): Uint8Array {
254
+ const file = node(path)
255
+ if (file?.kind !== 'file') {
256
+ throw new Error(`Unable to read '${toUri(path, false)}': the file does not exist`)
257
+ }
258
+ return file.data ?? new Uint8Array()
259
+ }
260
+
261
+ export function remove(path: string): void {
262
+ if (isSystemDirectory(path)) {
263
+ throw new Error(`'${toUri(path, true)}' cannot be deleted`)
264
+ }
265
+ const paths = [path, ...descendants(path)]
266
+ paths.forEach((each) => store().nodes.delete(each))
267
+ persist(paths.map((each) => [each, null]))
268
+ }
269
+
270
+ export function copy(from: string, to: string, overwrite: boolean): void {
271
+ if (!exists(from)) {
272
+ throw new Error(`'${toUri(from, false)}' does not exist`)
273
+ }
274
+ if (to === from || to.startsWith(`${from}/`)) {
275
+ throw new Error(`Cannot copy '${toUri(from, false)}' into itself`)
276
+ }
277
+ if (exists(to)) {
278
+ if (!overwrite) {
279
+ throw new Error(`'${toUri(to, false)}' already exists`)
280
+ }
281
+ remove(to)
282
+ }
283
+ requireParent(to)
284
+ const changes: [string, Node][] = []
285
+ for (const source of [from, ...descendants(from)]) {
286
+ const original = node(source) ?? { kind: 'directory', created: Date.now(), modified: Date.now() }
287
+ const target = to + source.slice(from.length)
288
+ const copied: Node = { ...original, data: original.data?.slice() }
289
+ store().nodes.set(target, copied)
290
+ changes.push([target, copied])
291
+ }
292
+ persist(changes)
293
+ }
294
+
295
+ export function move(from: string, to: string, overwrite: boolean): void {
296
+ copy(from, to, overwrite)
297
+ remove(from)
298
+ }
299
+
300
+ export function size(path: string): number {
301
+ if (isFile(path)) {
302
+ return readFile(path).length
303
+ }
304
+ return descendants(path).reduce((total, each) => total + (node(each)?.data?.length ?? 0), 0)
305
+ }
306
+
307
+ /** A copy made in the app's realm, so `instanceof Uint8Array` and `.buffer` behave in app code. */
308
+ export function own(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
309
+ const copied = new Uint8Array(bytes.length)
310
+ copied.set(bytes)
311
+ return copied
312
+ }
313
+
314
+ export function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
315
+ const joined = new Uint8Array(a.length + b.length)
316
+ joined.set(a)
317
+ joined.set(b, a.length)
318
+ return joined
319
+ }
320
+
321
+ // ---------------------------------------------------------------------------------------------------------------
322
+ // Encodings
323
+
324
+ export function toBase64(bytes: Uint8Array): string {
325
+ let binary = ''
326
+ for (let i = 0; i < bytes.length; i += 0x8000) {
327
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
328
+ }
329
+ return btoa(binary)
330
+ }
331
+
332
+ export function fromBase64(base64: string): Uint8Array {
333
+ const binary = atob(base64.replace(/^data:[^,]*,/, '').replace(/\s/g, ''))
334
+ const bytes = new Uint8Array(binary.length)
335
+ for (let i = 0; i < binary.length; i++) {
336
+ bytes[i] = binary.charCodeAt(i)
337
+ }
338
+ return bytes
339
+ }
340
+
341
+ const MIME_TYPES: Record<string, string> = {
342
+ txt: 'text/plain', md: 'text/markdown', html: 'text/html', css: 'text/css', csv: 'text/csv', json: 'application/json',
343
+ js: 'text/javascript', xml: 'application/xml', pdf: 'application/pdf', zip: 'application/zip', png: 'image/png',
344
+ jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', heic: 'image/heic', svg: 'image/svg+xml',
345
+ mp3: 'audio/mpeg', m4a: 'audio/mp4', wav: 'audio/wav', mp4: 'video/mp4', mov: 'video/quicktime',
346
+ }
347
+
348
+ export function mimeType(path: string): string {
349
+ const extension = nameOf(path).split('.').pop()?.toLowerCase() ?? ''
350
+ return MIME_TYPES[extension] ?? 'application/octet-stream'
351
+ }