@nativue/core 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/AGENTS.md +39 -7
  2. package/README.md +1 -0
  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 +66 -7
  6. package/android/src/main/java/dev/nativue/NativueActivity.kt +12 -5
  7. package/android/src/main/java/dev/nativue/Permissions.kt +107 -0
  8. package/android/src/main/java/dev/nativue/Plugins.kt +98 -15
  9. package/cli/android-project.mjs +377 -0
  10. package/cli/app-config.mjs +526 -0
  11. package/cli/config.d.mts +162 -3
  12. package/cli/ios-project.mjs +652 -0
  13. package/cli/link.mjs +66 -71
  14. package/cli/nativue.mjs +39 -5
  15. package/cli/plugins.mjs +236 -0
  16. package/cli/prebuild.mjs +458 -0
  17. package/cli/run.mjs +2 -2
  18. package/cli/serialize.mjs +168 -0
  19. package/ios/AppLifecycle.swift +165 -0
  20. package/ios/Bridge.swift +53 -4
  21. package/ios/NativueView.swift +5 -1
  22. package/ios/Permissions.swift +19 -0
  23. package/ios/Plugins.swift +24 -0
  24. package/package.json +3 -2
  25. package/src/globals.ts +7 -1
  26. package/src/native-events.ts +99 -0
  27. package/src/native-functions.ts +16 -2
  28. package/src/permissions.ts +57 -0
  29. package/src/renderer.ts +5 -1
  30. package/src/router.ts +2 -1
  31. package/src/types.ts +3 -0
  32. package/template/android/app/src/debug/AndroidManifest.xml +4 -0
  33. package/template/android/app/src/main/java/MainActivity.kt +5 -0
  34. package/template/android/app/src/main/res/drawable-night-xxxhdpi/splash_logo.png +0 -0
  35. package/template/android/app/src/main/res/drawable-xxxhdpi/splash_logo.png +0 -0
  36. package/template/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +6 -0
  37. package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  38. package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  39. package/template/android/app/src/main/res/values/colors.xml +4 -0
  40. package/template/android/app/src/main/res/values/styles.xml +15 -0
  41. package/template/android/app/src/main/res/values-night/styles.xml +5 -0
  42. package/template/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  43. package/template/android/gradle/wrapper/gradle-wrapper.properties +9 -0
  44. package/template/android/gradlew +248 -0
  45. package/template/android/gradlew.bat +112 -0
  46. package/template/ios/App/App.swift +18 -0
  47. package/template/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json +1 -0
  48. package/template/ios/App/Assets.xcassets/AppIcon.appiconset/icon.png +0 -0
  49. package/template/ios/App/Assets.xcassets/Contents.json +1 -0
  50. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/Contents.json +11 -0
  51. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@1x.png +0 -0
  52. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@2x.png +0 -0
  53. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@3x.png +0 -0
  54. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@1x.png +0 -0
  55. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@2x.png +0 -0
  56. package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@3x.png +0 -0
  57. package/template/ios/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +15 -0
package/cli/link.mjs CHANGED
@@ -1,36 +1,31 @@
1
- // Links the iOS side of the app's packages: those whose package.json has
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 becomes a Swift package with a target per package (a link to its sources) and
4
- // `nativuePlugins`, the list App.swift passes to NativueView. The app's Xcode project depends on it
5
- // alone; it re-exports Nativue. (Android finds them itself: android/nativue.settings.gradle.kts.)
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
- existsSync,
12
- mkdirSync,
13
- readdirSync,
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
- const APP_NATIVE_DIRECTORY = 'native'
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 = process.cwd(); ; directory = dirname(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
- function iosPlugins() {
50
- const { dependencies = {}, devDependencies = {} } = readJson('package.json')
51
- const names = [...Object.keys(dependencies), ...Object.keys(devDependencies)]
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
- return names.flatMap((name) => {
54
- const directory = packageDirectory(name)
55
- const ios = directory && readJson(join(directory, 'package.json')).nativue?.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
- if (!existsSync(APP_NATIVE_DIRECTORY)) return []
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
- return readdirSync(APP_NATIVE_DIRECTORY).flatMap((name) => {
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(APP_NATIVE_DIRECTORY, name, 'nativue.json')
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 (packages/core/cli/link.mjs): rewritten on every build.
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 (packages/core/cli/link.mjs): rewritten on every build.
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
- /** coreDirectory: @nativue/core's folder, which holds its Package.swift. */
181
- export function linkIosPlugins(coreDirectory) {
182
- if (!existsSync('ios') || !existsSync('package.json')) return
183
-
184
- const plugins = [...iosPlugins(), ...appPlugins()]
185
- const corePath = relative(resolve(PLUGINS_DIRECTORY), coreDirectory)
186
-
187
- linkSources(plugins)
188
- writeIfChanged(`${PLUGINS_DIRECTORY}/Package.swift`, packageManifest(plugins, corePath))
189
- writeIfChanged(`${SOURCES_DIRECTORY}/${LIST_TARGET}/Plugins.swift`, pluginList(plugins))
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,5 +1,8 @@
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
@@ -26,7 +29,8 @@ import { randomUUID } from 'node:crypto'
26
29
  import { createRequire } from 'node:module'
27
30
  import { dirname, relative } from 'node:path'
28
31
  import { fileURLToPath } from 'node:url'
29
- import { linkIosPlugins } from './link.mjs'
32
+ import { resolvePlugins } from './plugins.mjs'
33
+ import { linkNativePackages, PLATFORMS, prebuild } from './prebuild.mjs'
30
34
  import { runOnAndroid, runOnIOS } from './run.mjs'
31
35
  import { createSymbolicator, framedFiles } from './symbolicate.mjs'
32
36
 
@@ -182,7 +186,11 @@ function pluginRuntimes(plugins) {
182
186
  }
183
187
  }
184
188
 
185
- const { plugins: appPlugins = [] } = await loadAppConfig()
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
+ })
186
194
  const APP_VITE_PLUGINS = [
187
195
  pluginRuntimes(appPlugins),
188
196
  ...appPlugins.flatMap((plugin) => plugin.vite ?? []),
@@ -508,12 +516,38 @@ async function runApp(platform, args) {
508
516
  console.log('\nA dev server is already running: the app reloads from it.')
509
517
  }
510
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
+
511
533
  const [command, ...args] = process.argv.slice(2)
512
534
 
513
535
  try {
514
- if (['dev', 'build', 'run'].includes(command)) linkIosPlugins(frameworkPath(''))
536
+ if (command === 'dev' || command === 'build') generateNativeProjects(LOCAL_PLATFORMS)
537
+ if (command === 'run' && RUNNERS[args[0]]) generateNativeProjects([args[0]])
538
+
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
+ }
515
545
 
516
- if (command === 'dev') {
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') {
517
551
  await dev()
518
552
  } else if (command === 'build') {
519
553
  await build(
@@ -525,7 +559,7 @@ try {
525
559
  await runApp(args[0], args.slice(1))
526
560
  } else {
527
561
  console.log(
528
- '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]>',
529
563
  )
530
564
  process.exitCode = 1
531
565
  }
@@ -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
+ }