@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.
- 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 +157 -0
- package/overrides/react-native-web/useElementLayout.ts +152 -0
- package/package.json +80 -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 +129 -0
- package/src/client/app/appFocus.ts +97 -0
- package/src/client/app/console.ts +118 -0
- package/src/client/app/fonts.ts +76 -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 +23 -0
- package/src/devices/catalog.ts +223 -0
- package/src/devices/types.ts +83 -0
- package/src/node/appInfo.ts +188 -0
- package/src/node/appSource.ts +140 -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/fonts.ts +377 -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 +169 -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 +254 -0
- package/src/node/worklets.ts +86 -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 +519 -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,377 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { inflateSync } from 'node:zlib'
|
|
5
|
+
import type { BundledFont, BundledFonts } from '../runtime/index.ts'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The fonts a native build of the app embeds, as `@font-face` rules for the simulated platform, so the app's custom
|
|
9
|
+
* fonts draw whether or not they are installed on the computer. Fonts the app loads at runtime (`useFonts`,
|
|
10
|
+
* `Font.loadAsync`) need nothing here: expo-font's web build registers those itself.
|
|
11
|
+
*
|
|
12
|
+
* Each platform names an embedded font its own way, and a family resolves here as it does on that platform:
|
|
13
|
+
*
|
|
14
|
+
* - iOS reads the names inside the file. `fontFamily` is a family name (with `fontWeight` and `fontStyle` picking the
|
|
15
|
+
* face), or one face's PostScript or full name. The files come from expo-font's config plugin (`fonts`,
|
|
16
|
+
* `ios.fonts`) and from `UIAppFonts` in the native project's `Info.plist`, which any other plugin writes to.
|
|
17
|
+
* - Android names a font by its file: `assets/fonts/Inter.ttf` is `Inter`, and `Inter_bold.ttf`, `Inter_italic.ttf`
|
|
18
|
+
* and `Inter_bold_italic.ttf` are its other styles. A family registered with `ReactFontManager.addCustomFont` (in
|
|
19
|
+
* `MainApplication`, as expo-font's object syntax does) takes its name from that call and its faces from the
|
|
20
|
+
* `res/font` XML it points at.
|
|
21
|
+
*
|
|
22
|
+
* An app without a native project for a platform (continuous native generation) may embed fonts through a config
|
|
23
|
+
* plugin web-sim can't run. When expo-font's plugin lists none for that platform either, the font files in the
|
|
24
|
+
* project (outside `node_modules`, build output and hidden folders) count as embedded.
|
|
25
|
+
*/
|
|
26
|
+
export function readBundledFonts(root: string, expo: Record<string, any>): BundledFonts {
|
|
27
|
+
const files = new FontFileIndex(root)
|
|
28
|
+
const plugin = expoFontOptions(expo)
|
|
29
|
+
const resolve = (entry: string) => resolveFontPaths(entry, root)
|
|
30
|
+
|
|
31
|
+
const ios = new FaceList(root)
|
|
32
|
+
const iosFiles = new Set<string>()
|
|
33
|
+
for (const entry of [...(plugin.fonts ?? []), ...(plugin.ios?.fonts ?? [])]) {
|
|
34
|
+
if (typeof entry === 'string') {
|
|
35
|
+
resolve(entry).forEach((file) => iosFiles.add(file))
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const iosProject = path.join(root, 'ios')
|
|
39
|
+
const appFonts = [...asStrings(expo.ios?.infoPlist?.UIAppFonts), ...(existsSync(iosProject) ? infoPlistFonts(iosProject) : [])]
|
|
40
|
+
for (const name of appFonts) {
|
|
41
|
+
const file = files.find(name, iosProject)
|
|
42
|
+
if (file !== undefined) {
|
|
43
|
+
iosFiles.add(file)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!existsSync(iosProject) && iosFiles.size === 0) {
|
|
47
|
+
files.outsideNativeProjects().forEach((file) => iosFiles.add(file))
|
|
48
|
+
}
|
|
49
|
+
for (const file of iosFiles) {
|
|
50
|
+
ios.addIos(file)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const android = new FaceList(root)
|
|
54
|
+
const androidProject = path.join(root, 'android')
|
|
55
|
+
for (const entry of [...(plugin.fonts ?? []), ...(plugin.android?.fonts ?? [])]) {
|
|
56
|
+
if (typeof entry === 'string') {
|
|
57
|
+
resolve(entry).forEach((file) => android.addAndroidAsset(file))
|
|
58
|
+
} else if (entry !== null && typeof entry === 'object' && typeof (entry as FontObject).fontFamily === 'string') {
|
|
59
|
+
const font = entry as FontObject & { fontFamily: string }
|
|
60
|
+
for (const definition of Array.isArray(font.fontDefinitions) ? font.fontDefinitions : []) {
|
|
61
|
+
const file = definition?.path ?? font.path
|
|
62
|
+
if (typeof file === 'string') {
|
|
63
|
+
resolve(file).forEach((resolved) => android.add(font.fontFamily, resolved, String(definition.weight ?? 400), definition.style === 'italic' ? 'italic' : 'normal'))
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (existsSync(androidProject)) {
|
|
69
|
+
const main = path.join(androidProject, 'app', 'src', 'main')
|
|
70
|
+
for (const file of listFonts(path.join(main, 'assets', 'fonts'))) {
|
|
71
|
+
android.addAndroidAsset(file)
|
|
72
|
+
}
|
|
73
|
+
for (const [family, resource] of customFonts(main)) {
|
|
74
|
+
for (const face of resourceFontFaces(path.join(main, 'res', 'font'), resource)) {
|
|
75
|
+
android.add(family, face.file, face.weight, face.style)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
} else if (android.faces.length === 0) {
|
|
79
|
+
files.outsideNativeProjects().forEach((file) => android.addAndroidAsset(file))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { ios: ios.faces, android: android.faces }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type FontObject = { fontFamily?: string; path?: string; fontDefinitions?: { path?: string; weight?: number; style?: string }[] }
|
|
86
|
+
type ExpoFontOptions = { fonts?: unknown[]; ios?: { fonts?: unknown[] }; android?: { fonts?: unknown[] } }
|
|
87
|
+
|
|
88
|
+
function expoFontOptions(expo: Record<string, any>): ExpoFontOptions {
|
|
89
|
+
const plugins: unknown[] = Array.isArray(expo.plugins) ? expo.plugins : []
|
|
90
|
+
const entry = plugins.find((plugin) => Array.isArray(plugin) && plugin[0] === 'expo-font')
|
|
91
|
+
return Array.isArray(entry) && entry[1] !== null && typeof entry[1] === 'object' ? (entry[1] as ExpoFontOptions) : {}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const asStrings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])
|
|
95
|
+
|
|
96
|
+
const FONT_EXTENSIONS = ['.ttf', '.otf', '.woff', '.woff2']
|
|
97
|
+
const isFont = (file: string) => FONT_EXTENSIONS.includes(path.extname(file).toLowerCase())
|
|
98
|
+
|
|
99
|
+
function listFonts(dir: string): string[] {
|
|
100
|
+
return existsSync(dir) ? readdirSync(dir).filter(isFont).map((name) => path.join(dir, name)) : []
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A path as expo-font's plugin resolves it: relative to the project, else as a package path; a folder is its fonts. */
|
|
104
|
+
function resolveFontPaths(entry: string, root: string): string[] {
|
|
105
|
+
let file = path.resolve(root, entry)
|
|
106
|
+
if (!existsSync(file)) {
|
|
107
|
+
try {
|
|
108
|
+
file = createRequire(path.join(root, 'package.json')).resolve(entry)
|
|
109
|
+
} catch {
|
|
110
|
+
console.warn(`web-sim: expo-font's config plugin lists ${entry}, which doesn't exist`)
|
|
111
|
+
return []
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return statSync(file).isDirectory() ? listFonts(file) : isFont(file) ? [file] : []
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The font files `UIAppFonts` lists, from each `Info.plist` in the iOS project. */
|
|
118
|
+
function infoPlistFonts(iosProject: string): string[] {
|
|
119
|
+
const names: string[] = []
|
|
120
|
+
for (const entry of readdirSync(iosProject, { withFileTypes: true })) {
|
|
121
|
+
const plist = path.join(iosProject, entry.name, 'Info.plist')
|
|
122
|
+
if (!entry.isDirectory() || entry.name === 'Pods' || !existsSync(plist)) {
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
const array = /<key>UIAppFonts<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(readFileSync(plist, 'utf8'))
|
|
126
|
+
for (const [, name] of array?.[1].matchAll(/<string>([^<]+)<\/string>/g) ?? []) {
|
|
127
|
+
names.push(name.trim())
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return names
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The families `MainApplication` registers with `ReactFontManager.addCustomFont`, and the font resource of each. */
|
|
134
|
+
function customFonts(main: string): [string, string][] {
|
|
135
|
+
const found: [string, string][] = []
|
|
136
|
+
const visit = (dir: string) => {
|
|
137
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
138
|
+
const file = path.join(dir, entry.name)
|
|
139
|
+
if (entry.isDirectory()) {
|
|
140
|
+
visit(file)
|
|
141
|
+
} else if (/^MainApplication\.(kt|java)$/.test(entry.name)) {
|
|
142
|
+
for (const [, family, resource] of readFileSync(file, 'utf8').matchAll(/addCustomFont\(\s*[\w.]+\s*,\s*"([^"]+)"\s*,\s*R\.font\.(\w+)\s*\)/g)) {
|
|
143
|
+
found.push([family, resource])
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const sources = [path.join(main, 'java'), path.join(main, 'kotlin')].filter(existsSync)
|
|
149
|
+
sources.forEach(visit)
|
|
150
|
+
return found
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A `res/font` resource's faces: the `<font>`s of its XML font family, or the one font file of that name. */
|
|
154
|
+
function resourceFontFaces(resDir: string, resource: string): { file: string; weight: string; style: 'normal' | 'italic' }[] {
|
|
155
|
+
const xml = path.join(resDir, `${resource}.xml`)
|
|
156
|
+
if (!existsSync(xml)) {
|
|
157
|
+
const file = listFonts(resDir).find((candidate) => path.parse(candidate).name === resource)
|
|
158
|
+
return file === undefined ? [] : [{ file, weight: '400', style: 'normal' }]
|
|
159
|
+
}
|
|
160
|
+
const faces: { file: string; weight: string; style: 'normal' | 'italic' }[] = []
|
|
161
|
+
for (const [tag] of readFileSync(xml, 'utf8').matchAll(/<font\b[^>]*>/g)) {
|
|
162
|
+
const attribute = (name: string) => new RegExp(`(?:app|android):${name}="([^"]*)"`).exec(tag)?.[1]
|
|
163
|
+
const name = attribute('font')?.replace(/^@font\//, '')
|
|
164
|
+
const file = listFonts(resDir).find((candidate) => path.parse(candidate).name === name)
|
|
165
|
+
if (file !== undefined) {
|
|
166
|
+
faces.push({ file, weight: attribute('fontWeight') ?? '400', style: attribute('fontStyle') === 'italic' ? 'italic' : 'normal' })
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return faces
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const SKIPPED_DIRS = new Set(['node_modules', 'Pods', 'build', 'dist', 'DerivedData'])
|
|
173
|
+
|
|
174
|
+
/** The font files in the project, outside `node_modules`, build output and hidden folders. */
|
|
175
|
+
class FontFileIndex {
|
|
176
|
+
private files: string[] | null = null
|
|
177
|
+
private readonly root: string
|
|
178
|
+
|
|
179
|
+
constructor(root: string) {
|
|
180
|
+
this.root = root
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private all(): string[] {
|
|
184
|
+
if (this.files === null) {
|
|
185
|
+
this.files = []
|
|
186
|
+
const visit = (dir: string, depth: number) => {
|
|
187
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
188
|
+
if (entry.name.startsWith('.') || SKIPPED_DIRS.has(entry.name)) {
|
|
189
|
+
continue
|
|
190
|
+
}
|
|
191
|
+
const file = path.join(dir, entry.name)
|
|
192
|
+
if (entry.isDirectory() && depth < 8) {
|
|
193
|
+
visit(file, depth + 1)
|
|
194
|
+
} else if (entry.isFile() && isFont(entry.name)) {
|
|
195
|
+
this.files!.push(file)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
visit(this.root, 0)
|
|
200
|
+
}
|
|
201
|
+
return this.files
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** A file by its name, as Xcode bundles it: one in the iOS project first, then one outside the Android project. */
|
|
205
|
+
find(name: string, iosProject: string): string | undefined {
|
|
206
|
+
const matches = this.all().filter((file) => path.basename(file) === name)
|
|
207
|
+
const android = path.join(this.root, 'android') + path.sep
|
|
208
|
+
return matches.find((file) => file.startsWith(iosProject + path.sep)) ?? matches.find((file) => !file.startsWith(android)) ?? matches[0]
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
outsideNativeProjects(): string[] {
|
|
212
|
+
const native = ['ios', 'android'].map((dir) => path.join(this.root, dir) + path.sep)
|
|
213
|
+
return this.all().filter((file) => !native.some((dir) => file.startsWith(dir)))
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Android's suffixes for an asset font's other styles: `Inter_bold.ttf` is `Inter` in bold. */
|
|
218
|
+
const ASSET_STYLES: [string, string, 'normal' | 'italic'][] = [
|
|
219
|
+
['_bold_italic', '700', 'italic'],
|
|
220
|
+
['_bold', '700', 'normal'],
|
|
221
|
+
['_italic', '400', 'italic'],
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
class FaceList {
|
|
225
|
+
readonly faces: BundledFont[] = []
|
|
226
|
+
private readonly root: string
|
|
227
|
+
|
|
228
|
+
constructor(root: string) {
|
|
229
|
+
this.root = root
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
add(family: string, file: string, weight: string, style: 'normal' | 'italic'): void {
|
|
233
|
+
const url = this.url(file)
|
|
234
|
+
if (!this.faces.some((face) => face.family === family && face.weight === weight && face.style === style)) {
|
|
235
|
+
this.faces.push({ family, url, weight, style })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* An iOS font by the names in it. Its family (the typographic family, and the legacy one where they differ) picks
|
|
241
|
+
* a face by weight and style. Its PostScript and full names are that one face, whatever the weight asked for.
|
|
242
|
+
*/
|
|
243
|
+
addIos(file: string): void {
|
|
244
|
+
const font = readFontNames(file)
|
|
245
|
+
if (font === null) {
|
|
246
|
+
console.warn(`web-sim: could not read the names in ${path.relative(this.root, file)}, so it isn't loaded`)
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
const families = new Set([font.typographicFamily, font.family].filter((name): name is string => name !== undefined))
|
|
250
|
+
for (const family of families) {
|
|
251
|
+
this.add(family, file, String(font.weight), font.italic ? 'italic' : 'normal')
|
|
252
|
+
}
|
|
253
|
+
for (const name of [font.postScriptName, font.fullName]) {
|
|
254
|
+
if (name !== undefined && !families.has(name)) {
|
|
255
|
+
this.add(name, file, '1 1000', font.italic ? 'italic' : 'normal')
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** An Android asset font, named by its file. */
|
|
261
|
+
addAndroidAsset(file: string): void {
|
|
262
|
+
if (!['.ttf', '.otf'].includes(path.extname(file).toLowerCase())) {
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
const name = path.parse(file).name
|
|
266
|
+
this.add(name, file, '400', 'normal')
|
|
267
|
+
const styled = ASSET_STYLES.find(([suffix]) => name.endsWith(suffix) && name.length > suffix.length)
|
|
268
|
+
if (styled !== undefined) {
|
|
269
|
+
this.add(name.slice(0, -styled[0].length), file, styled[1], styled[2])
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Where the dev server serves a file: from the project, or through `/@fs/` when it is outside (a monorepo's). */
|
|
274
|
+
private url(file: string): string {
|
|
275
|
+
const relative = path.relative(this.root, file)
|
|
276
|
+
const outside = relative.startsWith('..') || path.isAbsolute(relative)
|
|
277
|
+
return encodeURI(outside ? `/@fs${file.split(path.sep).join('/')}` : `/${relative.split(path.sep).join('/')}`)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
type FontNames = {
|
|
282
|
+
family?: string
|
|
283
|
+
typographicFamily?: string
|
|
284
|
+
fullName?: string
|
|
285
|
+
postScriptName?: string
|
|
286
|
+
weight: number
|
|
287
|
+
italic: boolean
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The names, weight and slant of a TrueType, OpenType or WOFF font, from its `name`, `OS/2` and `head` tables. */
|
|
291
|
+
export function readFontNames(file: string): FontNames | null {
|
|
292
|
+
try {
|
|
293
|
+
const tables = readTables(readFileSync(file))
|
|
294
|
+
const name = tables.get('name')
|
|
295
|
+
if (name === undefined) {
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
const names = readNameTable(name)
|
|
299
|
+
const os2 = tables.get('OS/2')
|
|
300
|
+
const head = tables.get('head')
|
|
301
|
+
const weight = os2 !== undefined && os2.length >= 6 ? os2.readUInt16BE(4) : 400
|
|
302
|
+
const italic = (os2 !== undefined && os2.length >= 64 && (os2.readUInt16BE(62) & 1) !== 0) || (head !== undefined && head.length >= 46 && (head.readUInt16BE(44) & 2) !== 0)
|
|
303
|
+
return {
|
|
304
|
+
family: names.get(1),
|
|
305
|
+
typographicFamily: names.get(16),
|
|
306
|
+
fullName: names.get(4),
|
|
307
|
+
postScriptName: names.get(6),
|
|
308
|
+
weight: Math.min(1000, Math.max(1, weight || 400)),
|
|
309
|
+
italic,
|
|
310
|
+
}
|
|
311
|
+
} catch {
|
|
312
|
+
return null
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function readTables(data: Buffer): Map<string, Buffer> {
|
|
317
|
+
const tables = new Map<string, Buffer>()
|
|
318
|
+
const signature = data.toString('latin1', 0, 4)
|
|
319
|
+
if (signature === 'wOFF') {
|
|
320
|
+
const count = data.readUInt16BE(12)
|
|
321
|
+
for (let i = 0; i < count; i++) {
|
|
322
|
+
const record = 44 + i * 20
|
|
323
|
+
const tag = data.toString('latin1', record, record + 4)
|
|
324
|
+
const offset = data.readUInt32BE(record + 4)
|
|
325
|
+
const compressed = data.readUInt32BE(record + 8)
|
|
326
|
+
const length = data.readUInt32BE(record + 12)
|
|
327
|
+
const bytes = data.subarray(offset, offset + compressed)
|
|
328
|
+
tables.set(tag, compressed < length ? inflateSync(bytes) : bytes)
|
|
329
|
+
}
|
|
330
|
+
return tables
|
|
331
|
+
}
|
|
332
|
+
if (signature !== '\0\x01\0\0' && signature !== 'OTTO' && signature !== 'true') {
|
|
333
|
+
// WOFF2's tables are one Brotli stream with its own directory format, and a collection holds several fonts.
|
|
334
|
+
return tables
|
|
335
|
+
}
|
|
336
|
+
const count = data.readUInt16BE(4)
|
|
337
|
+
for (let i = 0; i < count; i++) {
|
|
338
|
+
const record = 12 + i * 16
|
|
339
|
+
const offset = data.readUInt32BE(record + 8)
|
|
340
|
+
tables.set(data.toString('latin1', record, record + 4), data.subarray(offset, offset + data.readUInt32BE(record + 12)))
|
|
341
|
+
}
|
|
342
|
+
return tables
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Name IDs to strings, preferring Windows US English (UTF-16), then any Windows Unicode, then Mac Roman. */
|
|
346
|
+
function readNameTable(table: Buffer): Map<number, string> {
|
|
347
|
+
const count = table.readUInt16BE(2)
|
|
348
|
+
const strings = table.readUInt16BE(4)
|
|
349
|
+
const ranked = new Map<number, { rank: number; value: string }>()
|
|
350
|
+
for (let i = 0; i < count; i++) {
|
|
351
|
+
const record = 6 + i * 12
|
|
352
|
+
const platform = table.readUInt16BE(record)
|
|
353
|
+
const encoding = table.readUInt16BE(record + 2)
|
|
354
|
+
const language = table.readUInt16BE(record + 4)
|
|
355
|
+
const id = table.readUInt16BE(record + 6)
|
|
356
|
+
const bytes = table.subarray(strings + table.readUInt16BE(record + 10), strings + table.readUInt16BE(record + 10) + table.readUInt16BE(record + 8))
|
|
357
|
+
let rank: number
|
|
358
|
+
let value: string
|
|
359
|
+
if (platform === 3 && (encoding === 1 || encoding === 10)) {
|
|
360
|
+
rank = language === 0x409 ? 0 : 1
|
|
361
|
+
value = Buffer.from(bytes).swap16().toString('utf16le')
|
|
362
|
+
} else if (platform === 0) {
|
|
363
|
+
rank = 2
|
|
364
|
+
value = Buffer.from(bytes).swap16().toString('utf16le')
|
|
365
|
+
} else if (platform === 1 && encoding === 0) {
|
|
366
|
+
rank = 3
|
|
367
|
+
value = bytes.toString('latin1')
|
|
368
|
+
} else {
|
|
369
|
+
continue
|
|
370
|
+
}
|
|
371
|
+
const current = ranked.get(id)
|
|
372
|
+
if (value.trim() !== '' && (current === undefined || rank < current.rank)) {
|
|
373
|
+
ranked.set(id, { rank, value: value.trim() })
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return new Map([...ranked].map(([id, { value }]) => [id, value]))
|
|
377
|
+
}
|
|
@@ -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'
|