@nativue/core 0.12.0 → 0.14.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 +33 -8
- package/README.md +2 -1
- package/android/build.gradle.kts +4 -0
- package/android/nativue.settings.gradle.kts +2 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +118 -12
- package/android/src/main/java/dev/nativue/DownloadBanner.kt +45 -0
- package/android/src/main/java/dev/nativue/NativueActivity.kt +26 -5
- package/android/src/main/java/dev/nativue/Permissions.kt +107 -0
- package/android/src/main/java/dev/nativue/Plugins.kt +98 -15
- package/cli/android-project.mjs +377 -0
- package/cli/app-config.mjs +515 -0
- package/cli/config.d.mts +162 -3
- package/cli/hot-client.js +192 -0
- package/cli/ios-project.mjs +652 -0
- package/cli/link.mjs +66 -71
- package/cli/nativue.mjs +262 -58
- package/cli/plugins.mjs +236 -0
- package/cli/prebuild.mjs +458 -0
- package/cli/run.mjs +2 -2
- package/cli/serialize.mjs +168 -0
- package/cli/symbolicate.mjs +26 -14
- package/ios/AppLifecycle.swift +165 -0
- package/ios/Bridge.swift +110 -9
- package/ios/DownloadBanner.swift +38 -0
- package/ios/NativueView.swift +24 -1
- package/ios/Permissions.swift +19 -0
- package/ios/Plugins.swift +24 -0
- package/package.json +3 -2
- package/src/globals.ts +8 -1
- package/src/native-events.ts +99 -0
- package/src/native-functions.ts +16 -2
- package/src/permissions.ts +57 -0
- package/src/renderer.ts +6 -1
- package/src/router.ts +31 -1
- package/src/types.ts +6 -0
- package/template/android/app/src/debug/AndroidManifest.xml +4 -0
- package/template/android/app/src/main/java/MainActivity.kt +5 -0
- package/template/android/app/src/main/res/drawable-night-xxxhdpi/splash_logo.png +0 -0
- package/template/android/app/src/main/res/drawable-xxxhdpi/splash_logo.png +0 -0
- package/template/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +6 -0
- package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
- package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
- package/template/android/app/src/main/res/values/colors.xml +4 -0
- package/template/android/app/src/main/res/values/styles.xml +15 -0
- package/template/android/app/src/main/res/values-night/styles.xml +5 -0
- package/template/android/gradle/wrapper/gradle-wrapper.jar +0 -0
- package/template/android/gradle/wrapper/gradle-wrapper.properties +9 -0
- package/template/android/gradlew +248 -0
- package/template/android/gradlew.bat +112 -0
- package/template/ios/App/App.swift +18 -0
- package/template/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json +1 -0
- package/template/ios/App/Assets.xcassets/AppIcon.appiconset/icon.png +0 -0
- package/template/ios/App/Assets.xcassets/Contents.json +1 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/Contents.json +11 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@1x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@2x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@3x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@1x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@2x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@3x.png +0 -0
- package/template/ios/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +15 -0
package/cli/link.mjs
CHANGED
|
@@ -1,36 +1,31 @@
|
|
|
1
|
-
//
|
|
1
|
+
// The iOS side of the app's packages, those whose package.json has
|
|
2
2
|
// "nativue": { "ios": { "sources": "ios", "plugin": "HapticsPlugin" } }
|
|
3
|
-
// ios/NativuePlugins
|
|
4
|
-
// `nativuePlugins`, the list App.swift passes to NativueView. The app's Xcode project
|
|
5
|
-
// alone; it re-exports Nativue. (Android finds them itself:
|
|
3
|
+
// for prebuild to write: ios/NativuePlugins, a Swift package with a target per package (a link to its
|
|
4
|
+
// sources) and `nativuePlugins`, the list App.swift passes to NativueView. The app's Xcode project
|
|
5
|
+
// depends on it alone; it re-exports Nativue. (Android finds them itself:
|
|
6
|
+
// android/nativue.settings.gradle.kts.)
|
|
6
7
|
// The app's own native code links the same way: native/<name>/ios, whose plugin is <Name>Plugin.
|
|
7
8
|
// Swift packages the native code uses are listed in "ios": { "dependencies": [...] }, in the
|
|
8
9
|
// package.json's "nativue" field or native/<name>/nativue.json:
|
|
9
10
|
// { "url": "https://github.com/stripe/stripe-ios-spm", "from": "24.0.0", "products": ["StripePaymentSheet"] }
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
readFileSync,
|
|
15
|
-
readlinkSync,
|
|
16
|
-
rmSync,
|
|
17
|
-
symlinkSync,
|
|
18
|
-
writeFileSync,
|
|
19
|
-
} from 'node:fs'
|
|
20
|
-
import { dirname, join, relative, resolve } from 'node:path'
|
|
21
|
-
|
|
22
|
-
const PLUGINS_DIRECTORY = 'ios/NativuePlugins'
|
|
23
|
-
const SOURCES_DIRECTORY = `${PLUGINS_DIRECTORY}/Sources`
|
|
11
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
12
|
+
import { dirname, join, relative, sep } from 'node:path'
|
|
13
|
+
|
|
14
|
+
const PLUGINS_DIRECTORY = 'NativuePlugins'
|
|
24
15
|
const LIST_TARGET = 'NativuePlugins'
|
|
25
|
-
|
|
16
|
+
|
|
17
|
+
/** Paths in generated files, links and prebuild's records use '/', on Windows too. */
|
|
18
|
+
export function toPosixPath(path) {
|
|
19
|
+
return path.split(sep).join('/')
|
|
20
|
+
}
|
|
26
21
|
|
|
27
22
|
function readJson(path) {
|
|
28
23
|
return JSON.parse(readFileSync(path, 'utf8'))
|
|
29
24
|
}
|
|
30
25
|
|
|
31
26
|
/** node_modules/<name>, looked up the way Node does: in the app's folder, then in its parents. */
|
|
32
|
-
function packageDirectory(name) {
|
|
33
|
-
for (let directory =
|
|
27
|
+
function packageDirectory(name, appDirectory) {
|
|
28
|
+
for (let directory = appDirectory; ; directory = dirname(directory)) {
|
|
34
29
|
const candidate = join(directory, 'node_modules', name)
|
|
35
30
|
if (existsSync(join(candidate, 'package.json'))) return candidate
|
|
36
31
|
if (directory === dirname(directory)) return null
|
|
@@ -46,13 +41,24 @@ function moduleName(packageName) {
|
|
|
46
41
|
.join('')
|
|
47
42
|
}
|
|
48
43
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
44
|
+
/** The app's packages with a "nativue" field in their package.json, in the order it lists them. */
|
|
45
|
+
export function nativuePackages(appDirectory) {
|
|
46
|
+
if (!existsSync(join(appDirectory, 'package.json'))) return []
|
|
47
|
+
|
|
48
|
+
const { dependencies = {}, devDependencies = {} } = readJson(join(appDirectory, 'package.json'))
|
|
49
|
+
const names = new Set([...Object.keys(dependencies), ...Object.keys(devDependencies)])
|
|
50
|
+
|
|
51
|
+
return [...names].flatMap((name) => {
|
|
52
|
+
const directory = packageDirectory(name, appDirectory)
|
|
53
|
+
const nativue = directory && readJson(join(directory, 'package.json')).nativue
|
|
54
|
+
|
|
55
|
+
return nativue ? [{ name, directory, nativue }] : []
|
|
56
|
+
})
|
|
57
|
+
}
|
|
52
58
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const ios =
|
|
59
|
+
function iosPlugins(appDirectory) {
|
|
60
|
+
return nativuePackages(appDirectory).flatMap(({ name, directory, nativue }) => {
|
|
61
|
+
const ios = nativue.ios
|
|
56
62
|
if (!ios) return []
|
|
57
63
|
|
|
58
64
|
return [
|
|
@@ -67,14 +73,18 @@ function iosPlugins() {
|
|
|
67
73
|
}
|
|
68
74
|
|
|
69
75
|
/** native/<name>/ios: module App<Name> (not <Name>, which could hide a system module like Photos). */
|
|
70
|
-
function appPlugins() {
|
|
71
|
-
|
|
76
|
+
function appPlugins(appDirectory) {
|
|
77
|
+
const nativeDirectory = join(appDirectory, 'native')
|
|
78
|
+
if (!existsSync(nativeDirectory)) return []
|
|
79
|
+
|
|
80
|
+
// native/extensions holds extension targets, not modules.
|
|
81
|
+
return readdirSync(nativeDirectory).flatMap((name) => {
|
|
82
|
+
if (name === 'extensions') return []
|
|
72
83
|
|
|
73
|
-
|
|
74
|
-
const sources = resolve(APP_NATIVE_DIRECTORY, name, 'ios')
|
|
84
|
+
const sources = join(nativeDirectory, name, 'ios')
|
|
75
85
|
if (!existsSync(sources)) return []
|
|
76
86
|
|
|
77
|
-
const settingsPath = join(
|
|
87
|
+
const settingsPath = join(nativeDirectory, name, 'nativue.json')
|
|
78
88
|
const settings = existsSync(settingsPath) ? readJson(settingsPath) : {}
|
|
79
89
|
|
|
80
90
|
return [
|
|
@@ -88,33 +98,6 @@ function appPlugins() {
|
|
|
88
98
|
})
|
|
89
99
|
}
|
|
90
100
|
|
|
91
|
-
function writeIfChanged(path, content) {
|
|
92
|
-
if (existsSync(path) && readFileSync(path, 'utf8') === content) return
|
|
93
|
-
|
|
94
|
-
mkdirSync(dirname(path), { recursive: true })
|
|
95
|
-
writeFileSync(path, content)
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/** Sources/<module> -> the package's sources; links of packages the app no longer has are removed. */
|
|
99
|
-
function linkSources(plugins) {
|
|
100
|
-
const linkTargets = new Map(
|
|
101
|
-
plugins.map((plugin) => [plugin.module, relative(SOURCES_DIRECTORY, plugin.sources)]),
|
|
102
|
-
)
|
|
103
|
-
mkdirSync(SOURCES_DIRECTORY, { recursive: true })
|
|
104
|
-
|
|
105
|
-
for (const entry of readdirSync(SOURCES_DIRECTORY)) {
|
|
106
|
-
if (entry !== LIST_TARGET && !linkTargets.has(entry)) rmSync(join(SOURCES_DIRECTORY, entry))
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
for (const [module, target] of linkTargets) {
|
|
110
|
-
const link = join(SOURCES_DIRECTORY, module)
|
|
111
|
-
if (existsSync(link) && readlinkSync(link) === target) continue
|
|
112
|
-
|
|
113
|
-
rmSync(link, { force: true })
|
|
114
|
-
symlinkSync(target, link)
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
101
|
/** SwiftPM's identity of a package: the last part of its URL, without .git, lowercased. */
|
|
119
102
|
function packageIdentity(url) {
|
|
120
103
|
return url
|
|
@@ -149,7 +132,7 @@ function packageManifest(plugins, corePath) {
|
|
|
149
132
|
const listDependencies = [nativue, ...plugins.map(({ module }) => `"${module}"`)].join(', ')
|
|
150
133
|
|
|
151
134
|
return `// swift-tools-version: 5.9
|
|
152
|
-
// Generated by nativue from the app's packages
|
|
135
|
+
// Generated by nativue prebuild from the app's packages: rewritten on every build.
|
|
153
136
|
import PackageDescription
|
|
154
137
|
|
|
155
138
|
let package = Package(
|
|
@@ -170,21 +153,33 @@ function pluginList(plugins) {
|
|
|
170
153
|
const imports = plugins.map(({ module }) => `import ${module}\n`).join('')
|
|
171
154
|
const instances = plugins.map(({ plugin }) => `${plugin}()`).join(', ')
|
|
172
155
|
|
|
173
|
-
return `// Generated by nativue from the app's packages
|
|
156
|
+
return `// Generated by nativue prebuild from the app's packages: rewritten on every build.
|
|
174
157
|
@_exported import Nativue
|
|
175
158
|
${imports}
|
|
176
159
|
public let nativuePlugins: [NativuePlugin] = [${instances}]
|
|
177
160
|
`
|
|
178
161
|
}
|
|
179
162
|
|
|
180
|
-
/**
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
163
|
+
/**
|
|
164
|
+
* ios/NativuePlugins, as prebuild entries by path relative to ios/: its Package.swift, the plugin
|
|
165
|
+
* list and, per package, a link to its sources. coreDirectory: @nativue/core's folder, which holds
|
|
166
|
+
* its Package.swift.
|
|
167
|
+
*/
|
|
168
|
+
export function iosPluginFiles(appDirectory, coreDirectory) {
|
|
169
|
+
const plugins = [...iosPlugins(appDirectory), ...appPlugins(appDirectory)]
|
|
170
|
+
const pluginsDirectory = join(appDirectory, 'ios', PLUGINS_DIRECTORY)
|
|
171
|
+
const sourcesDirectory = join(pluginsDirectory, 'Sources')
|
|
172
|
+
const links = plugins.map(({ module, sources }) => [
|
|
173
|
+
`${PLUGINS_DIRECTORY}/Sources/${module}`,
|
|
174
|
+
{ symlink: toPosixPath(relative(sourcesDirectory, sources)) },
|
|
175
|
+
])
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
[`${PLUGINS_DIRECTORY}/Package.swift`]: packageManifest(
|
|
179
|
+
plugins,
|
|
180
|
+
toPosixPath(relative(pluginsDirectory, coreDirectory)),
|
|
181
|
+
),
|
|
182
|
+
[`${PLUGINS_DIRECTORY}/Sources/${LIST_TARGET}/Plugins.swift`]: pluginList(plugins),
|
|
183
|
+
...Object.fromEntries(links),
|
|
184
|
+
}
|
|
190
185
|
}
|
package/cli/nativue.mjs
CHANGED
|
@@ -1,33 +1,46 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// The nativue CLI, run from the app's folder:
|
|
3
|
+
// nativue prebuild [ios | android] [--force]
|
|
4
|
+
// generates ios/ and android/ from nativue.config.ts (dev, build and
|
|
5
|
+
// run do it first); --force discards changes made to them by hand
|
|
3
6
|
// nativue build bundles src/app/ into ios/App/main.bundle.js (and, with an android/
|
|
4
7
|
// folder, android/app/src/main/assets/main.bundle.js); Hermes bytecode
|
|
5
8
|
// with --production
|
|
6
|
-
// nativue dev
|
|
9
|
+
// nativue dev serves the app and updates it on save, keeping its state where it can
|
|
7
10
|
// nativue run <ios | android> builds, installs and opens the app on a simulator or emulator, then
|
|
8
11
|
// keeps going as `nativue dev` (unless one is already running);
|
|
9
12
|
// --device for a phone, --device <name or id> for a given one;
|
|
10
13
|
// --no-dev only opens the app
|
|
11
|
-
import { build, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
14
|
+
import { build, createServer, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
12
15
|
import vue from '@vitejs/plugin-vue'
|
|
13
16
|
import http from 'node:http'
|
|
14
17
|
import net from 'node:net'
|
|
15
18
|
import { execFileSync } from 'node:child_process'
|
|
16
|
-
import {
|
|
19
|
+
import {
|
|
20
|
+
copyFileSync,
|
|
21
|
+
existsSync,
|
|
22
|
+
mkdirSync,
|
|
23
|
+
readdirSync,
|
|
24
|
+
readFileSync,
|
|
25
|
+
renameSync,
|
|
26
|
+
watch,
|
|
27
|
+
} from 'node:fs'
|
|
28
|
+
import { randomUUID } from 'node:crypto'
|
|
17
29
|
import { createRequire } from 'node:module'
|
|
18
30
|
import { dirname, relative } from 'node:path'
|
|
19
31
|
import { fileURLToPath } from 'node:url'
|
|
20
|
-
import {
|
|
32
|
+
import { resolvePlugins } from './plugins.mjs'
|
|
33
|
+
import { linkNativePackages, PLATFORMS, prebuild } from './prebuild.mjs'
|
|
21
34
|
import { runOnAndroid, runOnIOS } from './run.mjs'
|
|
22
|
-
import { createSymbolicator } from './symbolicate.mjs'
|
|
35
|
+
import { createSymbolicator, framedFiles } from './symbolicate.mjs'
|
|
23
36
|
|
|
24
37
|
const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
|
|
25
38
|
const MAX_STACK_LENGTH = 1_000_000 // characters, of a stack the app posts to /symbolicate
|
|
26
39
|
const BUNDLE_DIRECTORY = 'ios/App'
|
|
27
40
|
const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
|
|
28
|
-
const SOURCE_MAP_PATH = `${BUNDLE_PATH}.map`
|
|
29
41
|
const ANDROID_ASSETS_DIRECTORY = 'android/app/src/main/assets'
|
|
30
42
|
const KEEPALIVE_INTERVAL_MS = 15000
|
|
43
|
+
const UNANSWERED_UPDATE_TIMEOUT_MS = 10000
|
|
31
44
|
|
|
32
45
|
const NATIVE_COMPONENT_TAGS = [
|
|
33
46
|
'View',
|
|
@@ -173,13 +186,17 @@ function pluginRuntimes(plugins) {
|
|
|
173
186
|
}
|
|
174
187
|
}
|
|
175
188
|
|
|
176
|
-
const
|
|
189
|
+
const appConfig = await loadAppConfig()
|
|
190
|
+
const appPlugins = await resolvePlugins(process.cwd(), appConfig.plugins).catch((error) => {
|
|
191
|
+
console.error(`\n${error.message}`)
|
|
192
|
+
process.exit(1)
|
|
193
|
+
})
|
|
177
194
|
const APP_VITE_PLUGINS = [
|
|
178
195
|
pluginRuntimes(appPlugins),
|
|
179
196
|
...appPlugins.flatMap((plugin) => plugin.vite ?? []),
|
|
180
197
|
]
|
|
181
198
|
|
|
182
|
-
function viteConfig({ mode, plugins = []
|
|
199
|
+
function viteConfig({ mode, plugins = [] }) {
|
|
183
200
|
// Vite reads the mode from NODE_ENV: development builds keep each component's file (for errors).
|
|
184
201
|
process.env.NODE_ENV = mode
|
|
185
202
|
|
|
@@ -222,16 +239,124 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
|
222
239
|
outDir: BUNDLE_DIRECTORY,
|
|
223
240
|
emptyOutDir: false,
|
|
224
241
|
minify: mode === 'production',
|
|
225
|
-
sourcemap,
|
|
226
|
-
watch,
|
|
227
242
|
},
|
|
228
243
|
}
|
|
229
244
|
}
|
|
230
245
|
|
|
231
|
-
|
|
246
|
+
// Full bundle mode skips the plugins' handleHotUpdate. @vitejs/plugin-vue's tells a template-only change
|
|
247
|
+
// apart, so the component re-renders and keeps its state, and tells the app which file changed: run it
|
|
248
|
+
// for every change, before it's rebuilt.
|
|
249
|
+
function vueHotUpdates(sendToApps) {
|
|
250
|
+
let vuePlugin
|
|
251
|
+
|
|
252
|
+
return {
|
|
253
|
+
name: 'nativue-vue-hot-updates',
|
|
254
|
+
|
|
255
|
+
configResolved(config) {
|
|
256
|
+
vuePlugin = config.plugins.find((plugin) => plugin.name === 'vite:vue')
|
|
257
|
+
},
|
|
258
|
+
|
|
259
|
+
async watchChange(file) {
|
|
260
|
+
if (!existsSync(file)) return
|
|
261
|
+
|
|
262
|
+
await vuePlugin.handleHotUpdate({
|
|
263
|
+
file,
|
|
264
|
+
modules: [],
|
|
265
|
+
read: () => readFileSync(file, 'utf8'),
|
|
266
|
+
server: { ws: { send: sendToApps } },
|
|
267
|
+
})
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function hotPrelude(clientId, serverURL) {
|
|
273
|
+
const viteRequire = createRequire(createRequire(import.meta.url).resolve('vite'))
|
|
274
|
+
const runtime = readFileSync(viteRequire.resolve('rolldown/experimental/runtime'), 'utf8')
|
|
275
|
+
const client = readFileSync(frameworkPath('cli/hot-client.js'), 'utf8')
|
|
276
|
+
const options = JSON.stringify({ clientId, serverURL })
|
|
277
|
+
|
|
278
|
+
return `${runtime.replace(/^export \{[^}]*\};?$/m, '')}\nvar __NATIVUE_HOT__ = ${options};\n${client}\n`
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Vite's full bundle mode builds the app and, on save, a patch with the changed modules. Each app
|
|
282
|
+
// runtime is a Vite client: the dev server speaks Vite's protocol for it and relays updates over SSE.
|
|
283
|
+
async function dev() {
|
|
232
284
|
const connectedApps = new Set()
|
|
233
|
-
let symbolicate = (text) => text
|
|
234
285
|
const sendToApps = (message) => connectedApps.forEach((response) => response.write(message))
|
|
286
|
+
const config = viteConfig({
|
|
287
|
+
mode: 'development',
|
|
288
|
+
plugins: [vueHotUpdates((payload) => sendToApps(`data: hot ${JSON.stringify(payload)}\n\n`))],
|
|
289
|
+
})
|
|
290
|
+
const vite = await createServer({
|
|
291
|
+
...config,
|
|
292
|
+
experimental: { bundledDev: true },
|
|
293
|
+
server: { host: '127.0.0.1', port: PORT + 1, watch: {} },
|
|
294
|
+
build: {
|
|
295
|
+
...config.build,
|
|
296
|
+
lib: false,
|
|
297
|
+
rolldownOptions: {
|
|
298
|
+
input: frameworkPath('src/entry.ts'),
|
|
299
|
+
experimental: { devMode: { lazy: false } },
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
})
|
|
303
|
+
await vite.listen()
|
|
304
|
+
|
|
305
|
+
const viteURL = `http://127.0.0.1:${vite.httpServer.address().port}`
|
|
306
|
+
const socketsByClientId = new Map()
|
|
307
|
+
const silenceTimersByClientId = new Map()
|
|
308
|
+
let reloadTimer = null
|
|
309
|
+
|
|
310
|
+
function reloadApps() {
|
|
311
|
+
clearTimeout(reloadTimer)
|
|
312
|
+
reloadTimer = setTimeout(() => {
|
|
313
|
+
socketsByClientId.forEach((socket) => socket.close())
|
|
314
|
+
socketsByClientId.clear()
|
|
315
|
+
console.log(`reload -> ${connectedApps.size} app(s)`)
|
|
316
|
+
sendToApps('data: reload\n\n')
|
|
317
|
+
}, 50)
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function sendToVite(clientId, message) {
|
|
321
|
+
const socket = socketsByClientId.get(clientId)
|
|
322
|
+
if (!socket) return
|
|
323
|
+
|
|
324
|
+
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message))
|
|
325
|
+
else socket.addEventListener('open', () => socket.send(JSON.stringify(message)), { once: true })
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function disconnect(clientId) {
|
|
329
|
+
socketsByClientId.get(clientId)?.close()
|
|
330
|
+
socketsByClientId.delete(clientId)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// A runtime replaced since (the app reopened or reconnected) never answers an update: forget its client.
|
|
334
|
+
function expectAnswer(clientId) {
|
|
335
|
+
if (silenceTimersByClientId.has(clientId)) return
|
|
336
|
+
|
|
337
|
+
silenceTimersByClientId.set(
|
|
338
|
+
clientId,
|
|
339
|
+
setTimeout(() => disconnect(clientId), UNANSWERED_UPDATE_TIMEOUT_MS),
|
|
340
|
+
)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function connectToVite(clientId) {
|
|
344
|
+
const socket = new WebSocket(
|
|
345
|
+
`${viteURL.replace('http', 'ws')}/?token=${vite.config.webSocketToken}`,
|
|
346
|
+
'vite-hmr',
|
|
347
|
+
)
|
|
348
|
+
socketsByClientId.set(clientId, socket)
|
|
349
|
+
socket.addEventListener('message', ({ data }) => {
|
|
350
|
+
const payload = JSON.parse(data)
|
|
351
|
+
if (payload.type === 'bundled-dev-update') {
|
|
352
|
+
expectAnswer(clientId)
|
|
353
|
+
sendToApps(`data: hot ${JSON.stringify({ ...payload, clientId })}\n\n`)
|
|
354
|
+
} else if (payload.type === 'full-reload' && !payload.ifFallback) {
|
|
355
|
+
reloadApps()
|
|
356
|
+
}
|
|
357
|
+
})
|
|
358
|
+
sendToVite(clientId, { type: 'custom', event: 'vite:client-connected', data: { clientId } })
|
|
359
|
+
}
|
|
235
360
|
|
|
236
361
|
function handleEvents(request, response) {
|
|
237
362
|
response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' })
|
|
@@ -240,72 +365,125 @@ function startDevServer() {
|
|
|
240
365
|
request.on('close', () => connectedApps.delete(response))
|
|
241
366
|
}
|
|
242
367
|
|
|
243
|
-
function handleBundle(response) {
|
|
244
|
-
//
|
|
245
|
-
|
|
368
|
+
async function handleBundle(request, response) {
|
|
369
|
+
// Hot updates leave the bundle Vite serves behind: a reload would run the code from before them.
|
|
370
|
+
await vite.environments.client.bundledDev.devEngine.ensureLatestBuildOutput()
|
|
371
|
+
const bundle = await fetch(`${viteURL}/assets/entry.js`)
|
|
372
|
+
if (!bundle.ok) {
|
|
246
373
|
response.writeHead(503, { 'Content-Type': 'text/plain' })
|
|
247
374
|
response.end('The bundle is still building')
|
|
248
375
|
return
|
|
249
376
|
}
|
|
250
377
|
|
|
251
|
-
|
|
252
|
-
|
|
378
|
+
const clientId = randomUUID()
|
|
379
|
+
connectToVite(clientId)
|
|
380
|
+
const body = hotPrelude(clientId, `http://${request.headers.host}`) + (await bundle.text())
|
|
381
|
+
response.writeHead(200, {
|
|
382
|
+
'Content-Type': 'application/javascript',
|
|
383
|
+
'Content-Length': Buffer.byteLength(body),
|
|
384
|
+
})
|
|
385
|
+
response.end(body)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function handleHotMessage(request, response) {
|
|
389
|
+
const { clientId, message } = JSON.parse(await readBody(request))
|
|
390
|
+
clearTimeout(silenceTimersByClientId.get(clientId))
|
|
391
|
+
silenceTimersByClientId.delete(clientId)
|
|
392
|
+
if (message.event !== 'nativue:received') sendToVite(clientId, message)
|
|
393
|
+
response.writeHead(204).end()
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// A patch: Vite serves it from memory, as an ES module the app evaluates as a script.
|
|
397
|
+
async function handlePatch(request, response) {
|
|
398
|
+
const patch = await fetch(`${viteURL}${request.url}`)
|
|
399
|
+
response.writeHead(patch.status, { 'Content-Type': 'application/javascript' })
|
|
400
|
+
response.end((await patch.text()).replace(/;\s*export \{\}\s*$/, ''))
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async function sourceMapOf(file) {
|
|
404
|
+
if (file === 'main.bundle.js') {
|
|
405
|
+
return {
|
|
406
|
+
sourceMap: await (await fetch(`${viteURL}/assets/entry.js.map`)).json(),
|
|
407
|
+
directory: `${BUNDLE_DIRECTORY}/assets`,
|
|
408
|
+
lineOffset: hotPrelude('', '').split('\n').length - 1,
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const sourceMap = await fetch(`${viteURL}/${file}.map`)
|
|
413
|
+
|
|
414
|
+
return sourceMap.ok ? { sourceMap: await sourceMap.json(), directory: BUNDLE_DIRECTORY } : null
|
|
253
415
|
}
|
|
254
416
|
|
|
255
417
|
// The app posts an error's stack; it gets it back pointing at the app's files.
|
|
256
418
|
async function handleSymbolicate(request, response) {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
419
|
+
const text = await readBody(request)
|
|
420
|
+
const files = [...framedFiles(text)]
|
|
421
|
+
const sourceMaps = await Promise.all(files.map(sourceMapOf))
|
|
422
|
+
const symbolicate = createSymbolicator(
|
|
423
|
+
Object.fromEntries(
|
|
424
|
+
files.map((file, index) => [file, sourceMaps[index]]).filter(([, map]) => map),
|
|
425
|
+
),
|
|
426
|
+
)
|
|
263
427
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
428
|
+
response.writeHead(200, { 'Content-Type': 'text/plain' })
|
|
429
|
+
response.end(symbolicate(text))
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const routes = {
|
|
433
|
+
'/events': handleEvents,
|
|
434
|
+
'/bundle.js': handleBundle,
|
|
435
|
+
'/hot': handleHotMessage,
|
|
436
|
+
'/symbolicate': handleSymbolicate,
|
|
269
437
|
}
|
|
270
438
|
|
|
271
439
|
http
|
|
272
440
|
.createServer((request, response) => {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
441
|
+
const handle = routes[request.url] ?? handlePatch
|
|
442
|
+
Promise.resolve(handle(request, response)).catch(() => {
|
|
443
|
+
response.writeHead(400).end() // an aborted or oversized post: never take the server down
|
|
444
|
+
})
|
|
276
445
|
})
|
|
277
446
|
// Limitation: Every interface, so phones reach it, and anyone on the network can download the bundle.
|
|
278
447
|
.listen(PORT, () => console.log(`dev server: http://localhost:${PORT}`))
|
|
279
448
|
|
|
449
|
+
if (process.stdin.isTTY) {
|
|
450
|
+
console.log('press r to reload the app')
|
|
451
|
+
process.stdin.setRawMode(true)
|
|
452
|
+
process.stdin.on('data', (key) => {
|
|
453
|
+
if (key[0] === 3) process.exit(130) // ctrl+c, which raw mode turns into a key
|
|
454
|
+
if (key.toString() === 'r') reloadApps()
|
|
455
|
+
})
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// The bundle only watches the files it has: one added or removed (a new route) needs a new build.
|
|
459
|
+
// Editors that save by renaming a temporary file keep the file there, which isn't a change.
|
|
460
|
+
const sourceFiles = new Set(readdirSync('src', { recursive: true }))
|
|
461
|
+
let restartTimer = null
|
|
462
|
+
watch('src', { recursive: true }, (_event, file) => {
|
|
463
|
+
if (!file || existsSync(`src/${file}`) === sourceFiles.has(file)) return
|
|
464
|
+
|
|
465
|
+
if (sourceFiles.has(file)) sourceFiles.delete(file)
|
|
466
|
+
else sourceFiles.add(file)
|
|
467
|
+
|
|
468
|
+
clearTimeout(restartTimer)
|
|
469
|
+
restartTimer = setTimeout(async () => {
|
|
470
|
+
await vite.restart()
|
|
471
|
+
reloadApps()
|
|
472
|
+
}, 100)
|
|
473
|
+
})
|
|
474
|
+
|
|
280
475
|
// Without a keepalive, URLSession drops the idle connection.
|
|
281
476
|
setInterval(() => sendToApps(':\n\n'), KEEPALIVE_INTERVAL_MS)
|
|
477
|
+
}
|
|
282
478
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
JSON.parse(readFileSync(SOURCE_MAP_PATH, 'utf8')),
|
|
289
|
-
BUNDLE_DIRECTORY,
|
|
290
|
-
)
|
|
291
|
-
rmSync(SOURCE_MAP_PATH)
|
|
292
|
-
|
|
293
|
-
console.log(`reload -> ${connectedApps.size} app(s)`)
|
|
294
|
-
sendToApps('data: reload\n\n')
|
|
295
|
-
},
|
|
479
|
+
async function readBody(request) {
|
|
480
|
+
let text = ''
|
|
481
|
+
for await (const chunk of request) {
|
|
482
|
+
text += chunk
|
|
483
|
+
if (text.length > MAX_STACK_LENGTH) throw new Error('body too long')
|
|
296
484
|
}
|
|
297
|
-
}
|
|
298
485
|
|
|
299
|
-
|
|
300
|
-
const reloadPlugin = startDevServer()
|
|
301
|
-
await build(
|
|
302
|
-
viteConfig({
|
|
303
|
-
mode: 'development',
|
|
304
|
-
plugins: [reloadPlugin],
|
|
305
|
-
watch: {},
|
|
306
|
-
sourcemap: 'hidden', // no comment in the bundle: the dev server serves the map
|
|
307
|
-
}),
|
|
308
|
-
)
|
|
486
|
+
return text
|
|
309
487
|
}
|
|
310
488
|
|
|
311
489
|
function isPortFree(port) {
|
|
@@ -338,12 +516,38 @@ async function runApp(platform, args) {
|
|
|
338
516
|
console.log('\nA dev server is already running: the app reloads from it.')
|
|
339
517
|
}
|
|
340
518
|
|
|
519
|
+
// The platforms dev and build generate: iOS needs a Mac, where its projects build.
|
|
520
|
+
const LOCAL_PLATFORMS = process.platform === 'darwin' ? PLATFORMS : ['android']
|
|
521
|
+
|
|
522
|
+
/** ios/ and android/ from nativue.config.ts, or, with `prebuild: false`, only the packages' links. */
|
|
523
|
+
function generateNativeProjects(platforms, { force = false } = {}) {
|
|
524
|
+
const directories = { appDirectory: process.cwd(), coreDirectory: frameworkPath('') }
|
|
525
|
+
const changedPaths =
|
|
526
|
+
appConfig.prebuild === false
|
|
527
|
+
? linkNativePackages({ ...directories, config: appConfig, plugins: appPlugins, platforms })
|
|
528
|
+
: prebuild({ ...directories, config: appConfig, plugins: appPlugins, platforms, force })
|
|
529
|
+
|
|
530
|
+
if (changedPaths.length > 0) console.log(`prebuild: ${changedPaths.length} file(s) updated`)
|
|
531
|
+
}
|
|
532
|
+
|
|
341
533
|
const [command, ...args] = process.argv.slice(2)
|
|
342
534
|
|
|
343
535
|
try {
|
|
344
|
-
if (
|
|
536
|
+
if (command === 'dev' || command === 'build') generateNativeProjects(LOCAL_PLATFORMS)
|
|
537
|
+
if (command === 'run' && RUNNERS[args[0]]) generateNativeProjects([args[0]])
|
|
345
538
|
|
|
346
|
-
if (command === '
|
|
539
|
+
if (command === 'prebuild') {
|
|
540
|
+
if (appConfig.prebuild === false) {
|
|
541
|
+
throw new Error(
|
|
542
|
+
'nativue.config.ts has prebuild: false, so the app keeps ios/ and android/ by hand.',
|
|
543
|
+
)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const platforms = PLATFORMS.filter((platform) => args.includes(platform))
|
|
547
|
+
generateNativeProjects(platforms.length > 0 ? platforms : PLATFORMS, {
|
|
548
|
+
force: args.includes('--force'),
|
|
549
|
+
})
|
|
550
|
+
} else if (command === 'dev') {
|
|
347
551
|
await dev()
|
|
348
552
|
} else if (command === 'build') {
|
|
349
553
|
await build(
|
|
@@ -355,7 +559,7 @@ try {
|
|
|
355
559
|
await runApp(args[0], args.slice(1))
|
|
356
560
|
} else {
|
|
357
561
|
console.log(
|
|
358
|
-
'usage: nativue <dev | build [--production] | run <ios | android> [--device [name or id]] [--no-dev]>',
|
|
562
|
+
'usage: nativue <prebuild [ios | android] [--force] | dev | build [--production] | run <ios | android> [--device [name or id]] [--no-dev]>',
|
|
359
563
|
)
|
|
360
564
|
process.exitCode = 1
|
|
361
565
|
}
|