@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.
Files changed (61) hide show
  1. package/AGENTS.md +33 -8
  2. package/README.md +2 -1
  3. package/android/build.gradle.kts +4 -0
  4. package/android/nativue.settings.gradle.kts +2 -0
  5. package/android/src/main/java/dev/nativue/Bridge.kt +118 -12
  6. package/android/src/main/java/dev/nativue/DownloadBanner.kt +45 -0
  7. package/android/src/main/java/dev/nativue/NativueActivity.kt +26 -5
  8. package/android/src/main/java/dev/nativue/Permissions.kt +107 -0
  9. package/android/src/main/java/dev/nativue/Plugins.kt +98 -15
  10. package/cli/android-project.mjs +377 -0
  11. package/cli/app-config.mjs +515 -0
  12. package/cli/config.d.mts +162 -3
  13. package/cli/hot-client.js +192 -0
  14. package/cli/ios-project.mjs +652 -0
  15. package/cli/link.mjs +66 -71
  16. package/cli/nativue.mjs +262 -58
  17. package/cli/plugins.mjs +236 -0
  18. package/cli/prebuild.mjs +458 -0
  19. package/cli/run.mjs +2 -2
  20. package/cli/serialize.mjs +168 -0
  21. package/cli/symbolicate.mjs +26 -14
  22. package/ios/AppLifecycle.swift +165 -0
  23. package/ios/Bridge.swift +110 -9
  24. package/ios/DownloadBanner.swift +38 -0
  25. package/ios/NativueView.swift +24 -1
  26. package/ios/Permissions.swift +19 -0
  27. package/ios/Plugins.swift +24 -0
  28. package/package.json +3 -2
  29. package/src/globals.ts +8 -1
  30. package/src/native-events.ts +99 -0
  31. package/src/native-functions.ts +16 -2
  32. package/src/permissions.ts +57 -0
  33. package/src/renderer.ts +6 -1
  34. package/src/router.ts +31 -1
  35. package/src/types.ts +6 -0
  36. package/template/android/app/src/debug/AndroidManifest.xml +4 -0
  37. package/template/android/app/src/main/java/MainActivity.kt +5 -0
  38. package/template/android/app/src/main/res/drawable-night-xxxhdpi/splash_logo.png +0 -0
  39. package/template/android/app/src/main/res/drawable-xxxhdpi/splash_logo.png +0 -0
  40. package/template/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +6 -0
  41. package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  42. package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  43. package/template/android/app/src/main/res/values/colors.xml +4 -0
  44. package/template/android/app/src/main/res/values/styles.xml +15 -0
  45. package/template/android/app/src/main/res/values-night/styles.xml +5 -0
  46. package/template/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  47. package/template/android/gradle/wrapper/gradle-wrapper.properties +9 -0
  48. package/template/android/gradlew +248 -0
  49. package/template/android/gradlew.bat +112 -0
  50. package/template/ios/App/App.swift +18 -0
  51. package/template/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json +1 -0
  52. package/template/ios/App/Assets.xcassets/AppIcon.appiconset/icon.png +0 -0
  53. package/template/ios/App/Assets.xcassets/Contents.json +1 -0
  54. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/Contents.json +11 -0
  55. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@1x.png +0 -0
  56. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@2x.png +0 -0
  57. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@3x.png +0 -0
  58. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@1x.png +0 -0
  59. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@2x.png +0 -0
  60. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@3x.png +0 -0
  61. package/template/ios/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +15 -0
@@ -0,0 +1,236 @@
1
+ // Config plugins' mods: functions a package (its package.json's "nativue": { "plugin": "./plugin.mjs" })
2
+ // or the app (nativue.config.ts's `plugins`) runs on the native files prebuild generates, before the
3
+ // app's own fields, so the app always wins.
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
+ import { basename, join } from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
7
+ import { appResources, emptyGradle, iosFonts, resourceFile } from './app-config.mjs'
8
+ import { nativuePackages, toPosixPath } from './link.mjs'
9
+ import { escapeXml } from './serialize.mjs'
10
+
11
+ // Where an app with `prebuild: false` keeps no file of its own; skipped when walking.
12
+ const SKIPPED_DIRECTORIES = new Set(['build', 'node_modules', 'NativuePlugins', '.gradle', 'Pods'])
13
+
14
+ /**
15
+ * The plugins prebuild applies: each package's own, without options, then nativue.config.ts's. A
16
+ * package's plugin is named after the package, so a config plugin of that name replaces it before
17
+ * it's created: a plugin with required options works.
18
+ */
19
+ export async function resolvePlugins(appDirectory, configPlugins = []) {
20
+ const configured = new Set(configPlugins.map((plugin) => plugin.name))
21
+ const packages = nativuePackages(appDirectory).filter(
22
+ ({ name, nativue }) => nativue.plugin && !configured.has(name),
23
+ )
24
+ const packagePlugins = await Promise.all(packages.map(loadPackagePlugin))
25
+
26
+ return [...packagePlugins, ...configPlugins]
27
+ }
28
+
29
+ async function loadPackagePlugin({ name, directory, nativue }) {
30
+ const path = join(directory, nativue.plugin)
31
+ const { default: createPlugin } = await import(pathToFileURL(path).href)
32
+ const plugin = typeof createPlugin === 'function' ? await createPlugin() : null
33
+
34
+ if (plugin?.name !== name) {
35
+ throw new Error(
36
+ `${name}'s nativue plugin (${path}) must export by default a function returning { name: '${name}', ... }`,
37
+ )
38
+ }
39
+
40
+ return plugin
41
+ }
42
+
43
+ /** Runs every plugin's mod on document, in order; mods change it in place. */
44
+ export function applyMods(plugins, platform, mod, document, context) {
45
+ plugins.forEach((plugin) => {
46
+ try {
47
+ plugin[platform]?.[mod]?.(document, { ...context, platform })
48
+ } catch (error) {
49
+ throw new Error(`${plugin.name}'s ${platform}.${mod} mod failed: ${error.message}`, {
50
+ cause: error,
51
+ })
52
+ }
53
+ })
54
+
55
+ return document
56
+ }
57
+
58
+ function filesIn(directory) {
59
+ if (!existsSync(directory)) return []
60
+
61
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
62
+ const path = join(directory, entry.name)
63
+
64
+ if (entry.isDirectory()) return SKIPPED_DIRECTORIES.has(entry.name) ? [] : filesIn(path)
65
+
66
+ return [toPosixPath(path)]
67
+ })
68
+ }
69
+
70
+ function stringValues(value) {
71
+ if (typeof value === 'string') return [value]
72
+ if (typeof value !== 'object' || value === null) return []
73
+
74
+ return Object.values(value).flatMap(stringValues)
75
+ }
76
+
77
+ /** Each key a mod adds, present with every string of its value. */
78
+ function plistChecks(file, document) {
79
+ return Object.entries(document).map(([key, value]) => {
80
+ const parts = [
81
+ `<key>${escapeXml(key)}</key>`,
82
+ ...stringValues(value).map((text) => `<string>${escapeXml(text)}</string>`),
83
+ ]
84
+
85
+ return {
86
+ file,
87
+ entry: `<key>${key}</key> = ${JSON.stringify(value)}`,
88
+ isPresent: (text) => parts.every((part) => text.includes(part)),
89
+ }
90
+ })
91
+ }
92
+
93
+ function usesPermissions(element) {
94
+ const own = element.tag === 'uses-permission' ? [element.attributes['android:name']] : []
95
+
96
+ return [...own, ...(element.children ?? []).flatMap(usesPermissions)]
97
+ }
98
+
99
+ function isQuoted(content, text) {
100
+ return content.includes(`"${text}"`) || content.includes(`'${text}'`)
101
+ }
102
+
103
+ function escapeRegExp(text) {
104
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
105
+ }
106
+
107
+ /** Kotlin or Groovy, either quotes; a dependency at any version. */
108
+ function gradleChecks(gradle) {
109
+ const inGradle = (entry, isPresent) => ({ file: 'build.gradle.kts', entry, isPresent })
110
+
111
+ return [
112
+ ...gradle.plugins.map(({ id }) => inGradle(`id("${id}")`, (content) => isQuoted(content, id))),
113
+ ...gradle.dependencies.map((dependency) => {
114
+ const groupAndArtifact = dependency.split(':').slice(0, 2).join(':')
115
+
116
+ return inGradle(`implementation("${dependency}")`, (content) =>
117
+ content.includes(groupAndArtifact),
118
+ )
119
+ }),
120
+ ...gradle.repositories.map((url) =>
121
+ inGradle(`maven("${url}")`, (content) => content.includes(url)),
122
+ ),
123
+ ...Object.entries(gradle.manifestPlaceholders).map(([key, value]) =>
124
+ inGradle(`manifestPlaceholders["${key}"] = "${value}"`, (content) =>
125
+ new RegExp(`\\b${escapeRegExp(key)}\\b`).test(content),
126
+ ),
127
+ ),
128
+ ...Object.entries(gradle.properties).map(([key, value]) => ({
129
+ file: 'gradle.properties',
130
+ entry: `${key}=${value}`,
131
+ isPresent: (content) => new RegExp(`^\\s*${escapeRegExp(key)}\\s*[=:]`, 'm').test(content),
132
+ })),
133
+ ]
134
+ }
135
+
136
+ /** A plugin's resource, by the end of its path. */
137
+ function resourceCheck(file, path) {
138
+ return { file, entry: path, isPresent: (filePath) => filePath.endsWith(`/${path}`) }
139
+ }
140
+
141
+ /** What one plugin's mods and resources add on a platform, as { file, entry, isPresent } checks. */
142
+ function pluginRequirements(plugin, platform, { context, manifest }) {
143
+ const run = (mod, document) => applyMods([plugin], platform, mod, document, context)
144
+ const resources = appResources({}, [plugin])
145
+ const fonts = iosFonts(resources)
146
+
147
+ if (platform === 'ios') {
148
+ // An invalid target is only refused when generating: here, it's skipped.
149
+ const targetNames = run('targets', [])
150
+ .map((target) => target?.name)
151
+ .filter((name) => typeof name === 'string')
152
+
153
+ return [
154
+ ...targetNames.map((name) => ({
155
+ file: 'project.pbxproj',
156
+ entry: `an extension target named ${name}`,
157
+ isPresent: (text) =>
158
+ new RegExp(`isa = PBXNativeTarget;[^}]*\\bname = "?${name}"?;`).test(text),
159
+ })),
160
+ ...plistChecks('Info.plist', run('infoPlist', {})),
161
+ ...plistChecks('.entitlements', run('entitlements', {})),
162
+ ...plistChecks('Info.plist', fonts.length > 0 ? { UIAppFonts: fonts } : {}),
163
+ ...resources
164
+ .filter(({ ios }) => ios)
165
+ .map(({ ios }) => resourceCheck('ios resources', ios.destination)),
166
+ ]
167
+ }
168
+
169
+ const gradle = run('gradle', emptyGradle())
170
+
171
+ const basePermissions = usesPermissions(manifest)
172
+ const addedPermissions = usesPermissions(run('manifest', structuredClone(manifest))).filter(
173
+ (permission) => !basePermissions.includes(permission),
174
+ )
175
+
176
+ return [
177
+ ...addedPermissions.map((permission) => ({
178
+ file: 'AndroidManifest.xml',
179
+ entry: `<uses-permission android:name="${permission}" />`,
180
+ isPresent: (text) => text.includes(`"${permission}"`),
181
+ })),
182
+ ...Object.entries(run('strings', {})).map(([name, value]) => ({
183
+ file: 'res/values strings',
184
+ entry: `<string name="${name}">${value}</string>`,
185
+ isPresent: (text) => text.includes(`name="${name}"`),
186
+ })),
187
+ ...gradleChecks(gradle),
188
+ ...resources
189
+ .filter(({ android }) => android)
190
+ .map((resource) => resourceCheck('android resources', resourceFile(resource))),
191
+ ]
192
+ }
193
+
194
+ /** By check: the texts of the app's files it looks in, or their paths for resources. */
195
+ function projectFiles(appDirectory) {
196
+ const iosPaths = filesIn(join(appDirectory, 'ios'))
197
+ const androidPaths = filesIn(join(appDirectory, 'android'))
198
+ const texts = (paths, matches) =>
199
+ paths.filter((path) => matches(basename(path))).map((path) => readFileSync(path, 'utf8'))
200
+
201
+ return {
202
+ 'Info.plist': texts(iosPaths, (name) => name.endsWith('Info.plist')),
203
+ '.entitlements': texts(iosPaths, (name) => name.endsWith('.entitlements')),
204
+ 'ios resources': iosPaths,
205
+ 'project.pbxproj': texts(iosPaths, (name) => name === 'project.pbxproj'),
206
+ 'AndroidManifest.xml': texts(androidPaths, (name) => name === 'AndroidManifest.xml'),
207
+ 'res/values strings': texts(androidPaths, (name) => /^strings.*\.xml$/.test(name)),
208
+ 'build.gradle.kts': texts(androidPaths, (name) => /\.gradle(\.kts)?$/.test(name)),
209
+ 'gradle.properties': texts(androidPaths, (name) => name === 'gradle.properties'),
210
+ 'android resources': androidPaths,
211
+ }
212
+ }
213
+
214
+ /**
215
+ * With `prebuild: false`, the app's own ios/ and android/ must hold what its plugins' mods add:
216
+ * throws with what's missing, to paste in. Only the platforms built that the app has are checked.
217
+ * manifest: the generated manifest mods start from, so only what they add is asked for.
218
+ */
219
+ export function checkManualProjects(plugins, { config, appDirectory, platforms, manifest }) {
220
+ const checkedPlatforms = platforms.filter((platform) => existsSync(join(appDirectory, platform)))
221
+ const files = projectFiles(appDirectory)
222
+ const context = { config, projectRoot: appDirectory }
223
+ const missing = checkedPlatforms.flatMap((platform) =>
224
+ plugins.flatMap((plugin) =>
225
+ pluginRequirements(plugin, platform, { context, manifest })
226
+ .filter(({ file, isPresent }) => !files[file].some(isPresent))
227
+ .map(({ file, entry }) => ` ${file}: ${entry} (from ${plugin.name})`),
228
+ ),
229
+ )
230
+
231
+ if (missing.length === 0) return
232
+
233
+ throw new Error(
234
+ `nativue.config.ts has prebuild: false, so ios/ and android/ are yours, but they lack what these plugins need:\n${missing.join('\n')}`,
235
+ )
236
+ }
@@ -0,0 +1,458 @@
1
+ // `nativue prebuild [ios | android] [--force]`, also run by dev, build and run: generates the app's
2
+ // ios/ and android/ from the template next to this file, nativue.config.ts and the app's packages.
3
+ // Every run starts from the template, so the projects depend only on those inputs; it writes only
4
+ // what changed, keeping Xcode's and Gradle's incremental builds.
5
+ // Each folder's .nativue/generated.json records a hash of every file it wrote. A file that no longer
6
+ // matches was edited by hand, and one it never wrote was added by hand: either stops prebuild before
7
+ // it writes anything, since the next run would lose that work. --force overwrites and deletes them.
8
+ // With `prebuild: false` in the config, the app keeps ios/ and android/ by hand: only the packages'
9
+ // native code is linked (ios/NativuePlugins), as before prebuild existed.
10
+ import { spawnSync } from 'node:child_process'
11
+ import { createHash } from 'node:crypto'
12
+ import {
13
+ existsSync,
14
+ lstatSync,
15
+ mkdirSync,
16
+ mkdtempSync,
17
+ readdirSync,
18
+ readFileSync,
19
+ readlinkSync,
20
+ rmdirSync,
21
+ rmSync,
22
+ symlinkSync,
23
+ writeFileSync,
24
+ } from 'node:fs'
25
+ import { tmpdir } from 'node:os'
26
+ import { dirname, join, relative } from 'node:path'
27
+ import { androidProjectFiles, nativueManifest } from './android-project.mjs'
28
+ import { appConfig, validateConfig } from './app-config.mjs'
29
+ import { iosProjectFiles } from './ios-project.mjs'
30
+ import { iosPluginFiles, toPosixPath } from './link.mjs'
31
+ import { checkManualProjects } from './plugins.mjs'
32
+
33
+ export const PLATFORMS = ['ios', 'android']
34
+
35
+ const RECORD_PATH = '.nativue/generated.json'
36
+ const MIGRATION_GUIDE_URL =
37
+ 'https://github.com/nativue/nativue/blob/main/docs/migrating-to-prebuild.md'
38
+ const TEMPLATE_TEXT_FILE = /\.(kts|kt|xml|swift|json)$/
39
+ // What Xcode, Gradle, Android Studio and the bundler write next to the generated files: never
40
+ // checked, deleted or walked into.
41
+ const IGNORED_DIRECTORIES = new Set([
42
+ 'build',
43
+ '.build',
44
+ '.gradle',
45
+ '.kotlin',
46
+ '.cxx',
47
+ '.idea',
48
+ '.swiftpm',
49
+ '.nativue',
50
+ 'xcuserdata',
51
+ ])
52
+ const IGNORED_FILES = new Set(['.DS_Store', 'local.properties', 'main.bundle.js'])
53
+ const IGNORED_PATHS = new Set(['App.xcodeproj/project.xcworkspace'])
54
+ // Written only when missing: Xcode keeps the resolved Swift package versions up to date afterwards.
55
+ const SEEDED_PATHS = new Set([
56
+ 'App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved',
57
+ ])
58
+
59
+ function isIgnored(path) {
60
+ const name = path.split('/').pop()
61
+
62
+ return (
63
+ IGNORED_DIRECTORIES.has(name) ||
64
+ IGNORED_FILES.has(name) ||
65
+ IGNORED_PATHS.has(path) ||
66
+ name.endsWith('.iml')
67
+ )
68
+ }
69
+
70
+ function hash(data) {
71
+ return createHash('sha256').update(data).digest('hex')
72
+ }
73
+
74
+ function entryHash(entry) {
75
+ return entry.symlink === undefined ? hash(entry.content) : hash(`symlink:${entry.symlink}`)
76
+ }
77
+
78
+ /** Files and links under directory, by path relative to it, skipping what tools own. */
79
+ function filesIn(directory, base = directory) {
80
+ if (!existsSync(directory)) return []
81
+
82
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
83
+ const path = join(directory, entry.name)
84
+ const relativePath = toPosixPath(relative(base, path))
85
+
86
+ if (isIgnored(relativePath)) return []
87
+
88
+ return entry.isDirectory() ? filesIn(path, base) : [relativePath]
89
+ })
90
+ }
91
+
92
+ function readEntry(path) {
93
+ if (lstatSync(path).isSymbolicLink()) return { symlink: readlinkSync(path) }
94
+
95
+ return { content: readFileSync(path) }
96
+ }
97
+
98
+ function readRecord(platformDirectory) {
99
+ const path = join(platformDirectory, RECORD_PATH)
100
+
101
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null
102
+ }
103
+
104
+ function writeRecord(platformDirectory, record) {
105
+ const path = join(platformDirectory, RECORD_PATH)
106
+
107
+ mkdirSync(dirname(path), { recursive: true })
108
+ writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`)
109
+ }
110
+
111
+ function fillPlaceholders(text, values) {
112
+ return Object.entries(values).reduce(
113
+ (filled, [placeholder, value]) => filled.replaceAll(placeholder, value),
114
+ text,
115
+ )
116
+ }
117
+
118
+ /** All of the template, including the seeded files under the paths isIgnored skips in the app. */
119
+ function templatePaths(templateDirectory) {
120
+ return readdirSync(templateDirectory, { recursive: true, withFileTypes: true })
121
+ .filter((entry) => entry.isFile() && entry.name !== '.DS_Store')
122
+ .map((entry) => toPosixPath(relative(templateDirectory, join(entry.parentPath, entry.name))))
123
+ }
124
+
125
+ function templateFiles(templateDirectory, placeholders) {
126
+ return Object.fromEntries(
127
+ templatePaths(templateDirectory).map((path) => {
128
+ const source = join(templateDirectory, path)
129
+ const content = readFileSync(source)
130
+ const executable = (lstatSync(source).mode & 0o111) !== 0
131
+ const filled = TEMPLATE_TEXT_FILE.test(path)
132
+ ? fillPlaceholders(content.toString('utf8'), placeholders)
133
+ : content
134
+
135
+ return [path, { content: filled, executable }]
136
+ }),
137
+ )
138
+ }
139
+
140
+ function asEntries(files) {
141
+ return Object.fromEntries(
142
+ Object.entries(files).map(([path, file]) => [
143
+ path,
144
+ typeof file === 'string' ? { content: file } : file,
145
+ ]),
146
+ )
147
+ }
148
+
149
+ /** Every file of platform's folder, by path relative to it: { content, executable } or { symlink }. */
150
+ function generatedFiles(platform, { app, plugins, appDirectory, coreDirectory }) {
151
+ const platformDirectory = join(appDirectory, platform)
152
+ const placeholders = {
153
+ __ANDROID_PACKAGE__: app.android.package,
154
+ __CORE_PATH__: toPosixPath(relative(platformDirectory, coreDirectory)),
155
+ __SPLASH_BACKGROUND__: app.splash.backgroundColor,
156
+ __DARK_SPLASH_BACKGROUND__: app.splash.darkBackgroundColor,
157
+ __ICON_BACKGROUND__: app.iconBackgroundColor,
158
+ }
159
+ const template = templateFiles(join(coreDirectory, 'template', platform), placeholders)
160
+ const generated =
161
+ platform === 'ios'
162
+ ? {
163
+ ...iosProjectFiles(app, appDirectory, plugins),
164
+ ...iosPluginFiles(appDirectory, coreDirectory),
165
+ }
166
+ : androidProjectFiles(app, { appDirectory, corePath: placeholders.__CORE_PATH__, plugins })
167
+ const files = { ...template, ...generated }
168
+
169
+ // A null replaces a template file with nothing.
170
+ return asEntries(Object.fromEntries(Object.entries(files).filter(([, file]) => file !== null)))
171
+ }
172
+
173
+ /** What the folder holds that prebuild didn't write, or wrote and was changed since. */
174
+ function findManualChanges(existingPaths, record, platformDirectory) {
175
+ if (existingPaths.length > 0 && !record) return { notGenerated: true, edited: [], added: [] }
176
+
177
+ const recordedHashes = { ...record?.pending, ...record?.files }
178
+ const isRecorded = (path) => path in recordedHashes
179
+ const matchesRecord = (path) => {
180
+ const current = entryHash(readEntry(join(platformDirectory, path)))
181
+
182
+ return current === record.files?.[path] || current === record.pending?.[path]
183
+ }
184
+ const edited = existingPaths.filter(
185
+ (path) => isRecorded(path) && !SEEDED_PATHS.has(path) && !matchesRecord(path),
186
+ )
187
+ const added = existingPaths.filter((path) => !isRecorded(path) && !SEEDED_PATHS.has(path))
188
+
189
+ return { notGenerated: false, edited, added }
190
+ }
191
+
192
+ function hasManualChanges({ notGenerated, edited, added }) {
193
+ return notGenerated || edited.length > 0 || added.length > 0
194
+ }
195
+
196
+ /** git's diff of the file on disk (label) against what prebuild generates, or nothing without git. */
197
+ function diffAgainstGenerated(path, label, entry) {
198
+ if (entry?.content === undefined) return ''
199
+
200
+ const directory = mkdtempSync(join(tmpdir(), 'nativue-prebuild-'))
201
+ const generatedPath = join(directory, 'generated')
202
+
203
+ writeFileSync(generatedPath, entry.content)
204
+
205
+ const { stdout } = spawnSync(
206
+ 'git',
207
+ ['diff', '--no-index', '--no-prefix', '--color=always', '--', generatedPath, path],
208
+ { encoding: 'utf8' },
209
+ )
210
+ rmSync(directory, { recursive: true, force: true })
211
+
212
+ // Without a prefix, git prints absolute paths without their leading slash.
213
+ return (stdout ?? '')
214
+ .replaceAll(generatedPath.slice(1), `${label} (generated)`)
215
+ .replaceAll(path.slice(1), `${label} (yours)`)
216
+ }
217
+
218
+ // Where a hand edit of each generated file belongs instead.
219
+ const DESTINATIONS = [
220
+ [/^Info\.plist$/, 'ios.infoPlist in nativue.config.ts'],
221
+ [/^App\.entitlements$/, 'ios.entitlements in nativue.config.ts'],
222
+ [
223
+ /^App\.xcodeproj\//,
224
+ 'nativue.config.ts: version, buildNumber, ios.appleTeamId, ios.entitlements',
225
+ ],
226
+ [/^App\/Assets\.xcassets\//, 'icon or splash in nativue.config.ts'],
227
+ [
228
+ /^app\/src\/main\/AndroidManifest\.xml$/,
229
+ 'android.permissions, or a plugin with an android.manifest mod (docs/packages.md)',
230
+ ],
231
+ [
232
+ /^app\/build\.gradle\.kts$/,
233
+ 'nativue.config.ts: version, buildNumber, android.signing, android.gradle',
234
+ ],
235
+ [
236
+ /^(build\.gradle\.kts|settings\.gradle\.kts|gradle\.properties)$/,
237
+ 'android.gradle in nativue.config.ts',
238
+ ],
239
+ [/^app\/src\/main\/res\/values\/strings\.xml$/, 'name in nativue.config.ts'],
240
+ [
241
+ /^app\/src\/main\/res\/values(-night)?\/(styles|colors)\.xml$/,
242
+ 'splash or android.adaptiveIcon.backgroundColor in nativue.config.ts',
243
+ ],
244
+ [
245
+ /^app\/src\/main\/res\/(mipmap|drawable)/,
246
+ 'icon, android.adaptiveIcon or splash in nativue.config.ts',
247
+ ],
248
+ [
249
+ /^(Extensions|ExtensionSupport)\//,
250
+ "an extension target: native/extensions/<name>/, or a plugin's ios.targets mod",
251
+ ],
252
+ [/\.(swift|kt|java)$/, 'a module in native/<name>/'],
253
+ [
254
+ /^(App\/Resources\/|app\/src\/main\/(assets\/|res\/(raw|font|xml|drawable)\/))/,
255
+ 'resources in nativue.config.ts',
256
+ ],
257
+ ]
258
+
259
+ function destination(path) {
260
+ const match = DESTINATIONS.find(([pattern]) => pattern.test(path))
261
+
262
+ return match ? ` → ${match[1]}` : ''
263
+ }
264
+
265
+ /** For a team picked in Xcode, the config field that keeps it. */
266
+ function teamHint(path, platformDirectory) {
267
+ if (!path.endsWith('project.pbxproj')) return ''
268
+
269
+ const team = readFileSync(join(platformDirectory, path), 'utf8').match(
270
+ /DEVELOPMENT_TEAM = "?(\w+)"?;/,
271
+ )?.[1]
272
+
273
+ return team ? `\nThe signing team goes in nativue.config.ts: ios: { appleTeamId: '${team}' }` : ''
274
+ }
275
+
276
+ function notGeneratedMessage(platforms) {
277
+ const folders = platforms.map((platform) => `${platform}/`).join(' and ')
278
+ const verb = platforms.length > 1 ? "weren't" : "wasn't"
279
+
280
+ return `${folders} ${verb} generated by nativue: from before nativue generated the native projects, so nativue left them alone.
281
+ Move its settings into nativue.config.ts and let nativue generate it: ${MIGRATION_GUIDE_URL}
282
+ Or keep it by hand, with this nativue.config.ts:
283
+
284
+ import { defineConfig } from '@nativue/core/config'
285
+
286
+ export default defineConfig({ prebuild: false })`
287
+ }
288
+
289
+ function manualChangesMessage(platform, changes, files, appDirectory) {
290
+ const platformDirectory = join(appDirectory, platform)
291
+
292
+ const diffs = changes.edited.map(
293
+ (path) =>
294
+ diffAgainstGenerated(join(platformDirectory, path), `${platform}/${path}`, files[path]) +
295
+ teamHint(path, platformDirectory),
296
+ )
297
+ const lines = [
298
+ ...changes.edited.map((path) => ` changed: ${platform}/${path}${destination(path)}`),
299
+ ...changes.added.map((path) => ` added: ${platform}/${path}${destination(path)}`),
300
+ ]
301
+
302
+ return `${platform}/ is generated by nativue, but was changed by hand: the next prebuild would lose this.
303
+ ${lines.join('\n')}
304
+ ${diffs.filter(Boolean).join('\n')}
305
+ Move these changes into nativue.config.ts or native/, or keep ios/ and android/ by hand with
306
+ prebuild: false in nativue.config.ts (${MIGRATION_GUIDE_URL}).
307
+ To discard them instead: npx nativue prebuild --force`
308
+ }
309
+
310
+ function writeEntry(path, entry) {
311
+ mkdirSync(dirname(path), { recursive: true })
312
+ rmSync(path, { recursive: true, force: true })
313
+
314
+ if (entry.symlink !== undefined) {
315
+ symlinkSync(entry.symlink, path)
316
+ return
317
+ }
318
+
319
+ writeFileSync(path, entry.content, { mode: entry.executable ? 0o755 : 0o644 })
320
+ }
321
+
322
+ /** Removes the folders that deleting path left empty, up to the platform folder. */
323
+ function removeEmptyParents(path, platformDirectory) {
324
+ for (
325
+ let directory = dirname(path);
326
+ directory !== platformDirectory;
327
+ directory = dirname(directory)
328
+ ) {
329
+ if (readdirSync(directory).length > 0) return
330
+
331
+ rmdirSync(directory)
332
+ }
333
+ }
334
+
335
+ /** Writes what changed and deletes what prebuild no longer generates; returns the paths it touched. */
336
+ function writePlatform(platformDirectory, files, existingPaths, record, version) {
337
+ const hashes = Object.fromEntries(
338
+ Object.entries(files)
339
+ .filter(([path]) => !SEEDED_PATHS.has(path))
340
+ .map(([path, entry]) => [path, entryHash(entry)]),
341
+ )
342
+ const existingHashes = Object.fromEntries(
343
+ existingPaths.map((path) => [path, entryHash(readEntry(join(platformDirectory, path)))]),
344
+ )
345
+ const isUpToDate = (path) =>
346
+ SEEDED_PATHS.has(path)
347
+ ? existsSync(join(platformDirectory, path))
348
+ : existingHashes[path] === hashes[path]
349
+ const changedPaths = Object.keys(files).filter((path) => !isUpToDate(path))
350
+ const removedPaths = existingPaths.filter((path) => !(path in files))
351
+
352
+ if (changedPaths.length === 0 && removedPaths.length === 0 && record?.version === version) {
353
+ return []
354
+ }
355
+
356
+ // Saved first, with both sets of hashes: a prebuild that stops halfway isn't taken for manual edits.
357
+ writeRecord(platformDirectory, { version, files: record?.files ?? {}, pending: hashes })
358
+ // Removed first: a file may take the place of a folder that held removed files.
359
+ removedPaths.forEach((path) => {
360
+ rmSync(join(platformDirectory, path), { force: true })
361
+ removeEmptyParents(join(platformDirectory, path), platformDirectory)
362
+ })
363
+ changedPaths.forEach((path) => writeEntry(join(platformDirectory, path), files[path]))
364
+ writeRecord(platformDirectory, { version, files: hashes })
365
+
366
+ return [...changedPaths, ...removedPaths]
367
+ }
368
+
369
+ /**
370
+ * Generates platforms' folders in appDirectory. Throws, before writing anything, when one was
371
+ * changed by hand, unless force. Returns the paths written or deleted, relative to appDirectory.
372
+ */
373
+ export function prebuild({
374
+ config,
375
+ plugins = [],
376
+ appDirectory,
377
+ coreDirectory,
378
+ platforms = PLATFORMS,
379
+ force = false,
380
+ }) {
381
+ // An app from before prebuild has no config for it yet: say why first, not which fields are missing.
382
+ const handKept = platforms.filter((platform) => {
383
+ const platformDirectory = join(appDirectory, platform)
384
+
385
+ return filesIn(platformDirectory).length > 0 && !readRecord(platformDirectory)
386
+ })
387
+
388
+ if (handKept.length > 0 && !force) throw new Error(notGeneratedMessage(handKept))
389
+
390
+ validateConfig(config, appDirectory, plugins)
391
+
392
+ const app = appConfig(config)
393
+ const { version } = JSON.parse(readFileSync(join(coreDirectory, 'package.json'), 'utf8'))
394
+ const plans = platforms.map((platform) => {
395
+ const platformDirectory = join(appDirectory, platform)
396
+ const files = generatedFiles(platform, { app, plugins, appDirectory, coreDirectory })
397
+ const existingPaths = filesIn(platformDirectory)
398
+ const record = readRecord(platformDirectory)
399
+ const changes = findManualChanges(existingPaths, record, platformDirectory)
400
+
401
+ return { platform, platformDirectory, files, existingPaths, record, changes }
402
+ })
403
+
404
+ const blocked = plans.filter((plan) => hasManualChanges(plan.changes))
405
+ if (blocked.length > 0 && !force) {
406
+ const messages = blocked.map(({ platform, changes, files }) =>
407
+ manualChangesMessage(platform, changes, files, appDirectory),
408
+ )
409
+ throw new Error(messages.join('\n\n'))
410
+ }
411
+
412
+ return plans.flatMap(({ platform, platformDirectory, files, existingPaths, record }) =>
413
+ writePlatform(platformDirectory, files, existingPaths, record, version).map(
414
+ (path) => `${platform}/${path}`,
415
+ ),
416
+ )
417
+ }
418
+
419
+ /**
420
+ * With `prebuild: false`: only ios/NativuePlugins, the packages' native code, written into the app's
421
+ * own ios/ when it has one, as before prebuild existed.
422
+ */
423
+ export function linkNativePackages({
424
+ config,
425
+ plugins = [],
426
+ appDirectory,
427
+ coreDirectory,
428
+ platforms = PLATFORMS,
429
+ }) {
430
+ validateConfig(config, appDirectory)
431
+ checkManualProjects(plugins, {
432
+ config,
433
+ appDirectory,
434
+ platforms,
435
+ manifest: nativueManifest({ schemes: [] }),
436
+ })
437
+
438
+ const iosDirectory = join(appDirectory, 'ios')
439
+ if (!existsSync(iosDirectory)) return []
440
+
441
+ const files = asEntries(iosPluginFiles(appDirectory, coreDirectory))
442
+ const isCurrent = (path) =>
443
+ lstatSync(join(iosDirectory, path), { throwIfNoEntry: false }) &&
444
+ entryHash(readEntry(join(iosDirectory, path))) === entryHash(files[path])
445
+ const changedPaths = Object.keys(files).filter((path) => !isCurrent(path))
446
+ // Links of packages the app no longer has.
447
+ const modulePaths = filesIn(join(iosDirectory, 'NativuePlugins/Sources')).map(
448
+ (path) => `NativuePlugins/Sources/${path.split('/')[0]}`,
449
+ )
450
+ const stalePaths = [...new Set(modulePaths)].filter(
451
+ (path) => !Object.keys(files).some((file) => file.startsWith(path)),
452
+ )
453
+
454
+ changedPaths.forEach((path) => writeEntry(join(iosDirectory, path), files[path]))
455
+ stalePaths.forEach((path) => rmSync(join(iosDirectory, path), { recursive: true, force: true }))
456
+
457
+ return [...changedPaths, ...stalePaths].map((path) => `ios/${path}`)
458
+ }