@a16n/web-sim 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/bin/cli.ts +255 -0
- package/bin/web-sim.js +39 -0
- package/overrides/@backpackapp-io/react-native-toast/overrides.ts +15 -0
- package/overrides/@react-native-firebase/app/overrides.ts +34 -0
- package/overrides/@tiktok-for-business/react-native-sdk/NativeTiktokSdk.ts +29 -0
- package/overrides/@tiktok-for-business/react-native-sdk/overrides.ts +9 -0
- package/overrides/expo-application/ExpoApplication.ts +81 -0
- package/overrides/expo-application/overrides.ts +16 -0
- package/overrides/expo-background-task/ExpoBackgroundTaskModule.ts +30 -0
- package/overrides/expo-background-task/overrides.ts +9 -0
- package/overrides/expo-constants/ExponentConstants.ts +66 -0
- package/overrides/expo-constants/overrides.ts +9 -0
- package/overrides/expo-device/ExpoDevice.ts +104 -0
- package/overrides/expo-device/overrides.ts +9 -0
- package/overrides/expo-glass-effect/GlassContainer.tsx +9 -0
- package/overrides/expo-glass-effect/GlassView.tsx +95 -0
- package/overrides/expo-glass-effect/availability.ts +14 -0
- package/overrides/expo-glass-effect/overrides.ts +14 -0
- package/overrides/expo-haptics/Haptics.ts +67 -0
- package/overrides/expo-haptics/overrides.ts +5 -0
- package/overrides/expo-mail-composer/ExpoMailComposer.ts +40 -0
- package/overrides/expo-mail-composer/overrides.ts +9 -0
- package/overrides/expo-mesh-gradient/MeshGradientView.tsx +44 -0
- package/overrides/expo-mesh-gradient/overrides.ts +9 -0
- package/overrides/expo-modules-core/overrides.ts +12 -0
- package/overrides/expo-navigation-bar/ExpoNavigationBar.ts +29 -0
- package/overrides/expo-navigation-bar/NavigationBar.ts +43 -0
- package/overrides/expo-navigation-bar/overrides.ts +12 -0
- package/overrides/expo-router/NativeStackView.tsx +74 -0
- package/overrides/expo-router/NativeTabsView.tsx +263 -0
- package/overrides/expo-router/SafeAreaProvider.ts +6 -0
- package/overrides/expo-router/overrides.ts +23 -0
- package/overrides/expo-router/statusBarRequests.ts +51 -0
- package/overrides/expo-screen-orientation/ExpoScreenOrientation.ts +173 -0
- package/overrides/expo-screen-orientation/overrides.ts +21 -0
- package/overrides/expo-sharing/SharingNativeModule.ts +21 -0
- package/overrides/expo-sharing/overrides.ts +9 -0
- package/overrides/expo-sms/ExpoSMS.ts +24 -0
- package/overrides/expo-sms/overrides.ts +9 -0
- package/overrides/expo-splash-screen/SplashScreen.ts +25 -0
- package/overrides/expo-splash-screen/overrides.ts +5 -0
- package/overrides/expo-status-bar/StatusBar.tsx +44 -0
- package/overrides/expo-status-bar/overrides.ts +5 -0
- package/overrides/expo-store-review/ExpoStoreReview.ts +18 -0
- package/overrides/expo-store-review/overrides.ts +9 -0
- package/overrides/expo-symbols/SymbolView.tsx +192 -0
- package/overrides/expo-symbols/overrides.ts +9 -0
- package/overrides/expo-system-ui/ExpoSystemUI.ts +34 -0
- package/overrides/expo-system-ui/overrides.ts +9 -0
- package/overrides/expo-task-manager/ExpoTaskManager.ts +39 -0
- package/overrides/expo-task-manager/overrides.ts +9 -0
- package/overrides/expo-tracking-transparency/ExpoTrackingTransparency.ts +30 -0
- package/overrides/expo-tracking-transparency/overrides.ts +11 -0
- package/overrides/expo-video/ExpoVideo.ts +16 -0
- package/overrides/expo-video/overrides.ts +9 -0
- package/overrides/lottie-react-native/LottieView.tsx +87 -0
- package/overrides/lottie-react-native/overrides.ts +9 -0
- package/overrides/react-native-pager-view/PagerViewNativeComponent.tsx +254 -0
- package/overrides/react-native-pager-view/overrides.ts +9 -0
- package/overrides/react-native-reanimated/overrides.ts +28 -0
- package/overrides/react-native-safe-area-context/NativeSafeAreaProvider.tsx +40 -0
- package/overrides/react-native-safe-area-context/overrides.ts +12 -0
- package/overrides/react-native-share/NativeRNShare.ts +22 -0
- package/overrides/react-native-share/overrides.ts +12 -0
- package/overrides/react-native-share/platform.ts +14 -0
- package/overrides/react-native-turbo-image/TurboImage.tsx +101 -0
- package/overrides/react-native-turbo-image/overrides.ts +9 -0
- package/overrides/react-native-web/RefreshControl.tsx +57 -0
- package/overrides/react-native-web/overrides.ts +153 -0
- package/overrides/react-native-web/useElementLayout.ts +140 -0
- package/package.json +78 -4
- package/plugins/battery/overrides/expo-battery/ExpoBattery.ts +57 -0
- package/plugins/battery/overrides/expo-battery/overrides.ts +9 -0
- package/plugins/battery/plugin.ts +8 -0
- package/plugins/battery/shell.tsx +56 -0
- package/plugins/battery/state.ts +11 -0
- package/plugins/biometrics/overrides/expo-local-authentication/ExpoLocalAuthentication.ts +90 -0
- package/plugins/biometrics/overrides/expo-local-authentication/overrides.ts +11 -0
- package/plugins/biometrics/plugin.ts +8 -0
- package/plugins/biometrics/shell.tsx +88 -0
- package/plugins/biometrics/state.ts +41 -0
- package/plugins/brightness/app.ts +5 -0
- package/plugins/brightness/overrides/expo-brightness/Brightness.ts +98 -0
- package/plugins/brightness/overrides/expo-brightness/overrides.ts +10 -0
- package/plugins/brightness/plugin.ts +9 -0
- package/plugins/brightness/shell.tsx +55 -0
- package/plugins/brightness/state.ts +19 -0
- package/plugins/calendar/calendar.ts +299 -0
- package/plugins/calendar/overrides/expo-calendar/ExpoCalendar.ts +358 -0
- package/plugins/calendar/overrides/expo-calendar/LegacyExpoCalendar.ts +163 -0
- package/plugins/calendar/overrides/expo-calendar/overrides.ts +14 -0
- package/plugins/calendar/plugin.ts +8 -0
- package/plugins/calendar/shell.tsx +123 -0
- package/plugins/camera/overrides/expo-camera/ExpoCamera.tsx +269 -0
- package/plugins/camera/overrides/expo-camera/ExpoCameraManager.ts +56 -0
- package/plugins/camera/overrides/expo-camera/overrides.ts +12 -0
- package/plugins/camera/plugin.ts +9 -0
- package/plugins/camera/shell.tsx +107 -0
- package/plugins/camera/state.ts +61 -0
- package/plugins/clipboard/overrides/expo-clipboard/ExpoClipboard.ts +138 -0
- package/plugins/clipboard/overrides/expo-clipboard/overrides.ts +9 -0
- package/plugins/clipboard/plugin.ts +8 -0
- package/plugins/clipboard/shell.tsx +122 -0
- package/plugins/clipboard/state.ts +93 -0
- package/plugins/clock/app.ts +25 -0
- package/plugins/clock/plugin.ts +8 -0
- package/plugins/clock/shell.tsx +225 -0
- package/plugins/clock/state.ts +12 -0
- package/plugins/contacts/contacts.ts +125 -0
- package/plugins/contacts/overrides/expo-contacts/ExpoContacts.ts +153 -0
- package/plugins/contacts/overrides/expo-contacts/ExpoContactsNext.ts +232 -0
- package/plugins/contacts/overrides/expo-contacts/overrides.ts +12 -0
- package/plugins/contacts/plugin.ts +8 -0
- package/plugins/contacts/shell.tsx +109 -0
- package/plugins/home-indicator/app.ts +5 -0
- package/plugins/home-indicator/plugin.ts +9 -0
- package/plugins/home-indicator/requests.ts +48 -0
- package/plugins/home-indicator/shell.tsx +68 -0
- package/plugins/home-indicator/state.ts +31 -0
- package/plugins/keep-awake/app.ts +5 -0
- package/plugins/keep-awake/overrides/expo-keep-awake/ExpoKeepAwake.ts +27 -0
- package/plugins/keep-awake/overrides/expo-keep-awake/overrides.ts +9 -0
- package/plugins/keep-awake/plugin.ts +9 -0
- package/plugins/keep-awake/shell.tsx +80 -0
- package/plugins/keep-awake/state.ts +12 -0
- package/plugins/keyboard/Keyboard.tsx +354 -0
- package/plugins/keyboard/app.ts +90 -0
- package/plugins/keyboard/controller.ts +384 -0
- package/plugins/keyboard/fields.ts +244 -0
- package/plugins/keyboard/icons.tsx +283 -0
- package/plugins/keyboard/keyboard.css +362 -0
- package/plugins/keyboard/layouts/android.ts +175 -0
- package/plugins/keyboard/layouts/index.ts +10 -0
- package/plugins/keyboard/layouts/ios.ts +219 -0
- package/plugins/keyboard/layouts/types.ts +80 -0
- package/plugins/keyboard/overrides/react-native-keyboard-controller/KeyboardController.tsx +470 -0
- package/plugins/keyboard/overrides/react-native-keyboard-controller/overrides.ts +9 -0
- package/plugins/keyboard/plugin.ts +13 -0
- package/plugins/keyboard/shell.tsx +133 -0
- package/plugins/keyboard/state.ts +92 -0
- package/plugins/keyboard/suggestions.ts +63 -0
- package/plugins/keyboard/taps.ts +77 -0
- package/plugins/keyboard/typing.ts +112 -0
- package/plugins/locale/app.ts +232 -0
- package/plugins/locale/locale.ts +143 -0
- package/plugins/locale/overrides/expo-localization/ExpoLocalization.ts +41 -0
- package/plugins/locale/overrides/expo-localization/overrides.ts +9 -0
- package/plugins/locale/plugin.ts +9 -0
- package/plugins/locale/shell.tsx +147 -0
- package/plugins/locale/state.ts +36 -0
- package/plugins/location/geo.ts +56 -0
- package/plugins/location/overrides/expo-location/ExpoLocation.ts +235 -0
- package/plugins/location/overrides/expo-location/overrides.ts +11 -0
- package/plugins/location/places.ts +38 -0
- package/plugins/location/plugin.ts +8 -0
- package/plugins/location/shell.tsx +188 -0
- package/plugins/location/state.ts +51 -0
- package/plugins/motion/overrides/expo-sensors/DeviceSensor.ts +169 -0
- package/plugins/motion/overrides/expo-sensors/ExponentPedometer.ts +54 -0
- package/plugins/motion/overrides/expo-sensors/overrides.ts +14 -0
- package/plugins/motion/plugin.ts +8 -0
- package/plugins/motion/sensors.ts +116 -0
- package/plugins/motion/shell.tsx +136 -0
- package/plugins/motion/state.ts +46 -0
- package/plugins/network/app.ts +400 -0
- package/plugins/network/overrides/expo-network/ExpoNetwork.ts +51 -0
- package/plugins/network/overrides/expo-network/overrides.ts +9 -0
- package/plugins/network/plugin.ts +8 -0
- package/plugins/network/shell.tsx +67 -0
- package/plugins/network/state.ts +29 -0
- package/plugins/notifications/center.ts +255 -0
- package/plugins/notifications/content.ts +36 -0
- package/plugins/notifications/overrides/expo-notifications/NotificationsModule.ts +175 -0
- package/plugins/notifications/overrides/expo-notifications/channels.ts +108 -0
- package/plugins/notifications/overrides/expo-notifications/getDevicePushTokenAsync.ts +19 -0
- package/plugins/notifications/overrides/expo-notifications/getExpoPushTokenAsync.ts +16 -0
- package/plugins/notifications/overrides/expo-notifications/overrides.ts +36 -0
- package/plugins/notifications/plugin.ts +8 -0
- package/plugins/notifications/shell.tsx +192 -0
- package/plugins/notifications/state.ts +56 -0
- package/plugins/notifications/tokens.ts +47 -0
- package/plugins/notifications/trigger.ts +107 -0
- package/plugins/permissions/plugin.ts +6 -0
- package/plugins/permissions/shell.tsx +50 -0
- package/plugins/permissions/state.ts +38 -0
- package/plugins/photos/appLibrary.ts +114 -0
- package/plugins/photos/library.ts +322 -0
- package/plugins/photos/overrides/expo-image-picker/ExponentImagePicker.ts +153 -0
- package/plugins/photos/overrides/expo-image-picker/overrides.ts +13 -0
- package/plugins/photos/overrides/expo-media-library/ExpoMediaLibrary.ts +235 -0
- package/plugins/photos/overrides/expo-media-library/NativeMediaLibraryModule.ts +318 -0
- package/plugins/photos/overrides/expo-media-library/overrides.ts +19 -0
- package/plugins/photos/plugin.ts +8 -0
- package/plugins/photos/samples.ts +367 -0
- package/plugins/photos/shell.tsx +164 -0
- package/plugins/photos/state.ts +88 -0
- package/plugins/storage/files.ts +351 -0
- package/plugins/storage/overrides/expo-file-system/ExpoFileSystem.ts +770 -0
- package/plugins/storage/overrides/expo-file-system/ExponentFileSystem.ts +196 -0
- package/plugins/storage/overrides/expo-file-system/overrides.ts +13 -0
- package/plugins/storage/overrides/expo-secure-store/ExpoSecureStore.ts +75 -0
- package/plugins/storage/overrides/expo-secure-store/overrides.ts +9 -0
- package/plugins/storage/plugin.ts +8 -0
- package/plugins/storage/reset.ts +136 -0
- package/plugins/storage/secure.ts +71 -0
- package/plugins/storage/shell.tsx +365 -0
- package/plugins/storage/state.ts +13 -0
- package/src/client/app/appDocument.ts +113 -0
- package/src/client/app/appFocus.ts +97 -0
- package/src/client/app/console.ts +118 -0
- package/src/client/app/fonts.ts +59 -0
- package/src/client/app/main.tsx +99 -0
- package/src/client/app/routeContext.ts +45 -0
- package/src/client/app/touch.ts +640 -0
- package/src/client/entry.ts +20 -0
- package/src/client/modules.d.ts +8 -0
- package/src/client/react-native/app.ts +57 -0
- package/src/client/react-native/deep.ts +13 -0
- package/src/client/react-native/keyboard.tsx +192 -0
- package/src/client/react-native/library.ts +256 -0
- package/src/client/shell/Cookies.tsx +95 -0
- package/src/client/shell/LogDrawer.tsx +415 -0
- package/src/client/shell/PhotoPicker.tsx +174 -0
- package/src/client/shell/PluginOverlays.tsx +42 -0
- package/src/client/shell/PluginPanels.tsx +82 -0
- package/src/client/shell/ResetApp.tsx +87 -0
- package/src/client/shell/Resizer.tsx +99 -0
- package/src/client/shell/Shell.tsx +531 -0
- package/src/client/shell/SystemBars.tsx +376 -0
- package/src/client/shell/SystemCamera.tsx +181 -0
- package/src/client/shell/SystemOverlay.tsx +422 -0
- package/src/client/shell/SystemSheets.tsx +462 -0
- package/src/client/shell/backdrop.ts +229 -0
- package/src/client/shell/control.ts +91 -0
- package/src/client/shell/events.ts +226 -0
- package/src/client/shell/geometry.ts +68 -0
- package/src/client/shell/host.ts +492 -0
- package/src/client/shell/icons.tsx +34 -0
- package/src/client/shell/logFeed.ts +102 -0
- package/src/client/shell/main.tsx +22 -0
- package/src/client/shell/permissionCopy.ts +169 -0
- package/src/client/shell/plugins.ts +266 -0
- package/src/client/shell/popout.ts +185 -0
- package/src/client/shell/popover.ts +27 -0
- package/src/client/shell/shell.css +878 -0
- package/src/client/shell/statusTime.ts +31 -0
- package/src/client/shell/tooltips.ts +104 -0
- package/src/client/virtual.d.ts +21 -0
- package/src/devices/catalog.ts +223 -0
- package/src/devices/types.ts +83 -0
- package/src/node/appInfo.ts +186 -0
- package/src/node/appSource.ts +138 -0
- package/src/node/config.ts +180 -0
- package/src/node/control.ts +144 -0
- package/src/node/doctor.ts +199 -0
- package/src/node/events/cli.ts +206 -0
- package/src/node/events/shared.ts +238 -0
- package/src/node/events/store.ts +266 -0
- package/src/node/index.ts +5 -0
- package/src/node/overrides/define.ts +56 -0
- package/src/node/overrides/packages.ts +136 -0
- package/src/node/overrides/platformPatch.ts +56 -0
- package/src/node/overrides/plugin.ts +166 -0
- package/src/node/overrides/registry.ts +258 -0
- package/src/node/paths.ts +18 -0
- package/src/node/platform.ts +171 -0
- package/src/node/plugins.ts +98 -0
- package/src/node/proxy.ts +421 -0
- package/src/node/server.ts +253 -0
- package/src/plugin/index.ts +33 -0
- package/src/plugin/types.ts +127 -0
- package/src/plugin/ui.tsx +562 -0
- package/src/runtime/clock.ts +112 -0
- package/src/runtime/draw.ts +196 -0
- package/src/runtime/index.ts +513 -0
- package/src/runtime/media.ts +379 -0
- package/src/runtime/records.ts +76 -0
- package/src/runtime/timezone.ts +81 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import type { Plugin } from 'vite'
|
|
5
|
+
import { compileQuery, type EventInput, type EventQuery, queryFromParams, type SimEvent } from './shared.ts'
|
|
6
|
+
|
|
7
|
+
export const EVENTS_PATH = '/__web-sim/events'
|
|
8
|
+
|
|
9
|
+
const RING_SIZE = 50_000
|
|
10
|
+
const ROTATE_BYTES = 20 * 1024 * 1024
|
|
11
|
+
const DEFAULT_LIMIT = 200
|
|
12
|
+
|
|
13
|
+
/** An event as a shell tab sends it: no id yet, and the tab's own run number. */
|
|
14
|
+
type TabEvent = Omit<SimEvent, 'id'> & { seq?: number }
|
|
15
|
+
|
|
16
|
+
type Subscriber = (event: SimEvent) => void
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The dev server's event log: every tab's events and the server's own, in one order, with global ids and run
|
|
20
|
+
* numbers. Kept in memory for queries and appended to `events.jsonl` in its directory (one per dev server), so
|
|
21
|
+
* `web-sim logs` still answers after the tab or the server has gone. At 20 MB the file is rotated, keeping one older
|
|
22
|
+
* file.
|
|
23
|
+
*/
|
|
24
|
+
export class EventStore {
|
|
25
|
+
readonly dir: string
|
|
26
|
+
private readonly file: string
|
|
27
|
+
private readonly previousFile: string
|
|
28
|
+
private ring: SimEvent[] = []
|
|
29
|
+
private nextId = 1
|
|
30
|
+
private size = 0
|
|
31
|
+
/** The newest run, across tabs. */
|
|
32
|
+
lastRun = 0
|
|
33
|
+
/** Each tab's run number to the global one, by `<tab>:<run>`. */
|
|
34
|
+
private runs = new Map<string, number>()
|
|
35
|
+
private subscribers = new Set<Subscriber>()
|
|
36
|
+
|
|
37
|
+
constructor(dir: string) {
|
|
38
|
+
this.dir = dir
|
|
39
|
+
this.file = path.join(dir, 'events.jsonl')
|
|
40
|
+
this.previousFile = path.join(dir, 'events.1.jsonl')
|
|
41
|
+
this.load()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The tail of the files on disk, as much as fits the ring. */
|
|
45
|
+
private load(): void {
|
|
46
|
+
const lines: string[] = []
|
|
47
|
+
for (const file of [this.previousFile, this.file]) {
|
|
48
|
+
if (existsSync(file)) {
|
|
49
|
+
lines.push(...readFileSync(file, 'utf8').split('\n'))
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
this.size = existsSync(this.file) ? statSync(this.file).size : 0
|
|
53
|
+
for (const line of lines.slice(-RING_SIZE * 2)) {
|
|
54
|
+
if (line.trim() === '') {
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
this.ring.push(JSON.parse(line) as SimEvent)
|
|
59
|
+
} catch {
|
|
60
|
+
// A line cut short when the server stopped mid-write.
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
this.ring = this.ring.slice(-RING_SIZE)
|
|
64
|
+
const last = this.ring.at(-1)
|
|
65
|
+
if (last !== undefined) {
|
|
66
|
+
this.nextId = last.id + 1
|
|
67
|
+
this.lastRun = this.ring.reduce((max, event) => Math.max(max, event.run), 0)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** An event from the dev server itself, in the newest run. */
|
|
72
|
+
add(input: EventInput & { time?: number }): SimEvent {
|
|
73
|
+
const event: SimEvent = {
|
|
74
|
+
id: 0,
|
|
75
|
+
time: input.time ?? Date.now(),
|
|
76
|
+
run: this.lastRun,
|
|
77
|
+
tab: '',
|
|
78
|
+
kind: input.kind,
|
|
79
|
+
level: input.level ?? 'info',
|
|
80
|
+
actor: input.actor ?? 'system',
|
|
81
|
+
summary: input.summary,
|
|
82
|
+
}
|
|
83
|
+
if (input.data !== undefined) {
|
|
84
|
+
event.data = input.data
|
|
85
|
+
}
|
|
86
|
+
if (input.span !== undefined) {
|
|
87
|
+
event.span = input.span
|
|
88
|
+
}
|
|
89
|
+
if (input.cause !== undefined) {
|
|
90
|
+
event.cause = input.cause
|
|
91
|
+
}
|
|
92
|
+
this.append([event])
|
|
93
|
+
return event
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A batch from a shell tab: its runs mapped to global ones, a new run at each of its launches. */
|
|
97
|
+
addFromTab(tab: string, batch: TabEvent[]): void {
|
|
98
|
+
const events = batch.map(({ seq: _, ...event }): SimEvent => {
|
|
99
|
+
const key = `${tab}:${event.run}`
|
|
100
|
+
let run = this.runs.get(key)
|
|
101
|
+
if (run === undefined) {
|
|
102
|
+
// A tab's run 0 is what it did before the app first launched: it belongs to the newest run so far.
|
|
103
|
+
run = event.run === 0 ? this.lastRun : ++this.lastRun
|
|
104
|
+
this.runs.set(key, run)
|
|
105
|
+
}
|
|
106
|
+
return { ...event, id: 0, tab, run }
|
|
107
|
+
})
|
|
108
|
+
this.append(events)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private append(events: SimEvent[]): void {
|
|
112
|
+
if (events.length === 0) {
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
for (const event of events) {
|
|
116
|
+
event.id = this.nextId++
|
|
117
|
+
}
|
|
118
|
+
this.ring.push(...events)
|
|
119
|
+
if (this.ring.length > RING_SIZE) {
|
|
120
|
+
this.ring.splice(0, this.ring.length - RING_SIZE)
|
|
121
|
+
}
|
|
122
|
+
const text = events.map((event) => `${JSON.stringify(event)}\n`).join('')
|
|
123
|
+
try {
|
|
124
|
+
if (this.size + text.length > ROTATE_BYTES && existsSync(this.file)) {
|
|
125
|
+
renameSync(this.file, this.previousFile)
|
|
126
|
+
this.size = 0
|
|
127
|
+
}
|
|
128
|
+
mkdirSync(this.dir, { recursive: true })
|
|
129
|
+
appendFileSync(this.file, text)
|
|
130
|
+
this.size += Buffer.byteLength(text)
|
|
131
|
+
} catch (error) {
|
|
132
|
+
console.warn(`\x1b[33mweb-sim\x1b[0m could not write the event log: ${error instanceof Error ? error.message : String(error)}`)
|
|
133
|
+
}
|
|
134
|
+
for (const event of events) {
|
|
135
|
+
this.subscribers.forEach((subscriber) => subscriber(event))
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* A test for one event that also knows the whole log: `run` against the newest run as it is when asked, and `span`
|
|
141
|
+
* growing as events it caused arrive, so the same matcher serves history and then live events.
|
|
142
|
+
*/
|
|
143
|
+
matcher(query: EventQuery): (event: SimEvent) => boolean {
|
|
144
|
+
const test = compileQuery(query)
|
|
145
|
+
const spans = query.span === undefined ? null : new Set([query.span])
|
|
146
|
+
return (event) => {
|
|
147
|
+
if (spans !== null) {
|
|
148
|
+
if (!(event.span !== undefined && spans.has(event.span)) && !(event.cause !== undefined && spans.has(event.cause))) {
|
|
149
|
+
return false
|
|
150
|
+
}
|
|
151
|
+
if (event.span !== undefined) {
|
|
152
|
+
spans.add(event.span)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (query.run !== undefined) {
|
|
156
|
+
const run = query.run === 'current' ? this.lastRun : query.run === 'previous' ? this.lastRun - 1 : query.run
|
|
157
|
+
if (event.run !== run) {
|
|
158
|
+
return false
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return test(event)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The newest `limit` events that match, oldest first. */
|
|
166
|
+
query(query: EventQuery, matches = this.matcher(query)): SimEvent[] {
|
|
167
|
+
// In time order: a tab's events reach the server up to a batch later than the server's own.
|
|
168
|
+
const found = this.ring.filter(matches).sort((a, b) => a.time - b.time || a.id - b.id)
|
|
169
|
+
const limit = query.limit ?? DEFAULT_LIMIT
|
|
170
|
+
return limit > 0 ? found.slice(-limit) : found
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
subscribe(subscriber: Subscriber): () => void {
|
|
174
|
+
this.subscribers.add(subscriber)
|
|
175
|
+
return () => this.subscribers.delete(subscriber)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Each kind seen, with how many and when it was last seen. */
|
|
179
|
+
kinds(): { kind: string; count: number; last: number }[] {
|
|
180
|
+
const kinds = new Map<string, { kind: string; count: number; last: number }>()
|
|
181
|
+
for (const event of this.ring) {
|
|
182
|
+
const entry = kinds.get(event.kind) ?? { kind: event.kind, count: 0, last: 0 }
|
|
183
|
+
entry.count += 1
|
|
184
|
+
entry.last = event.time
|
|
185
|
+
kinds.set(event.kind, entry)
|
|
186
|
+
}
|
|
187
|
+
return [...kinds.values()].sort((a, b) => a.kind.localeCompare(b.kind))
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Empties the log, on disk too. Ids keep counting, so a reader following by id never goes back. */
|
|
191
|
+
clear(): void {
|
|
192
|
+
this.ring = []
|
|
193
|
+
rmSync(this.file, { force: true })
|
|
194
|
+
rmSync(this.previousFile, { force: true })
|
|
195
|
+
this.size = 0
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The event log's half of the dev server: takes the tabs' batches over Vite's websocket, and answers
|
|
201
|
+
*
|
|
202
|
+
* - `GET /__web-sim/events?<query>`: matching events as JSON, oldest first.
|
|
203
|
+
* - `GET /__web-sim/events/stream?<query>`: Server-Sent Events, the matching history and then each new match.
|
|
204
|
+
* - `GET /__web-sim/events/kinds`: the kinds seen, with counts.
|
|
205
|
+
* - `DELETE /__web-sim/events`: clears the log.
|
|
206
|
+
*
|
|
207
|
+
* The query parameters are `EventQuery`'s fields; lists repeat or take commas (`kind=network,console`).
|
|
208
|
+
*/
|
|
209
|
+
export function eventsChannel(store: EventStore): Plugin {
|
|
210
|
+
return {
|
|
211
|
+
name: 'web-sim:events',
|
|
212
|
+
configureServer(server) {
|
|
213
|
+
server.ws.on('web-sim:events', (data: { tab: string; events: TabEvent[] }) => {
|
|
214
|
+
if (typeof data?.tab === 'string' && Array.isArray(data.events)) {
|
|
215
|
+
store.addFromTab(data.tab, data.events)
|
|
216
|
+
}
|
|
217
|
+
})
|
|
218
|
+
server.middlewares.use(EVENTS_PATH, (req, res) => {
|
|
219
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
220
|
+
try {
|
|
221
|
+
if (req.method === 'DELETE' && url.pathname === '/') {
|
|
222
|
+
store.clear()
|
|
223
|
+
json(res, 200, { ok: true })
|
|
224
|
+
} else if (req.method !== 'GET') {
|
|
225
|
+
json(res, 405, { ok: false, error: 'GET or DELETE' })
|
|
226
|
+
} else if (url.pathname === '/') {
|
|
227
|
+
json(res, 200, { ok: true, run: store.lastRun, events: store.query(queryFromParams(url.searchParams)) })
|
|
228
|
+
} else if (url.pathname === '/kinds') {
|
|
229
|
+
json(res, 200, { ok: true, kinds: store.kinds() })
|
|
230
|
+
} else if (url.pathname === '/stream') {
|
|
231
|
+
stream(store, queryFromParams(url.searchParams), req, res)
|
|
232
|
+
} else {
|
|
233
|
+
json(res, 404, { ok: false, error: `No ${EVENTS_PATH}${url.pathname}` })
|
|
234
|
+
}
|
|
235
|
+
} catch (error) {
|
|
236
|
+
json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
237
|
+
}
|
|
238
|
+
})
|
|
239
|
+
},
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
244
|
+
res.statusCode = status
|
|
245
|
+
res.setHeader('Content-Type', 'application/json')
|
|
246
|
+
res.end(JSON.stringify(body))
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function stream(store: EventStore, query: EventQuery, req: IncomingMessage, res: ServerResponse): void {
|
|
250
|
+
const matches = store.matcher(query)
|
|
251
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' })
|
|
252
|
+
const send = (event: SimEvent) => res.write(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`)
|
|
253
|
+
store.query(query, matches).forEach(send)
|
|
254
|
+
// Tells the reader the history is done, so `wait` and `--follow` know what is live.
|
|
255
|
+
res.write('event: live\ndata: {}\n\n')
|
|
256
|
+
const unsubscribe = store.subscribe((event) => {
|
|
257
|
+
if (matches(event)) {
|
|
258
|
+
send(event)
|
|
259
|
+
}
|
|
260
|
+
})
|
|
261
|
+
const keepAlive = setInterval(() => res.write(': keep-alive\n\n'), 15_000)
|
|
262
|
+
req.on('close', () => {
|
|
263
|
+
unsubscribe()
|
|
264
|
+
clearInterval(keepAlive)
|
|
265
|
+
})
|
|
266
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { defineConfig, type WebSimConfig } from './config.ts'
|
|
2
|
+
export { defineOverrides, type OverrideRule, type PackageOverrides, type SourcePatch } from './overrides/define.ts'
|
|
3
|
+
export type { Device, Platform } from '../devices/types.ts'
|
|
4
|
+
export { DEVICES } from '../devices/catalog.ts'
|
|
5
|
+
export { definePlugin, type WebSimPlugin } from './plugins.ts'
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A change to one source file of a package, made as the file is loaded. It must change the file: one that no longer
|
|
3
|
+
* matches after an upgrade is an error, not a silent no-op.
|
|
4
|
+
*/
|
|
5
|
+
export type SourcePatch = {
|
|
6
|
+
/** The file, relative to the package's root (`dist/exports/View/index.js`), or a pattern over that path. */
|
|
7
|
+
file: string | RegExp
|
|
8
|
+
replace: (source: string) => string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What web-sim does to one range of a package's versions. Paths to replacement files are relative to the file that
|
|
13
|
+
* defines the override.
|
|
14
|
+
*
|
|
15
|
+
* Replacement files are compiled as if they sat where the file they replace sits, so their relative and bare imports
|
|
16
|
+
* resolve from inside the package. `web-sim:original` imports the file being replaced, and `web-sim/runtime` the
|
|
17
|
+
* simulator's state (the device, insets, appearance).
|
|
18
|
+
*/
|
|
19
|
+
export type OverrideRule = {
|
|
20
|
+
/** A semver range, matched against the installed version of the package that each import reaches. */
|
|
21
|
+
versions: string
|
|
22
|
+
/** A file that replaces the package's entry point. */
|
|
23
|
+
replace?: string
|
|
24
|
+
/** Files that replace files of the package, keyed by their path from the package's root. */
|
|
25
|
+
files?: Record<string, string>
|
|
26
|
+
/** Changes to the package's own source files. */
|
|
27
|
+
patch?: SourcePatch[]
|
|
28
|
+
/** Replace the whole package with a stub where every call does nothing: for native-only modules with no web build. */
|
|
29
|
+
stub?: boolean
|
|
30
|
+
/**
|
|
31
|
+
* `'device'`: the package sees the simulated device's platform, as app code does. Its `react-native` import gets a
|
|
32
|
+
* `Platform` that reports `ios` or `android` (with `Platform.select` and `Platform.Version` to match) and its
|
|
33
|
+
* `process.env.EXPO_OS` is the device's platform. It still loads its web files (`.web.js`, then plain), so no
|
|
34
|
+
* native module is reached. `{ device: [...] }` limits that to some of its files: paths from the package's root,
|
|
35
|
+
* where one ending in `/` covers a folder, or patterns over that path.
|
|
36
|
+
*
|
|
37
|
+
* For packages whose platform branches are look and feel (sizes, fonts, layout), not for ones whose
|
|
38
|
+
* `Platform.OS === 'web'` checks pick the only path that works in a browser.
|
|
39
|
+
*/
|
|
40
|
+
platform?: 'device' | { device: (string | RegExp)[] }
|
|
41
|
+
/** Why this override exists, shown by `web-sim doctor`. */
|
|
42
|
+
note?: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type PackageOverrides = {
|
|
46
|
+
package: string
|
|
47
|
+
rules: OverrideRule[]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Overrides for one package. The first rule whose range matches the installed version applies; a version no rule
|
|
52
|
+
* matches gets a warning, so an upgrade past what an override knows is visible.
|
|
53
|
+
*/
|
|
54
|
+
export function defineOverrides(packageName: string, rules: OverrideRule[]): PackageOverrides {
|
|
55
|
+
return { package: packageName, rules }
|
|
56
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
export type PackageInfo = {
|
|
5
|
+
name: string
|
|
6
|
+
version: string
|
|
7
|
+
/** The package's root directory, real path. */
|
|
8
|
+
dir: string
|
|
9
|
+
json: Record<string, unknown>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const byDir = new Map<string, PackageInfo | null>()
|
|
13
|
+
|
|
14
|
+
function readPackage(dir: string): PackageInfo | null {
|
|
15
|
+
if (byDir.has(dir)) {
|
|
16
|
+
return byDir.get(dir)!
|
|
17
|
+
}
|
|
18
|
+
const file = path.join(dir, 'package.json')
|
|
19
|
+
let info: PackageInfo | null = null
|
|
20
|
+
if (existsSync(file)) {
|
|
21
|
+
try {
|
|
22
|
+
const json = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>
|
|
23
|
+
if (typeof json.name === 'string' && typeof json.version === 'string') {
|
|
24
|
+
info = { name: json.name, version: json.version, dir, json }
|
|
25
|
+
}
|
|
26
|
+
} catch {
|
|
27
|
+
info = null
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
byDir.set(dir, info)
|
|
31
|
+
return info
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The package a file belongs to: the nearest `package.json` above it with a name and a version. Nested
|
|
36
|
+
* `package.json` files that only set `type` or `sideEffects` are skipped.
|
|
37
|
+
*/
|
|
38
|
+
export function packageOfFile(file: string): { info: PackageInfo; relative: string } | null {
|
|
39
|
+
let dir = path.dirname(file)
|
|
40
|
+
while (true) {
|
|
41
|
+
const info = readPackage(dir)
|
|
42
|
+
if (info !== null) {
|
|
43
|
+
return { info, relative: path.relative(dir, file).split(path.sep).join('/') }
|
|
44
|
+
}
|
|
45
|
+
const parent = path.dirname(dir)
|
|
46
|
+
if (parent === dir || path.basename(dir) === 'node_modules') {
|
|
47
|
+
return null
|
|
48
|
+
}
|
|
49
|
+
dir = parent
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The installed copy of a package that an import from `fromDir` reaches, found as Node finds it: the nearest
|
|
55
|
+
* `node_modules/<name>` above. With pnpm, each package's own dependencies sit next to it, so two importers can reach
|
|
56
|
+
* two versions.
|
|
57
|
+
*/
|
|
58
|
+
export function findPackage(name: string, fromDir: string): PackageInfo | null {
|
|
59
|
+
let dir = fromDir
|
|
60
|
+
while (true) {
|
|
61
|
+
const candidate = path.join(dir, 'node_modules', name)
|
|
62
|
+
if (existsSync(path.join(candidate, 'package.json'))) {
|
|
63
|
+
return readPackage(realpathSync(candidate))
|
|
64
|
+
}
|
|
65
|
+
const parent = path.dirname(dir)
|
|
66
|
+
if (parent === dir) {
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
dir = parent
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `@scope/name/sub/path` → `['@scope/name', 'sub/path']`. Null for relative, absolute and virtual specifiers. */
|
|
74
|
+
export function splitSpecifier(specifier: string): [string, string] | null {
|
|
75
|
+
if (!/^[@a-zA-Z0-9]/.test(specifier) || specifier.includes(':')) {
|
|
76
|
+
return null
|
|
77
|
+
}
|
|
78
|
+
const parts = specifier.split('/')
|
|
79
|
+
const nameLength = specifier.startsWith('@') ? 2 : 1
|
|
80
|
+
if (parts.length < nameLength) {
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
return [parts.slice(0, nameLength).join('/'), parts.slice(nameLength).join('/')]
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const ENTRY_EXTENSIONS = ['.web.js', '.web.mjs', '.js', '.mjs', '.cjs', '/index.web.js', '/index.js']
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The files a bundler might pick as a package's entry point for the web: its `exports` conditions, `browser`,
|
|
90
|
+
* `module` and `main`. A `replace` override applies to all of them, so it holds whichever one an import reaches.
|
|
91
|
+
*/
|
|
92
|
+
export function entryFiles(info: PackageInfo): string[] {
|
|
93
|
+
const candidates: string[] = []
|
|
94
|
+
const exportsField = info.json.exports
|
|
95
|
+
const rootExport =
|
|
96
|
+
typeof exportsField === 'string'
|
|
97
|
+
? exportsField
|
|
98
|
+
: exportsField !== null && typeof exportsField === 'object'
|
|
99
|
+
? ((exportsField as Record<string, unknown>)['.'] ?? null)
|
|
100
|
+
: null
|
|
101
|
+
collectExportTargets(rootExport, candidates)
|
|
102
|
+
for (const field of ['browser', 'module', 'main']) {
|
|
103
|
+
const value = info.json[field]
|
|
104
|
+
if (typeof value === 'string') {
|
|
105
|
+
candidates.push(value)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (candidates.length === 0) {
|
|
109
|
+
candidates.push('index')
|
|
110
|
+
}
|
|
111
|
+
const files = new Set<string>()
|
|
112
|
+
for (const candidate of candidates) {
|
|
113
|
+
const base = path.join(info.dir, candidate)
|
|
114
|
+
for (const suffix of ['', ...ENTRY_EXTENSIONS]) {
|
|
115
|
+
const file = base + suffix
|
|
116
|
+
if (existsSync(file) && statSync(file).isFile()) {
|
|
117
|
+
files.add(file)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return [...files]
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function collectExportTargets(target: unknown, into: string[]): void {
|
|
125
|
+
if (typeof target === 'string') {
|
|
126
|
+
into.push(target)
|
|
127
|
+
} else if (Array.isArray(target)) {
|
|
128
|
+
target.forEach((item) => collectExportTargets(item, into))
|
|
129
|
+
} else if (target !== null && typeof target === 'object') {
|
|
130
|
+
for (const [condition, value] of Object.entries(target)) {
|
|
131
|
+
if (condition !== 'types' && condition !== 'react-native' && condition !== 'node') {
|
|
132
|
+
collectExportTargets(value, into)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import type { SourcePatch } from './define.ts'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A patch that makes a library file's `Platform.OS` checks see the simulated device rather than `web`. For a
|
|
7
|
+
* module's JS layer whose branches decide what the native module offers (iOS-only reminders, web-only refusals),
|
|
8
|
+
* when the native module under it is simulated.
|
|
9
|
+
*/
|
|
10
|
+
export function simulatedPlatform(file: string): SourcePatch {
|
|
11
|
+
return {
|
|
12
|
+
file,
|
|
13
|
+
replace: (source) =>
|
|
14
|
+
/\bPlatform\.OS\b/.test(source)
|
|
15
|
+
? `import { platform as __webSimPlatform } from 'web-sim/runtime';\n${source.replace(/\bPlatform\.OS\b/g, '__webSimPlatform()')}`
|
|
16
|
+
: source,
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const PLATFORM_IMAGE = /\brequire\(\s*(['"])(\.{1,2}\/[^'"]+)\.(png|jpe?g|gif|webp)\1\s*\)/g
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A dependency's source, for a file that sees the device's platform: `process.env.EXPO_OS` is read from the simulator
|
|
24
|
+
* as the app runs, and an image with `.ios` / `.android` variants (`back-icon@3x.ios.png`) loads the device's one,
|
|
25
|
+
* as Metro picks it. Both are decided when the app runs, not written in, so the pre-bundle is the same for both
|
|
26
|
+
* platforms. `file` is the file's path, which relative image paths start from.
|
|
27
|
+
*/
|
|
28
|
+
export function devicePlatformSource(source: string, file: string): string {
|
|
29
|
+
let body = source.replaceAll('process.env.EXPO_OS', '__webSimPlatform()')
|
|
30
|
+
body = body.replace(PLATFORM_IMAGE, (whole: string, quote: string, stem: string, extension: string) => {
|
|
31
|
+
const ios = platformVariant(file, stem, extension, 'ios')
|
|
32
|
+
const android = platformVariant(file, stem, extension, 'android')
|
|
33
|
+
if (ios === null && android === null) {
|
|
34
|
+
return whole
|
|
35
|
+
}
|
|
36
|
+
const load = (variant: string | null) => (variant === null ? whole : `require(${quote}${variant}${quote})`)
|
|
37
|
+
return `(__webSimPlatform() === 'ios' ? ${load(ios)} : __webSimPlatform() === 'android' ? ${load(android)} : ${whole})`
|
|
38
|
+
})
|
|
39
|
+
if (body === source) {
|
|
40
|
+
return source
|
|
41
|
+
}
|
|
42
|
+
return /^\s*(import|export)\b/m.test(source)
|
|
43
|
+
? `import { platform as __webSimPlatform } from 'web-sim/runtime';\n${body}`
|
|
44
|
+
: `var __webSimPlatform = require('web-sim/runtime').platform;\n${body}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The sharpest of an image's variants for one platform, as a path from the importing file, or null. */
|
|
48
|
+
function platformVariant(file: string, stem: string, extension: string, platform: 'ios' | 'android'): string | null {
|
|
49
|
+
for (const scale of ['@3x', '@2x', '@1x', '']) {
|
|
50
|
+
const candidate = `${stem}${scale}.${platform}.${extension}`
|
|
51
|
+
if (existsSync(path.resolve(path.dirname(file), candidate))) {
|
|
52
|
+
return candidate
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { type Loader, type Plugin as EsbuildPlugin, transform } from 'esbuild'
|
|
4
|
+
import type { Plugin } from 'vite'
|
|
5
|
+
import { RUNTIME_ENTRY } from '../paths.ts'
|
|
6
|
+
import { devicePlatformSource } from './platformPatch.ts'
|
|
7
|
+
import { applyPatches, type FileOverride, type OverrideRegistry } from './registry.ts'
|
|
8
|
+
|
|
9
|
+
const ORIGINAL = 'web-sim:original'
|
|
10
|
+
const ORIGINAL_PREFIX = '\0web-sim-original:'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Applies the overrides to dependencies as Vite pre-bundles them, which is where nearly all of a package's files are
|
|
14
|
+
* loaded. The plugin is named after a hash of the overrides, because Vite keys the pre-bundle by esbuild plugin
|
|
15
|
+
* names: an edited override then rebuilds it, and browsers fetch the new bundle.
|
|
16
|
+
*/
|
|
17
|
+
export function overridesEsbuild(registry: OverrideRegistry): EsbuildPlugin {
|
|
18
|
+
return {
|
|
19
|
+
name: `web-sim-overrides-${registry.hash()}`,
|
|
20
|
+
setup(build) {
|
|
21
|
+
build.onResolve({ filter: /^web-sim\/runtime$/ }, () => ({ path: RUNTIME_ENTRY }))
|
|
22
|
+
build.onResolve({ filter: /^web-sim:original$/ }, ({ importer }) => ({
|
|
23
|
+
path: importer,
|
|
24
|
+
namespace: 'web-sim-original',
|
|
25
|
+
}))
|
|
26
|
+
// A replacement's relative imports find files beside it first (a plugin's shared modules), then the package's.
|
|
27
|
+
build.onResolve({ filter: /^\.\.?\// }, ({ path: source, pluginData }) => {
|
|
28
|
+
const own = typeof pluginData?.overrideFile === 'string' ? resolveBeside(pluginData.overrideFile, source) : null
|
|
29
|
+
return own === null ? undefined : { path: own }
|
|
30
|
+
})
|
|
31
|
+
build.onLoad({ filter: /.*/, namespace: 'web-sim-original' }, ({ path: file }) => ({
|
|
32
|
+
contents: readFileSync(file, 'utf8'),
|
|
33
|
+
loader: loaderFor(file),
|
|
34
|
+
resolveDir: path.dirname(file),
|
|
35
|
+
}))
|
|
36
|
+
build.onLoad({ filter: /[\\/]node_modules[\\/]/ }, ({ path: file }) => {
|
|
37
|
+
const override = registry.overrideForFile(file)
|
|
38
|
+
const loaded = override === null ? undefined : loadOverride(file, override)
|
|
39
|
+
if (!registry.seesDevicePlatform(file) || !/\.[cm]?[jt]sx?$/.test(file) || (override !== null && override.kind !== 'patch')) {
|
|
40
|
+
return loaded
|
|
41
|
+
}
|
|
42
|
+
const source = loaded?.contents ?? readFileSync(file, 'utf8')
|
|
43
|
+
const contents = devicePlatformSource(source, file)
|
|
44
|
+
return contents === source ? loaded : { contents, loader: loaderFor(file), resolveDir: path.dirname(file) }
|
|
45
|
+
})
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function loadOverride(file: string, override: FileOverride) {
|
|
51
|
+
switch (override.kind) {
|
|
52
|
+
case 'replace':
|
|
53
|
+
return {
|
|
54
|
+
contents: readFileSync(override.file, 'utf8'),
|
|
55
|
+
loader: loaderFor(override.file),
|
|
56
|
+
// Compiled as if it sat where the file it replaces sits.
|
|
57
|
+
resolveDir: path.dirname(file),
|
|
58
|
+
watchFiles: [override.file],
|
|
59
|
+
pluginData: { overrideFile: override.file },
|
|
60
|
+
}
|
|
61
|
+
case 'stub':
|
|
62
|
+
// CommonJS, so importers may take any name from it.
|
|
63
|
+
return { contents: `${STUB_FACTORY}\nmodule.exports = createStub(${JSON.stringify(override.info.name)});`, loader: 'js' as const }
|
|
64
|
+
case 'patch':
|
|
65
|
+
return {
|
|
66
|
+
contents: applyPatches(readFileSync(file, 'utf8'), override),
|
|
67
|
+
loader: loaderFor(file),
|
|
68
|
+
resolveDir: path.dirname(file),
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The same overrides for files Vite serves without pre-bundling: excluded or linked dependencies.
|
|
75
|
+
*/
|
|
76
|
+
export function overridesPlugin(registry: OverrideRegistry): Plugin {
|
|
77
|
+
return {
|
|
78
|
+
name: 'web-sim:overrides',
|
|
79
|
+
enforce: 'pre',
|
|
80
|
+
resolveId(source, importer) {
|
|
81
|
+
if (source === 'web-sim/runtime') {
|
|
82
|
+
return RUNTIME_ENTRY
|
|
83
|
+
}
|
|
84
|
+
if (source === ORIGINAL && importer !== undefined) {
|
|
85
|
+
return ORIGINAL_PREFIX + importer.split('?')[0]
|
|
86
|
+
}
|
|
87
|
+
if (/^\.\.?\//.test(source) && importer !== undefined) {
|
|
88
|
+
const override = registry.overrideForFile(importer.split('?')[0])
|
|
89
|
+
if (override?.kind === 'replace') {
|
|
90
|
+
return resolveBeside(override.file, source)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return null
|
|
94
|
+
},
|
|
95
|
+
async load(id) {
|
|
96
|
+
if (id.startsWith(ORIGINAL_PREFIX)) {
|
|
97
|
+
const file = id.slice(ORIGINAL_PREFIX.length)
|
|
98
|
+
return compile(readFileSync(file, 'utf8'), file)
|
|
99
|
+
}
|
|
100
|
+
const file = id.split('?')[0]
|
|
101
|
+
const override = registry.overrideForFile(file)
|
|
102
|
+
if (override === null) {
|
|
103
|
+
if (!registry.seesDevicePlatform(file) || !/\.[cm]?[jt]sx?$/.test(file)) {
|
|
104
|
+
return null
|
|
105
|
+
}
|
|
106
|
+
const source = readFileSync(file, 'utf8')
|
|
107
|
+
const contents = devicePlatformSource(source, file)
|
|
108
|
+
return contents === source ? null : contents
|
|
109
|
+
}
|
|
110
|
+
switch (override.kind) {
|
|
111
|
+
case 'replace':
|
|
112
|
+
this.addWatchFile(override.file)
|
|
113
|
+
return compile(readFileSync(override.file, 'utf8'), override.file)
|
|
114
|
+
case 'stub':
|
|
115
|
+
return `${STUB_FACTORY}\nexport default createStub(${JSON.stringify(override.info.name)});`
|
|
116
|
+
case 'patch': {
|
|
117
|
+
const source = applyPatches(readFileSync(file, 'utf8'), override)
|
|
118
|
+
return registry.seesDevicePlatform(file) ? devicePlatformSource(source, file) : source
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const SOURCE_EXTENSIONS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '/index.ts', '/index.tsx', '/index.js']
|
|
126
|
+
|
|
127
|
+
/** `source` relative to the replacement file `file`, when a file is there. */
|
|
128
|
+
function resolveBeside(file: string, source: string): string | null {
|
|
129
|
+
const base = path.resolve(path.dirname(file), source)
|
|
130
|
+
for (const extension of SOURCE_EXTENSIONS) {
|
|
131
|
+
const candidate = base + extension
|
|
132
|
+
if (existsSync(candidate) && statSync(candidate).isFile()) {
|
|
133
|
+
return candidate
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return null
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function compile(source: string, file: string): Promise<string> {
|
|
140
|
+
const result = await transform(source, { loader: loaderFor(file), jsx: 'automatic', format: 'esm', sourcefile: file })
|
|
141
|
+
return result.code
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function loaderFor(file: string): Loader {
|
|
145
|
+
const extension = path.extname(file)
|
|
146
|
+
return extension === '.ts' ? 'ts' : extension === '.tsx' ? 'tsx' : extension === '.css' ? 'css' : 'jsx'
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A stub where any property read, call or construction returns another stub, so `Module.configure().then` chains
|
|
151
|
+
* succeed and do nothing. `then` is undefined, so a stub is never mistaken for a promise.
|
|
152
|
+
*/
|
|
153
|
+
export const STUB_FACTORY = `
|
|
154
|
+
function createStub(name) {
|
|
155
|
+
const target = function () {};
|
|
156
|
+
return new Proxy(target, {
|
|
157
|
+
get(_, property) {
|
|
158
|
+
if (property === 'then' || typeof property === 'symbol') return undefined;
|
|
159
|
+
if (property === '__esModule') return false;
|
|
160
|
+
if (property === 'toString') return () => '[web-sim stub ' + name + ']';
|
|
161
|
+
return createStub(name + '.' + property);
|
|
162
|
+
},
|
|
163
|
+
apply() { return createStub(name + '()'); },
|
|
164
|
+
construct() { return createStub('new ' + name); },
|
|
165
|
+
});
|
|
166
|
+
}`
|