@nativue/core 0.11.1 → 0.13.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/AGENTS.md +2 -1
- package/Package.swift +1 -1
- package/README.md +1 -1
- package/android/build.gradle.kts +5 -3
- package/android/src/main/java/dev/nativue/Accessibility.kt +5 -3
- package/android/src/main/java/dev/nativue/AnimatedGraph.kt +2 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +81 -22
- package/android/src/main/java/dev/nativue/DownloadBanner.kt +45 -0
- package/android/src/main/java/dev/nativue/ErrorOverlay.kt +5 -4
- package/android/src/main/java/dev/nativue/LayoutAnimation.kt +14 -11
- package/android/src/main/java/dev/nativue/NativeNode.kt +11 -6
- package/android/src/main/java/dev/nativue/NativueActivity.kt +34 -7
- package/android/src/main/java/dev/nativue/Navigation.kt +7 -4
- package/android/src/main/java/dev/nativue/Style.kt +7 -1
- package/android/src/main/java/dev/nativue/SystemBars.kt +14 -16
- package/cli/hot-client.js +192 -0
- package/cli/link.mjs +1 -1
- package/cli/nativue.mjs +228 -54
- package/cli/symbolicate.mjs +26 -14
- package/ios/Accessibility.swift +18 -5
- package/ios/AnimatedGraph.swift +20 -12
- package/ios/Bridge.swift +68 -16
- package/ios/DownloadBanner.swift +38 -0
- package/ios/KeyValueStorage.swift +2 -2
- package/ios/NativeNode.swift +23 -9
- package/ios/NativueView.swift +25 -0
- package/ios/TextLabel.swift +14 -0
- package/package.json +1 -1
- package/src/globals.ts +1 -0
- package/src/renderer.ts +1 -0
- package/src/router.ts +29 -0
- package/src/types.ts +3 -0
|
@@ -2,10 +2,9 @@ package dev.nativue
|
|
|
2
2
|
|
|
3
3
|
import android.graphics.Color
|
|
4
4
|
import android.os.Build
|
|
5
|
-
import android.view.View
|
|
6
5
|
import android.view.Window
|
|
7
|
-
import android.view.WindowInsetsController
|
|
8
6
|
import android.view.WindowManager
|
|
7
|
+
import androidx.core.view.WindowCompat
|
|
9
8
|
|
|
10
9
|
/** The status and navigation bars: transparent, over the screens, with icons that contrast with them. */
|
|
11
10
|
@Suppress("DEPRECATION") // the APIs older Android versions need
|
|
@@ -17,24 +16,23 @@ object SystemBars {
|
|
|
17
16
|
fun drawBehind(window: Window) {
|
|
18
17
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) return
|
|
19
18
|
|
|
20
|
-
|
|
19
|
+
WindowCompat.setDecorFitsSystemWindows(window, false)
|
|
21
20
|
window.statusBarColor = Color.TRANSPARENT
|
|
22
|
-
|
|
23
|
-
window.
|
|
21
|
+
// Before Android 8 the navigation bar's icons are always light: a scrim keeps them readable.
|
|
22
|
+
window.navigationBarColor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Color.TRANSPARENT else NAVIGATION_BAR_SCRIM
|
|
23
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
24
|
+
window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
|
|
25
|
+
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
|
26
|
+
window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
|
27
|
+
}
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
/** Dark icons on light screens, light icons on dark ones. */
|
|
27
31
|
fun setLight(window: Window, isLight: Boolean) {
|
|
28
|
-
val
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
// Android 11 keeps the theme's light-bar flags over setSystemBarsAppearance: they're set too.
|
|
33
|
-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) return
|
|
34
|
-
|
|
35
|
-
val decorView = window.decorView
|
|
36
|
-
val flags = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
|
|
37
|
-
decorView.systemUiVisibility =
|
|
38
|
-
if (isLight) decorView.systemUiVisibility or flags else decorView.systemUiVisibility and flags.inv()
|
|
32
|
+
val controller = WindowCompat.getInsetsController(window, window.decorView)
|
|
33
|
+
controller.isAppearanceLightStatusBars = isLight
|
|
34
|
+
controller.isAppearanceLightNavigationBars = isLight
|
|
39
35
|
}
|
|
36
|
+
|
|
37
|
+
private const val NAVIGATION_BAR_SCRIM = 0x80000000.toInt()
|
|
40
38
|
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Hot module replacement in the app: runs before the dev bundle, after Rolldown's DevRuntime. The dev
|
|
2
|
+
// server fills in __NATIVUE_HOT__ ({ clientId, serverURL }). Native code calls __hotUpdate(json) for
|
|
3
|
+
// each `data: hot` line; anything that can't be applied asks Vite for a full reload.
|
|
4
|
+
;(() => {
|
|
5
|
+
const { clientId, serverURL } = __NATIVUE_HOT__
|
|
6
|
+
const acceptCallbacksById = new Map()
|
|
7
|
+
const disposersById = new Map()
|
|
8
|
+
const dataById = new Map()
|
|
9
|
+
const listenersById = new Map()
|
|
10
|
+
let lastSequence = 0
|
|
11
|
+
let isReloadPending = false
|
|
12
|
+
let queue = Promise.resolve()
|
|
13
|
+
|
|
14
|
+
function send(event, data) {
|
|
15
|
+
fetch(`${serverURL}/hot`, {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
body: JSON.stringify({ clientId, message: { type: 'custom', event, data } }),
|
|
18
|
+
}).catch(() => {})
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function requestReload(reason) {
|
|
22
|
+
if (isReloadPending) return
|
|
23
|
+
|
|
24
|
+
isReloadPending = true
|
|
25
|
+
console.log(`[nativue] reload: ${reason}`)
|
|
26
|
+
send('vite:bundled-dev:reload-needed', { reason })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function hotContext(id) {
|
|
30
|
+
if (!dataById.has(id)) dataById.set(id, {})
|
|
31
|
+
acceptCallbacksById.set(id, [])
|
|
32
|
+
listenersById.set(id, [])
|
|
33
|
+
|
|
34
|
+
const accept = (deps, callback) => acceptCallbacksById.get(id).push({ deps, callback })
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
get data() {
|
|
38
|
+
return dataById.get(id)
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
accept(deps, callback) {
|
|
42
|
+
if (typeof deps === 'function' || !deps) accept([id], ([module]) => deps?.(module))
|
|
43
|
+
else if (typeof deps === 'string') accept([deps], ([module]) => callback?.(module))
|
|
44
|
+
else accept(deps, callback ?? (() => {}))
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
acceptExports(_names, callback) {
|
|
48
|
+
accept([id], ([module]) => callback?.(module))
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
dispose(callback) {
|
|
52
|
+
disposersById.set(id, callback)
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
invalidate() {
|
|
56
|
+
requestReload(`${id} invalidated itself`)
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
on(event, callback) {
|
|
60
|
+
listenersById.get(id).push({ event, callback })
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
off(event, callback) {
|
|
64
|
+
const listeners = listenersById.get(id)
|
|
65
|
+
listenersById.set(
|
|
66
|
+
id,
|
|
67
|
+
listeners.filter(
|
|
68
|
+
(listener) => listener.callback !== callback || listener.event !== event,
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
send(event, data) {
|
|
74
|
+
send(event, data)
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
prune() {},
|
|
78
|
+
decline() {},
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const acceptsDependency = (parent, id) =>
|
|
83
|
+
(acceptCallbacksById.get(parent) ?? []).some(({ deps }) => deps.includes(id))
|
|
84
|
+
|
|
85
|
+
function findBoundaries(changedIds) {
|
|
86
|
+
const boundaries = []
|
|
87
|
+
const updateSet = new Set()
|
|
88
|
+
|
|
89
|
+
function bubble(id) {
|
|
90
|
+
if (updateSet.has(id)) return
|
|
91
|
+
|
|
92
|
+
updateSet.add(id)
|
|
93
|
+
if (acceptsDependency(id, id)) return boundaries.push({ boundary: id, acceptedVia: id })
|
|
94
|
+
|
|
95
|
+
for (const parent of runtime
|
|
96
|
+
.getImporters(id)
|
|
97
|
+
.filter((parent) => runtime.isExecuted(parent))) {
|
|
98
|
+
if (acceptsDependency(parent, id)) boundaries.push({ boundary: parent, acceptedVia: id })
|
|
99
|
+
else bubble(parent)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
for (const id of changedIds) if (runtime.isExecuted(id)) bubble(id)
|
|
104
|
+
|
|
105
|
+
return { boundaries, updateSet }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function hasEntryWithoutBoundary({ boundaries, updateSet }) {
|
|
109
|
+
const reRun = new Set()
|
|
110
|
+
const pending = boundaries.map(({ acceptedVia }) => acceptedVia)
|
|
111
|
+
|
|
112
|
+
while (pending.length > 0) {
|
|
113
|
+
const id = pending.pop()
|
|
114
|
+
if (reRun.has(id) || !updateSet.has(id)) continue
|
|
115
|
+
|
|
116
|
+
reRun.add(id)
|
|
117
|
+
pending.push(...(runtime.staticImports.get(id)?.edges ?? []))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return [...updateSet].some((id) => runtime.isEntry(id) && !reRun.has(id))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function apply({ changedIds, url, seq }) {
|
|
124
|
+
if (isReloadPending) return
|
|
125
|
+
if (seq !== lastSequence + 1) return requestReload('missed an update')
|
|
126
|
+
|
|
127
|
+
lastSequence = seq
|
|
128
|
+
|
|
129
|
+
const update = findBoundaries(changedIds)
|
|
130
|
+
if (update.updateSet.size === 0) return
|
|
131
|
+
if (hasEntryWithoutBoundary(update)) return requestReload(`${changedIds.join(', ')} changed`)
|
|
132
|
+
|
|
133
|
+
const patch = await (await fetch(`${serverURL}/${url}`)).text()
|
|
134
|
+
;(0, eval)(`${patch}\n//# sourceURL=${url}`)
|
|
135
|
+
|
|
136
|
+
if ([...update.updateSet].some((id) => !runtime.hasFactory(id))) {
|
|
137
|
+
return requestReload('a module is missing from the update')
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const applies = update.boundaries.map(({ boundary, acceptedVia }) => ({
|
|
141
|
+
acceptedVia,
|
|
142
|
+
callbacks: acceptCallbacksById.get(boundary).filter(({ deps }) => deps.includes(acceptedVia)),
|
|
143
|
+
}))
|
|
144
|
+
|
|
145
|
+
for (const id of update.updateSet) runtime.removeModuleCache(id)
|
|
146
|
+
for (const { acceptedVia, callbacks } of applies) {
|
|
147
|
+
runtime.initModule(acceptedVia)
|
|
148
|
+
|
|
149
|
+
const exports = runtime.loadExports(acceptedVia)
|
|
150
|
+
for (const { deps, callback } of callbacks) {
|
|
151
|
+
callback(deps.map((dep) => (dep === acceptedVia ? exports : undefined)))
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
console.log(`[nativue] hot updated ${changedIds.join(', ')}`)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function notifyListeners(event, data) {
|
|
159
|
+
for (const listeners of listenersById.values()) {
|
|
160
|
+
for (const listener of listeners) if (listener.event === event) listener.callback(data)
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
class NativueDevRuntime extends DevRuntime {
|
|
165
|
+
payloadDelivered(filename) {
|
|
166
|
+
send('vite:bundled-dev:payload-delivered', { filename })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
createModuleHotContext(id) {
|
|
170
|
+
return hotContext(id)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const runtime = new NativueDevRuntime(clientId)
|
|
175
|
+
runtime.hooks = {
|
|
176
|
+
createModuleHotContext: (id) => runtime.createModuleHotContext(id),
|
|
177
|
+
onModuleCacheRemoval: (id) => disposersById.get(id)?.(dataById.get(id)),
|
|
178
|
+
}
|
|
179
|
+
globalThis.__rolldown_runtime__ = runtime
|
|
180
|
+
|
|
181
|
+
globalThis.__hotUpdate = (json) => {
|
|
182
|
+
const update = JSON.parse(json)
|
|
183
|
+
if (update.type === 'custom') return notifyListeners(update.event, update.data)
|
|
184
|
+
if (update.clientId !== clientId) return
|
|
185
|
+
|
|
186
|
+
send('nativue:received')
|
|
187
|
+
|
|
188
|
+
queue = queue
|
|
189
|
+
.then(() => apply(update))
|
|
190
|
+
.catch((error) => requestReload(error?.message ?? String(error)))
|
|
191
|
+
}
|
|
192
|
+
})()
|
package/cli/link.mjs
CHANGED
|
@@ -154,7 +154,7 @@ import PackageDescription
|
|
|
154
154
|
|
|
155
155
|
let package = Package(
|
|
156
156
|
name: "NativuePlugins",
|
|
157
|
-
platforms: [.iOS(.
|
|
157
|
+
platforms: [.iOS("15.1")],
|
|
158
158
|
products: [.library(name: "NativuePlugins", targets: ["${LIST_TARGET}"])],
|
|
159
159
|
dependencies: [
|
|
160
160
|
.package(path: "${corePath}"),
|
package/cli/nativue.mjs
CHANGED
|
@@ -3,31 +3,40 @@
|
|
|
3
3
|
// nativue build bundles src/app/ into ios/App/main.bundle.js (and, with an android/
|
|
4
4
|
// folder, android/app/src/main/assets/main.bundle.js); Hermes bytecode
|
|
5
5
|
// with --production
|
|
6
|
-
// nativue dev
|
|
6
|
+
// nativue dev serves the app and updates it on save, keeping its state where it can
|
|
7
7
|
// nativue run <ios | android> builds, installs and opens the app on a simulator or emulator, then
|
|
8
8
|
// keeps going as `nativue dev` (unless one is already running);
|
|
9
9
|
// --device for a phone, --device <name or id> for a given one;
|
|
10
10
|
// --no-dev only opens the app
|
|
11
|
-
import { build, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
11
|
+
import { build, createServer, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
12
12
|
import vue from '@vitejs/plugin-vue'
|
|
13
13
|
import http from 'node:http'
|
|
14
14
|
import net from 'node:net'
|
|
15
15
|
import { execFileSync } from 'node:child_process'
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
copyFileSync,
|
|
18
|
+
existsSync,
|
|
19
|
+
mkdirSync,
|
|
20
|
+
readdirSync,
|
|
21
|
+
readFileSync,
|
|
22
|
+
renameSync,
|
|
23
|
+
watch,
|
|
24
|
+
} from 'node:fs'
|
|
25
|
+
import { randomUUID } from 'node:crypto'
|
|
17
26
|
import { createRequire } from 'node:module'
|
|
18
27
|
import { dirname, relative } from 'node:path'
|
|
19
28
|
import { fileURLToPath } from 'node:url'
|
|
20
29
|
import { linkIosPlugins } from './link.mjs'
|
|
21
30
|
import { runOnAndroid, runOnIOS } from './run.mjs'
|
|
22
|
-
import { createSymbolicator } from './symbolicate.mjs'
|
|
31
|
+
import { createSymbolicator, framedFiles } from './symbolicate.mjs'
|
|
23
32
|
|
|
24
33
|
const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
|
|
25
34
|
const MAX_STACK_LENGTH = 1_000_000 // characters, of a stack the app posts to /symbolicate
|
|
26
35
|
const BUNDLE_DIRECTORY = 'ios/App'
|
|
27
36
|
const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
|
|
28
|
-
const SOURCE_MAP_PATH = `${BUNDLE_PATH}.map`
|
|
29
37
|
const ANDROID_ASSETS_DIRECTORY = 'android/app/src/main/assets'
|
|
30
38
|
const KEEPALIVE_INTERVAL_MS = 15000
|
|
39
|
+
const UNANSWERED_UPDATE_TIMEOUT_MS = 10000
|
|
31
40
|
|
|
32
41
|
const NATIVE_COMPONENT_TAGS = [
|
|
33
42
|
'View',
|
|
@@ -179,7 +188,7 @@ const APP_VITE_PLUGINS = [
|
|
|
179
188
|
...appPlugins.flatMap((plugin) => plugin.vite ?? []),
|
|
180
189
|
]
|
|
181
190
|
|
|
182
|
-
function viteConfig({ mode, plugins = []
|
|
191
|
+
function viteConfig({ mode, plugins = [] }) {
|
|
183
192
|
// Vite reads the mode from NODE_ENV: development builds keep each component's file (for errors).
|
|
184
193
|
process.env.NODE_ENV = mode
|
|
185
194
|
|
|
@@ -190,7 +199,11 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
|
190
199
|
plugins: [
|
|
191
200
|
vue({
|
|
192
201
|
template: {
|
|
193
|
-
compilerOptions: {
|
|
202
|
+
compilerOptions: {
|
|
203
|
+
isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag),
|
|
204
|
+
// Long static runs would become an HTML string for innerHTML, which native views can't take.
|
|
205
|
+
hoistStatic: false,
|
|
206
|
+
},
|
|
194
207
|
},
|
|
195
208
|
}),
|
|
196
209
|
ignoreStyleBlocks(),
|
|
@@ -218,16 +231,124 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
|
218
231
|
outDir: BUNDLE_DIRECTORY,
|
|
219
232
|
emptyOutDir: false,
|
|
220
233
|
minify: mode === 'production',
|
|
221
|
-
sourcemap,
|
|
222
|
-
watch,
|
|
223
234
|
},
|
|
224
235
|
}
|
|
225
236
|
}
|
|
226
237
|
|
|
227
|
-
|
|
238
|
+
// Full bundle mode skips the plugins' handleHotUpdate. @vitejs/plugin-vue's tells a template-only change
|
|
239
|
+
// apart, so the component re-renders and keeps its state, and tells the app which file changed: run it
|
|
240
|
+
// for every change, before it's rebuilt.
|
|
241
|
+
function vueHotUpdates(sendToApps) {
|
|
242
|
+
let vuePlugin
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
name: 'nativue-vue-hot-updates',
|
|
246
|
+
|
|
247
|
+
configResolved(config) {
|
|
248
|
+
vuePlugin = config.plugins.find((plugin) => plugin.name === 'vite:vue')
|
|
249
|
+
},
|
|
250
|
+
|
|
251
|
+
async watchChange(file) {
|
|
252
|
+
if (!existsSync(file)) return
|
|
253
|
+
|
|
254
|
+
await vuePlugin.handleHotUpdate({
|
|
255
|
+
file,
|
|
256
|
+
modules: [],
|
|
257
|
+
read: () => readFileSync(file, 'utf8'),
|
|
258
|
+
server: { ws: { send: sendToApps } },
|
|
259
|
+
})
|
|
260
|
+
},
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function hotPrelude(clientId, serverURL) {
|
|
265
|
+
const viteRequire = createRequire(createRequire(import.meta.url).resolve('vite'))
|
|
266
|
+
const runtime = readFileSync(viteRequire.resolve('rolldown/experimental/runtime'), 'utf8')
|
|
267
|
+
const client = readFileSync(frameworkPath('cli/hot-client.js'), 'utf8')
|
|
268
|
+
const options = JSON.stringify({ clientId, serverURL })
|
|
269
|
+
|
|
270
|
+
return `${runtime.replace(/^export \{[^}]*\};?$/m, '')}\nvar __NATIVUE_HOT__ = ${options};\n${client}\n`
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Vite's full bundle mode builds the app and, on save, a patch with the changed modules. Each app
|
|
274
|
+
// runtime is a Vite client: the dev server speaks Vite's protocol for it and relays updates over SSE.
|
|
275
|
+
async function dev() {
|
|
228
276
|
const connectedApps = new Set()
|
|
229
|
-
let symbolicate = (text) => text
|
|
230
277
|
const sendToApps = (message) => connectedApps.forEach((response) => response.write(message))
|
|
278
|
+
const config = viteConfig({
|
|
279
|
+
mode: 'development',
|
|
280
|
+
plugins: [vueHotUpdates((payload) => sendToApps(`data: hot ${JSON.stringify(payload)}\n\n`))],
|
|
281
|
+
})
|
|
282
|
+
const vite = await createServer({
|
|
283
|
+
...config,
|
|
284
|
+
experimental: { bundledDev: true },
|
|
285
|
+
server: { host: '127.0.0.1', port: PORT + 1, watch: {} },
|
|
286
|
+
build: {
|
|
287
|
+
...config.build,
|
|
288
|
+
lib: false,
|
|
289
|
+
rolldownOptions: {
|
|
290
|
+
input: frameworkPath('src/entry.ts'),
|
|
291
|
+
experimental: { devMode: { lazy: false } },
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
})
|
|
295
|
+
await vite.listen()
|
|
296
|
+
|
|
297
|
+
const viteURL = `http://127.0.0.1:${vite.httpServer.address().port}`
|
|
298
|
+
const socketsByClientId = new Map()
|
|
299
|
+
const silenceTimersByClientId = new Map()
|
|
300
|
+
let reloadTimer = null
|
|
301
|
+
|
|
302
|
+
function reloadApps() {
|
|
303
|
+
clearTimeout(reloadTimer)
|
|
304
|
+
reloadTimer = setTimeout(() => {
|
|
305
|
+
socketsByClientId.forEach((socket) => socket.close())
|
|
306
|
+
socketsByClientId.clear()
|
|
307
|
+
console.log(`reload -> ${connectedApps.size} app(s)`)
|
|
308
|
+
sendToApps('data: reload\n\n')
|
|
309
|
+
}, 50)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function sendToVite(clientId, message) {
|
|
313
|
+
const socket = socketsByClientId.get(clientId)
|
|
314
|
+
if (!socket) return
|
|
315
|
+
|
|
316
|
+
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message))
|
|
317
|
+
else socket.addEventListener('open', () => socket.send(JSON.stringify(message)), { once: true })
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function disconnect(clientId) {
|
|
321
|
+
socketsByClientId.get(clientId)?.close()
|
|
322
|
+
socketsByClientId.delete(clientId)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// A runtime replaced since (the app reopened or reconnected) never answers an update: forget its client.
|
|
326
|
+
function expectAnswer(clientId) {
|
|
327
|
+
if (silenceTimersByClientId.has(clientId)) return
|
|
328
|
+
|
|
329
|
+
silenceTimersByClientId.set(
|
|
330
|
+
clientId,
|
|
331
|
+
setTimeout(() => disconnect(clientId), UNANSWERED_UPDATE_TIMEOUT_MS),
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function connectToVite(clientId) {
|
|
336
|
+
const socket = new WebSocket(
|
|
337
|
+
`${viteURL.replace('http', 'ws')}/?token=${vite.config.webSocketToken}`,
|
|
338
|
+
'vite-hmr',
|
|
339
|
+
)
|
|
340
|
+
socketsByClientId.set(clientId, socket)
|
|
341
|
+
socket.addEventListener('message', ({ data }) => {
|
|
342
|
+
const payload = JSON.parse(data)
|
|
343
|
+
if (payload.type === 'bundled-dev-update') {
|
|
344
|
+
expectAnswer(clientId)
|
|
345
|
+
sendToApps(`data: hot ${JSON.stringify({ ...payload, clientId })}\n\n`)
|
|
346
|
+
} else if (payload.type === 'full-reload' && !payload.ifFallback) {
|
|
347
|
+
reloadApps()
|
|
348
|
+
}
|
|
349
|
+
})
|
|
350
|
+
sendToVite(clientId, { type: 'custom', event: 'vite:client-connected', data: { clientId } })
|
|
351
|
+
}
|
|
231
352
|
|
|
232
353
|
function handleEvents(request, response) {
|
|
233
354
|
response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' })
|
|
@@ -236,72 +357,125 @@ function startDevServer() {
|
|
|
236
357
|
request.on('close', () => connectedApps.delete(response))
|
|
237
358
|
}
|
|
238
359
|
|
|
239
|
-
function handleBundle(response) {
|
|
240
|
-
//
|
|
241
|
-
|
|
360
|
+
async function handleBundle(request, response) {
|
|
361
|
+
// Hot updates leave the bundle Vite serves behind: a reload would run the code from before them.
|
|
362
|
+
await vite.environments.client.bundledDev.devEngine.ensureLatestBuildOutput()
|
|
363
|
+
const bundle = await fetch(`${viteURL}/assets/entry.js`)
|
|
364
|
+
if (!bundle.ok) {
|
|
242
365
|
response.writeHead(503, { 'Content-Type': 'text/plain' })
|
|
243
366
|
response.end('The bundle is still building')
|
|
244
367
|
return
|
|
245
368
|
}
|
|
246
369
|
|
|
247
|
-
|
|
248
|
-
|
|
370
|
+
const clientId = randomUUID()
|
|
371
|
+
connectToVite(clientId)
|
|
372
|
+
const body = hotPrelude(clientId, `http://${request.headers.host}`) + (await bundle.text())
|
|
373
|
+
response.writeHead(200, {
|
|
374
|
+
'Content-Type': 'application/javascript',
|
|
375
|
+
'Content-Length': Buffer.byteLength(body),
|
|
376
|
+
})
|
|
377
|
+
response.end(body)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async function handleHotMessage(request, response) {
|
|
381
|
+
const { clientId, message } = JSON.parse(await readBody(request))
|
|
382
|
+
clearTimeout(silenceTimersByClientId.get(clientId))
|
|
383
|
+
silenceTimersByClientId.delete(clientId)
|
|
384
|
+
if (message.event !== 'nativue:received') sendToVite(clientId, message)
|
|
385
|
+
response.writeHead(204).end()
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// A patch: Vite serves it from memory, as an ES module the app evaluates as a script.
|
|
389
|
+
async function handlePatch(request, response) {
|
|
390
|
+
const patch = await fetch(`${viteURL}${request.url}`)
|
|
391
|
+
response.writeHead(patch.status, { 'Content-Type': 'application/javascript' })
|
|
392
|
+
response.end((await patch.text()).replace(/;\s*export \{\}\s*$/, ''))
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function sourceMapOf(file) {
|
|
396
|
+
if (file === 'main.bundle.js') {
|
|
397
|
+
return {
|
|
398
|
+
sourceMap: await (await fetch(`${viteURL}/assets/entry.js.map`)).json(),
|
|
399
|
+
directory: `${BUNDLE_DIRECTORY}/assets`,
|
|
400
|
+
lineOffset: hotPrelude('', '').split('\n').length - 1,
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const sourceMap = await fetch(`${viteURL}/${file}.map`)
|
|
405
|
+
|
|
406
|
+
return sourceMap.ok ? { sourceMap: await sourceMap.json(), directory: BUNDLE_DIRECTORY } : null
|
|
249
407
|
}
|
|
250
408
|
|
|
251
409
|
// The app posts an error's stack; it gets it back pointing at the app's files.
|
|
252
410
|
async function handleSymbolicate(request, response) {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
411
|
+
const text = await readBody(request)
|
|
412
|
+
const files = [...framedFiles(text)]
|
|
413
|
+
const sourceMaps = await Promise.all(files.map(sourceMapOf))
|
|
414
|
+
const symbolicate = createSymbolicator(
|
|
415
|
+
Object.fromEntries(
|
|
416
|
+
files.map((file, index) => [file, sourceMaps[index]]).filter(([, map]) => map),
|
|
417
|
+
),
|
|
418
|
+
)
|
|
259
419
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
420
|
+
response.writeHead(200, { 'Content-Type': 'text/plain' })
|
|
421
|
+
response.end(symbolicate(text))
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const routes = {
|
|
425
|
+
'/events': handleEvents,
|
|
426
|
+
'/bundle.js': handleBundle,
|
|
427
|
+
'/hot': handleHotMessage,
|
|
428
|
+
'/symbolicate': handleSymbolicate,
|
|
265
429
|
}
|
|
266
430
|
|
|
267
431
|
http
|
|
268
432
|
.createServer((request, response) => {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
433
|
+
const handle = routes[request.url] ?? handlePatch
|
|
434
|
+
Promise.resolve(handle(request, response)).catch(() => {
|
|
435
|
+
response.writeHead(400).end() // an aborted or oversized post: never take the server down
|
|
436
|
+
})
|
|
272
437
|
})
|
|
273
438
|
// Limitation: Every interface, so phones reach it, and anyone on the network can download the bundle.
|
|
274
439
|
.listen(PORT, () => console.log(`dev server: http://localhost:${PORT}`))
|
|
275
440
|
|
|
441
|
+
if (process.stdin.isTTY) {
|
|
442
|
+
console.log('press r to reload the app')
|
|
443
|
+
process.stdin.setRawMode(true)
|
|
444
|
+
process.stdin.on('data', (key) => {
|
|
445
|
+
if (key[0] === 3) process.exit(130) // ctrl+c, which raw mode turns into a key
|
|
446
|
+
if (key.toString() === 'r') reloadApps()
|
|
447
|
+
})
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// The bundle only watches the files it has: one added or removed (a new route) needs a new build.
|
|
451
|
+
// Editors that save by renaming a temporary file keep the file there, which isn't a change.
|
|
452
|
+
const sourceFiles = new Set(readdirSync('src', { recursive: true }))
|
|
453
|
+
let restartTimer = null
|
|
454
|
+
watch('src', { recursive: true }, (_event, file) => {
|
|
455
|
+
if (!file || existsSync(`src/${file}`) === sourceFiles.has(file)) return
|
|
456
|
+
|
|
457
|
+
if (sourceFiles.has(file)) sourceFiles.delete(file)
|
|
458
|
+
else sourceFiles.add(file)
|
|
459
|
+
|
|
460
|
+
clearTimeout(restartTimer)
|
|
461
|
+
restartTimer = setTimeout(async () => {
|
|
462
|
+
await vite.restart()
|
|
463
|
+
reloadApps()
|
|
464
|
+
}, 100)
|
|
465
|
+
})
|
|
466
|
+
|
|
276
467
|
// Without a keepalive, URLSession drops the idle connection.
|
|
277
468
|
setInterval(() => sendToApps(':\n\n'), KEEPALIVE_INTERVAL_MS)
|
|
469
|
+
}
|
|
278
470
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
JSON.parse(readFileSync(SOURCE_MAP_PATH, 'utf8')),
|
|
285
|
-
BUNDLE_DIRECTORY,
|
|
286
|
-
)
|
|
287
|
-
rmSync(SOURCE_MAP_PATH)
|
|
288
|
-
|
|
289
|
-
console.log(`reload -> ${connectedApps.size} app(s)`)
|
|
290
|
-
sendToApps('data: reload\n\n')
|
|
291
|
-
},
|
|
471
|
+
async function readBody(request) {
|
|
472
|
+
let text = ''
|
|
473
|
+
for await (const chunk of request) {
|
|
474
|
+
text += chunk
|
|
475
|
+
if (text.length > MAX_STACK_LENGTH) throw new Error('body too long')
|
|
292
476
|
}
|
|
293
|
-
}
|
|
294
477
|
|
|
295
|
-
|
|
296
|
-
const reloadPlugin = startDevServer()
|
|
297
|
-
await build(
|
|
298
|
-
viteConfig({
|
|
299
|
-
mode: 'development',
|
|
300
|
-
plugins: [reloadPlugin],
|
|
301
|
-
watch: {},
|
|
302
|
-
sourcemap: 'hidden', // no comment in the bundle: the dev server serves the map
|
|
303
|
-
}),
|
|
304
|
-
)
|
|
478
|
+
return text
|
|
305
479
|
}
|
|
306
480
|
|
|
307
481
|
function isPortFree(port) {
|
package/cli/symbolicate.mjs
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
|
-
// Maps stack frames of the bundle back to the app's files with
|
|
2
|
-
// `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
|
|
1
|
+
// Maps stack frames of the bundle (and of hot updates) back to the app's files with their source maps:
|
|
2
|
+
// Hermes' `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
|
|
3
3
|
// frames from outside src/ (Vue, nativue, Hermes' native ones) collapse into one line, so the app's
|
|
4
4
|
// own frames stand out. Other lines are kept.
|
|
5
5
|
import { SourceMap } from 'node:module'
|
|
6
6
|
import { relative, resolve } from 'node:path'
|
|
7
7
|
|
|
8
|
-
// Groups: before the location, the location's line and column, after it.
|
|
9
|
-
const HERMES_FRAME = /^(\s*at .* \()(
|
|
8
|
+
// Groups: before the location, the file, the location's line and column, after it.
|
|
9
|
+
const HERMES_FRAME = /^(\s*at .* \()(?:.*\/)?([^/()]+\.js):(\d+):(\d+)(\))$/
|
|
10
10
|
const HERMES_NATIVE_FRAME = /^\s*at .* \(native\)$/
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
export function framedFiles(text) {
|
|
13
|
+
return new Set(text.split('\n').flatMap((line) => HERMES_FRAME.exec(line)?.[2] ?? []))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// sourceMapsByFile: for each file (main.bundle.js, a hot update), { sourceMap: the map as JSON,
|
|
17
|
+
// directory: the one its sources are relative to, lineOffset: how many lines above the file's first
|
|
18
|
+
// line the map starts }.
|
|
19
|
+
export function createSymbolicator(sourceMapsByFile) {
|
|
20
|
+
const mapsByFile = new Map(
|
|
21
|
+
Object.entries(sourceMapsByFile).map(([file, { sourceMap, directory, lineOffset = 0 }]) => [
|
|
22
|
+
file,
|
|
23
|
+
{ sourceMap: new SourceMap(sourceMap), directory, lineOffset },
|
|
24
|
+
]),
|
|
25
|
+
)
|
|
15
26
|
|
|
16
|
-
function displayPath(source) {
|
|
17
|
-
const absolutePath = resolve(
|
|
27
|
+
function displayPath(directory, source) {
|
|
28
|
+
const absolutePath = resolve(directory, source)
|
|
18
29
|
const nodeModulesIndex = absolutePath.lastIndexOf('node_modules/')
|
|
19
30
|
|
|
20
31
|
return nodeModulesIndex === -1
|
|
@@ -26,14 +37,15 @@ export function createSymbolicator(sourceMapPayload, bundleDirectory) {
|
|
|
26
37
|
function symbolicateLine(line) {
|
|
27
38
|
if (HERMES_NATIVE_FRAME.test(line)) return { text: line, isInternal: true }
|
|
28
39
|
|
|
29
|
-
const
|
|
30
|
-
|
|
40
|
+
const [, before, file, lineNumber, columnNumber, after] = HERMES_FRAME.exec(line) ?? []
|
|
41
|
+
const map = mapsByFile.get(file)
|
|
42
|
+
if (!map) return { text: line, isInternal: false }
|
|
31
43
|
|
|
32
|
-
const
|
|
33
|
-
const entry = sourceMap.findEntry(Number(lineNumber) - 1, Number(columnNumber) - 1)
|
|
44
|
+
const { sourceMap, directory, lineOffset } = map
|
|
45
|
+
const entry = sourceMap.findEntry(Number(lineNumber) - 1 - lineOffset, Number(columnNumber) - 1)
|
|
34
46
|
if (!entry.originalSource) return { text: line, isInternal: false }
|
|
35
47
|
|
|
36
|
-
const path = displayPath(entry.originalSource)
|
|
48
|
+
const path = displayPath(directory, entry.originalSource)
|
|
37
49
|
const text = `${before}${path}:${entry.originalLine + 1}:${entry.originalColumn + 1}${after}`
|
|
38
50
|
|
|
39
51
|
return { text, isInternal: !path.startsWith('src/') }
|