peachsim 0.1.2158 → 0.1.2172

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 (131) hide show
  1. package/README.md +7 -1
  2. package/cli/app-catalog.ts +22 -15
  3. package/cli/bridge-flow-runner.ts +8 -7
  4. package/cli/commands/cleanup.ts +4 -2
  5. package/cli/commands/control.ts +2 -1
  6. package/cli/commands/kotlin.ts +2 -2
  7. package/cli/commands/package.ts +22 -7
  8. package/cli/commands/shell-url.ts +4 -2
  9. package/cli/native-input.ts +1 -1
  10. package/cli/outbound-endpoints.ts +13 -2
  11. package/dist-lib/agent-daemon-client.cjs +1 -1
  12. package/dist-lib/agent-events.cjs +1 -1
  13. package/dist-lib/attached-projects.cjs +2 -3
  14. package/dist-lib/auth/shared-session.cjs +2 -3
  15. package/dist-lib/backend-origin.cjs +1 -1
  16. package/dist-lib/beta.cjs +1 -1
  17. package/dist-lib/beta.mjs +1 -1
  18. package/dist-lib/bridge-constants.cjs +1 -1
  19. package/dist-lib/bridge-contract-input.cjs +1 -1
  20. package/dist-lib/bridge-contract-input.mjs +1 -1
  21. package/dist-lib/bridge-contract.cjs +1 -1
  22. package/dist-lib/bridge-contract.mjs +1 -1
  23. package/dist-lib/bundle-channel.cjs +3643 -3306
  24. package/dist-lib/capture-contract.cjs +1 -1
  25. package/dist-lib/capture-contract.mjs +1 -1
  26. package/dist-lib/cloud-contract.cjs +1 -1
  27. package/dist-lib/cloud-contract.mjs +1 -1
  28. package/dist-lib/cloud-test-args.cjs +1 -1
  29. package/dist-lib/cloud-test-args.mjs +1 -1
  30. package/dist-lib/cloud.cjs +1 -1
  31. package/dist-lib/cloud.mjs +1 -1
  32. package/dist-lib/config.cjs +1 -1
  33. package/dist-lib/config.mjs +1 -1
  34. package/dist-lib/detox/index.cjs +6 -5
  35. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  36. package/dist-lib/expo-swift-bundle.cjs +4228 -8528
  37. package/dist-lib/expo-swift-metadata.cjs +5 -1
  38. package/dist-lib/expo-swift-metadata.mjs +5 -1
  39. package/dist-lib/home-paths.cjs +2 -3
  40. package/dist-lib/host/bridge-host.cjs +4566 -4253
  41. package/dist-lib/host/fetch-proxy-handler.cjs +35 -15
  42. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  43. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  44. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  45. package/dist-lib/host/websocket-proxy.cjs +1 -1
  46. package/dist-lib/index.cjs +195 -155
  47. package/dist-lib/jump-to-source-babel.cjs +1 -1
  48. package/dist-lib/jump-to-source-native.cjs +1 -1
  49. package/dist-lib/kotlin-host.cjs +12 -7
  50. package/dist-lib/menu.cjs +1 -1
  51. package/dist-lib/menu.mjs +1 -1
  52. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  53. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  54. package/dist-lib/metro-production-bundle.cjs +1 -1
  55. package/dist-lib/metro-production-bundle.mjs +1 -1
  56. package/dist-lib/metro.cjs +42 -16
  57. package/dist-lib/native-app-identity-project.cjs +10 -5
  58. package/dist-lib/native-app-identity-project.mjs +10 -5
  59. package/dist-lib/native-app-identity.cjs +9 -1
  60. package/dist-lib/native-app-identity.mjs +9 -1
  61. package/dist-lib/native-firebase-metadata.cjs +1 -1
  62. package/dist-lib/native-firebase-metadata.mjs +1 -1
  63. package/dist-lib/pdfium-raster.cjs +1 -1
  64. package/dist-lib/pdfium-raster.mjs +1 -1
  65. package/dist-lib/plist.cjs +1 -1
  66. package/dist-lib/plist.mjs +1 -1
  67. package/dist-lib/profiles.cjs +2 -3
  68. package/dist-lib/public-brand.cjs +1 -1
  69. package/dist-lib/public-origins-lib-esm.json +24 -24
  70. package/dist-lib/public-origins-lib.json +99 -78
  71. package/dist-lib/react-native-host-modules.cjs +1 -1
  72. package/dist-lib/react-native-host-modules.mjs +1 -1
  73. package/dist-lib/reap-browser.cjs +4 -2
  74. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  75. package/dist-lib/sdk.cjs +1 -1
  76. package/dist-lib/sdk.mjs +1 -1
  77. package/dist-lib/skills.cjs +5760 -5116
  78. package/dist-lib/swift-compile.cjs +22 -11
  79. package/dist-lib/swift-compile.mjs +22 -11
  80. package/dist-lib/swift-package.cjs +1 -1
  81. package/dist-lib/swift-package.mjs +1 -1
  82. package/dist-lib/swift-submit.cjs +1 -1
  83. package/dist-lib/swift-submit.mjs +1 -1
  84. package/dist-lib/swift-toolchain.cjs +1 -1
  85. package/dist-lib/swift.cjs +1 -1
  86. package/dist-lib/vite-swift.cjs +31 -15
  87. package/dist-lib/vite.cjs +119 -85
  88. package/dist-lib/worklet-executable.cjs +1 -1
  89. package/dist-lib/worklet-executable.mjs +1 -1
  90. package/dist-types/packages/peach-engine/src/engine/inspect-info.d.ts +0 -1
  91. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +3 -1
  92. package/dist-types/packages/peach-engine/src/render-worker/shell-protocol.d.ts +9 -1
  93. package/dist-types/packages/peach-engine/src/render-worker/ui-frame-clock.d.ts +26 -0
  94. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +2 -2
  95. package/dist-types/packages/peach-engine/src/render-worker/worklet-sab.d.ts +1 -6
  96. package/kotlin/README.md +5 -0
  97. package/kotlin/sdk.tar.gz +0 -0
  98. package/package.json +2 -1
  99. package/runtime-companion.json +1 -1
  100. package/src/answeredNativePackages.ts +1 -5
  101. package/src/disk-cleanup.ts +44 -1
  102. package/src/expo-native-compiler-digest.ts +2 -0
  103. package/src/expo-native-workspace.ts +61 -16
  104. package/src/expo-swift-host.ts +64 -53
  105. package/src/expoSwiftContract.ts +6 -0
  106. package/src/home-activity.ts +124 -0
  107. package/src/home-paths.ts +1 -2
  108. package/src/installed-native-build-options.ts +27 -3
  109. package/src/kotlin-app.ts +156 -31
  110. package/src/kotlin-compose-bom.ts +64 -0
  111. package/src/kotlin-host.ts +12 -3
  112. package/src/kotlin-version-catalog.ts +77 -0
  113. package/src/native-app-identity-project.ts +3 -0
  114. package/src/native-app-identity.ts +15 -0
  115. package/src/native-git.ts +12 -0
  116. package/src/native-prebuilt.ts +11 -2
  117. package/src/nitro-compile.ts +12 -4
  118. package/src/one-native-app-catalog.ts +59 -0
  119. package/src/one-sdk-preparation.ts +53 -8
  120. package/src/react-native-core-digest.ts +24 -0
  121. package/src/react-native-core.ts +239 -0
  122. package/src/reap-browser.ts +3 -1
  123. package/src/swift-compile.ts +6 -5
  124. package/src/swift-packages.ts +2 -0
  125. package/src/swift-standins.ts +6 -5
  126. package/src/swift-wasm-prune.ts +20 -2
  127. package/src/turbo-bundle.ts +1 -1
  128. package/src/turbo-compile.ts +27 -6
  129. package/src/turbo-source.ts +29 -9
  130. package/src/vite-plugin-one.ts +8 -5
  131. package/src/one-native-app-accent.ts +0 -32
@@ -0,0 +1,124 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { isRecord } from './is-record'
4
+
5
+ const ACTIVITY = '.home-activity'
6
+ const CLEANUP = '.home-cleanup'
7
+ const activated = new Set<string>()
8
+ const sleepWord = new Int32Array(new SharedArrayBuffer(4))
9
+ export const PORT_HOME_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000
10
+ export const PORT_HOME_DISPOSABLE_DIRS = ['cache', 'swift', 'nitro-dependencies']
11
+
12
+ function processAlive(pid: number): boolean {
13
+ try {
14
+ process.kill(pid, 0)
15
+ return true
16
+ } catch (error) {
17
+ return !(error instanceof Error && 'code' in error && error.code === 'ESRCH')
18
+ }
19
+ }
20
+
21
+ export function activatePeachHome(home: string): void {
22
+ if (activated.has(home)) return
23
+ const activity = path.join(home, ACTIVITY)
24
+ fs.mkdirSync(activity, { recursive: true })
25
+ const lease = path.join(activity, String(process.pid))
26
+ fs.writeFileSync(lease, '')
27
+ fs.writeFileSync(path.join(activity, 'last-opened'), '')
28
+ const guard = path.join(home, CLEANUP)
29
+ const deadline = Date.now() + 30_000
30
+ while (fs.existsSync(guard)) {
31
+ let owner: number
32
+ try {
33
+ owner = Number(fs.readFileSync(guard, 'utf8'))
34
+ } catch (error) {
35
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue
36
+ throw error
37
+ }
38
+ if (owner > 0 && !processAlive(owner)) {
39
+ fs.rmSync(guard, { force: true })
40
+ continue
41
+ }
42
+ if (Date.now() >= deadline) throw new Error(`Peach home cleanup is busy: ${home}`)
43
+ Atomics.wait(sleepWord, 0, 0, 25)
44
+ }
45
+ activated.add(home)
46
+ process.once('exit', () => fs.rmSync(lease, { force: true }))
47
+ }
48
+
49
+ function modifiedAt(directory: string): number {
50
+ let latest = 0
51
+ for (const child of fs.readdirSync(directory, { withFileTypes: true })) {
52
+ if (child.name === CLEANUP || child.name === ACTIVITY) continue
53
+ const file = path.join(directory, child.name)
54
+ const stat = fs.lstatSync(file)
55
+ latest = Math.max(latest, stat.mtimeMs)
56
+ if (child.isDirectory() && !child.isSymbolicLink())
57
+ latest = Math.max(latest, modifiedAt(file))
58
+ }
59
+ return latest
60
+ }
61
+
62
+ function homeRecord(file: string): unknown {
63
+ try {
64
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+
70
+ export function portHomeCleanupState(home: string): 'safe' | 'in-use' | 'retained' {
71
+ if (
72
+ fs.existsSync(path.join(home, 'app-runtime.json')) ||
73
+ fs.existsSync(path.join(home, 'peach-app.json'))
74
+ )
75
+ return 'retained'
76
+ const config = path.join(home, 'config.json')
77
+ if (fs.existsSync(config)) {
78
+ const saved = homeRecord(config)
79
+ if (!isRecord(saved) || Object.hasOwn(saved, 'packageDefaults')) return 'retained'
80
+ }
81
+ const daemon = path.join(home, 'daemon.json')
82
+ if (fs.existsSync(daemon)) {
83
+ const owner = homeRecord(daemon)
84
+ if (!isRecord(owner) || typeof owner.pid !== 'number' || processAlive(owner.pid))
85
+ return 'in-use'
86
+ }
87
+ const activity = path.join(home, ACTIVITY)
88
+ if (fs.existsSync(activity)) {
89
+ for (const name of fs.readdirSync(activity)) {
90
+ if (/^[0-9]+$/.test(name) && processAlive(Number(name))) return 'in-use'
91
+ }
92
+ }
93
+ const opened = path.join(activity, 'last-opened')
94
+ const lastActive = fs.existsSync(opened)
95
+ ? fs.statSync(opened).mtimeMs
96
+ : modifiedAt(home)
97
+ return Date.now() - lastActive >= PORT_HOME_EXPIRY_MS ? 'safe' : 'retained'
98
+ }
99
+
100
+ export function expirePortHomeCache(home: string, target: string): boolean {
101
+ const guard = path.join(home, CLEANUP)
102
+ const owner = `${guard}.${process.pid}`
103
+ fs.writeFileSync(owner, String(process.pid), { flag: 'wx' })
104
+ try {
105
+ fs.linkSync(owner, guard)
106
+ } catch (error) {
107
+ if (error instanceof Error && 'code' in error && error.code === 'EEXIST') return false
108
+ throw error
109
+ } finally {
110
+ fs.unlinkSync(owner)
111
+ }
112
+ let guarded = true
113
+ try {
114
+ if (portHomeCleanupState(home) !== 'safe') return false
115
+ const retired = path.join(home, `.expired-${path.basename(target)}-${process.pid}`)
116
+ fs.renameSync(target, retired)
117
+ fs.unlinkSync(guard)
118
+ guarded = false
119
+ fs.rmSync(retired, { recursive: true, force: true })
120
+ return true
121
+ } finally {
122
+ if (guarded) fs.unlinkSync(guard)
123
+ }
124
+ }
package/src/home-paths.ts CHANGED
@@ -52,8 +52,7 @@ export function ambientHomeDir(): string {
52
52
 
53
53
  export function rnxHomeDir(): string {
54
54
  const override = process.env[PEACH_HOME_ENV]
55
- if (override && override.length > 0) return path.resolve(override)
56
- return ambientHomeDir()
55
+ return override && override.length > 0 ? path.resolve(override) : ambientHomeDir()
57
56
  }
58
57
 
59
58
  // where the pinned wasm SDK installs unless PEACH_SWIFT_SDKS_PATH names another
@@ -102,9 +102,33 @@ function* nativeBuildOptionsWalk(
102
102
  versions: PackageVersions,
103
103
  environment: NodeJS.ProcessEnv,
104
104
  ): Walk<NativeBuildOptions> {
105
- if (!needsRiveOptions(versions)) return {}
105
+ let sensorOptions: NativeBuildOptions = {}
106
+ const sensors = versions['expo-sensors']
107
+ if (
108
+ sensors &&
109
+ resolveCompatVersionRange(['>=58.0.4 <59.0.0'], sensors).status === 'matched'
110
+ ) {
111
+ const file = path.join(projectRoot, 'ios', 'Podfile.properties.json')
112
+ const source = yield { type: 'read', path: file }
113
+ if (source !== null && typeof source !== 'string')
114
+ throw new Error(`cannot inspect ${file}`)
115
+ const properties: unknown = source === null ? {} : JSON.parse(source)
116
+ if (
117
+ typeof properties !== 'object' ||
118
+ properties === null ||
119
+ Array.isArray(properties)
120
+ )
121
+ throw new Error(`${file} must contain an object`)
122
+ sensorOptions = {
123
+ 'expo-sensors': {
124
+ EXPO_DISABLE_MOTION_PERMISSION:
125
+ Reflect.get(properties, 'MOTION_PERMISSION') === 'false',
126
+ },
127
+ }
128
+ }
129
+ if (!needsRiveOptions(versions)) return sensorOptions
106
130
  if (environment.USE_RIVE_LEGACY === '1' || environment.USE_RIVE_LEGACY === 'true')
107
- return { [RIVE_PACKAGE]: { USE_RIVE_LEGACY: true } }
131
+ return { ...sensorOptions, [RIVE_PACKAGE]: { USE_RIVE_LEGACY: true } }
108
132
 
109
133
  const ios = path.join(projectRoot, 'ios')
110
134
  const podfile = path.join(ios, 'Podfile')
@@ -126,7 +150,7 @@ function* nativeBuildOptionsWalk(
126
150
  value = literal[1] === 'true'
127
151
  }
128
152
  }
129
- return { [RIVE_PACKAGE]: { USE_RIVE_LEGACY: value } }
153
+ return { ...sensorOptions, [RIVE_PACKAGE]: { USE_RIVE_LEGACY: value } }
130
154
  }
131
155
 
132
156
  export function readInstalledNativeBuildOptions(
package/src/kotlin-app.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // reads a pure Kotlin Android app module the way its Gradle build and the
2
2
  // device resolve it, for the subset Peach boots: one module's `main` source
3
- // set, its own manifest, literal Gradle values and the pinned Compose closure.
3
+ // set, its own manifest, supported Gradle values and the pinned Compose closure.
4
4
  // anything outside that subset rejects with its location, never approximated.
5
5
 
6
6
  import fs from 'node:fs'
@@ -17,6 +17,8 @@ import {
17
17
  import { parseXml, type XmlElement } from './android-xml'
18
18
  import frameworkThemes from './generated/android-framework-themes.json' with { type: 'json' }
19
19
  import { isRecord } from './is-record'
20
+ import { composeBomVersions } from './kotlin-compose-bom'
21
+ import { KotlinVersionCatalog } from './kotlin-version-catalog'
20
22
 
21
23
  // statusBarColor and navigationBarColor are ARGB
22
24
  export interface KotlinWindowTheme {
@@ -34,6 +36,7 @@ export interface KotlinAppProject {
34
36
  moduleDir: string
35
37
  sources: string[]
36
38
  language: string
39
+ usesSerialization: boolean
37
40
  packageName: string
38
41
  namespace: string
39
42
  targetSdk: number
@@ -72,6 +75,9 @@ export interface AndroidPins {
72
75
  navigation: string
73
76
  activity: string
74
77
  materialIcons: string
78
+ serializationCore: string
79
+ kotlin: string
80
+ coroutines: string
75
81
  }
76
82
 
77
83
  const ANDROID_NS = 'android:'
@@ -81,6 +87,7 @@ const PLUGINS = new Set([
81
87
  'com.android.application',
82
88
  'org.jetbrains.kotlin.android',
83
89
  'org.jetbrains.kotlin.plugin.compose',
90
+ 'org.jetbrains.kotlin.plugin.serialization',
84
91
  ])
85
92
  // the closure Peach links. compose, navigation and activity artifacts must
86
93
  // match their Android pins (Peach's activity actuals are that version's); the
@@ -96,6 +103,12 @@ const ANDROID_PIN: Record<string, keyof AndroidPins> = {
96
103
  'androidx.compose.material3': 'material3',
97
104
  'androidx.navigation': 'navigation',
98
105
  'androidx.activity': 'activity',
106
+ 'org.jetbrains.kotlinx:kotlinx-serialization-core': 'serializationCore',
107
+ 'org.jetbrains.kotlin:kotlin-stdlib': 'kotlin',
108
+ 'org.jetbrains.kotlin:kotlin-stdlib-jdk7': 'kotlin',
109
+ 'org.jetbrains.kotlin:kotlin-stdlib-jdk8': 'kotlin',
110
+ 'org.jetbrains.kotlinx:kotlinx-coroutines-core': 'coroutines',
111
+ 'org.jetbrains.kotlinx:kotlinx-coroutines-android': 'coroutines',
99
112
  }
100
113
 
101
114
  // the Android artifact versions Peach's Kotlin closure is pinned to, from
@@ -104,14 +117,36 @@ export function readAndroidPins(moduleRoot: string): AndroidPins {
104
117
  const toolchain: unknown = JSON.parse(
105
118
  fs.readFileSync(path.join(moduleRoot, 'toolchain.json'), 'utf8'),
106
119
  )
107
- const android =
108
- isRecord(toolchain) && isRecord(toolchain.compose) ? toolchain.compose.android : null
109
- const pin = (name: keyof AndroidPins) => {
120
+ if (!isRecord(toolchain))
121
+ throw new Error('peachsim kotlin/toolchain.json is not an object')
122
+ const android = isRecord(toolchain.compose) ? toolchain.compose.android : null
123
+ const pin = (
124
+ name: Exclude<keyof AndroidPins, 'serializationCore' | 'kotlin' | 'coroutines'>,
125
+ ) => {
110
126
  const value = isRecord(android) ? android[name] : undefined
111
127
  if (typeof value !== 'string')
112
128
  throw new Error(`peachsim kotlin/toolchain.json has no Android ${name} pin`)
113
129
  return value
114
130
  }
131
+ const libraryPin = (name: string, libraries: unknown): string => {
132
+ const prefix = `${name}-wasm-js-`
133
+ const versions = Array.isArray(libraries)
134
+ ? libraries.flatMap((library: unknown) =>
135
+ isRecord(library) &&
136
+ typeof library.name === 'string' &&
137
+ library.name.startsWith(prefix) &&
138
+ library.name.endsWith('.klib')
139
+ ? [library.name.slice(prefix.length, -'.klib'.length)]
140
+ : [],
141
+ )
142
+ : []
143
+ if (versions.length !== 1 || !versions[0])
144
+ throw new Error(`peachsim kotlin/toolchain.json has no unique ${name} pin`)
145
+ return versions[0]
146
+ }
147
+ const kotlin = isRecord(toolchain.compiler) ? toolchain.compiler.version : undefined
148
+ if (typeof kotlin !== 'string')
149
+ throw new Error('peachsim kotlin/toolchain.json has no Kotlin compiler version')
115
150
  return {
116
151
  ui: pin('ui'),
117
152
  foundation: pin('foundation'),
@@ -120,6 +155,12 @@ export function readAndroidPins(moduleRoot: string): AndroidPins {
120
155
  navigation: pin('navigation'),
121
156
  activity: pin('activity'),
122
157
  materialIcons: pin('materialIcons'),
158
+ serializationCore: libraryPin(
159
+ 'kotlinx-serialization-core',
160
+ toolchain.composeLibraries,
161
+ ),
162
+ kotlin,
163
+ coroutines: libraryPin('kotlinx-coroutines-core', toolchain.libraries),
123
164
  }
124
165
  }
125
166
 
@@ -141,11 +182,23 @@ function gradleLiteral(
141
182
  gradle: { file: string; text: string },
142
183
  name: string,
143
184
  pattern: string,
185
+ catalog: KotlinVersionCatalog,
144
186
  ): string | null {
145
187
  const literal = new RegExp(`\\b${name}\\s*=?\\s*(${pattern})\\s*$`, 'm').exec(
146
188
  gradle.text,
147
189
  )
148
190
  if (literal?.[1]) return literal[1].replace(/^"|"$/g, '')
191
+ const reference = new RegExp(
192
+ `\\b${name}\\s*=?\\s*(?:project\\.)?libs\\.versions\\.([\\w.]+)\\.get\\(\\)(?:\\.toInt\\(\\))?\\s*$`,
193
+ 'm',
194
+ ).exec(gradle.text)
195
+ if (reference?.[1]) {
196
+ const where = `${gradle.file}:${lineOf(gradle.text, reference.index)}`
197
+ const value = catalog.scalar(reference[1], where)
198
+ if (!new RegExp(`^(?:${pattern})$`).test(value))
199
+ throw new Error(`${where}: catalog value ${value} is invalid for ${name}`)
200
+ return value
201
+ }
149
202
  const any = new RegExp(`\\b${name}\\b\\s*=?\\s*\\S`, 'm').exec(gradle.text)
150
203
  if (any)
151
204
  throw new Error(
@@ -157,6 +210,7 @@ function gradleLiteral(
157
210
  function kotlinPluginVersion(
158
211
  projectDir: string,
159
212
  moduleGradle: { file: string; text: string },
213
+ catalog: KotlinVersionCatalog,
160
214
  ) {
161
215
  const sources = [readGradle(projectDir), moduleGradle].filter((value) => value !== null)
162
216
  for (const gradle of sources) {
@@ -165,25 +219,56 @@ function kotlinPluginVersion(
165
219
  gradle.text,
166
220
  ) ?? /kotlin\(\s*"android"\s*\)\s*version\s*"([^"]+)"/.exec(gradle.text)
167
221
  if (match?.[1]) return match[1]
168
- }
169
- const catalog = path.join(projectDir, 'gradle', 'libs.versions.toml')
170
- if (fs.existsSync(catalog)) {
171
- const match = /^kotlin\s*=\s*"([^"]+)"/m.exec(fs.readFileSync(catalog, 'utf8'))
172
- if (match?.[1]) return match[1]
222
+ for (const alias of gradle.text.matchAll(
223
+ /\balias\(\s*libs\.plugins\.([\w.]+)\s*\)/g,
224
+ )) {
225
+ const plugin = catalog.plugin(
226
+ alias[1] ?? '',
227
+ `${gradle.file}:${lineOf(gradle.text, alias.index)}`,
228
+ )
229
+ if (
230
+ plugin.id === 'org.jetbrains.kotlin.android' ||
231
+ plugin.id === 'org.jetbrains.kotlin.plugin.compose'
232
+ )
233
+ return plugin.version
234
+ }
173
235
  }
174
236
  throw new Error(
175
237
  `${projectDir} declares no literal org.jetbrains.kotlin.android plugin version`,
176
238
  )
177
239
  }
178
240
 
179
- function checkModuleGradle(gradle: { file: string; text: string }, pins: AndroidPins) {
241
+ async function checkModuleGradle(
242
+ gradle: { file: string; text: string },
243
+ pins: AndroidPins,
244
+ catalog: KotlinVersionCatalog,
245
+ ) {
180
246
  const at = (index: number) => `${gradle.file}:${lineOf(gradle.text, index)}`
247
+ const coordinates = (value: string, where: string): string[] => {
248
+ const alias = /^libs\.([\w.]+)$/.exec(value)
249
+ const literal = /^["']([^"']+)["']$/.exec(value)
250
+ if (alias?.[1]) return catalog.dependencies(alias[1], where)
251
+ if (literal?.[1]) return [literal[1]]
252
+ throw new Error(`${where}: ${value} is not a literal or catalog dependency`)
253
+ }
254
+ const platforms = new Map<string, string>()
255
+ const dependencies: { coordinate: string; where: string }[] = []
256
+ let usesSerialization = false
181
257
  for (const match of gradle.text.matchAll(
182
- /\bid\(\s*"([^"]+)"\s*\)|\bkotlin\(\s*"([^"]+)"\s*\)/g,
258
+ /\bid\(\s*"([^"]+)"\s*\)|\bkotlin\(\s*"([^"]+)"\s*\)|\balias\(\s*libs\.plugins\.([\w.]+)\s*\)/g,
183
259
  )) {
184
- const plugin = match[1] ?? `org.jetbrains.kotlin.${match[2]}`
260
+ const plugin = match[3]
261
+ ? catalog.plugin(match[3], at(match.index)).id
262
+ : (match[1] ?? `org.jetbrains.kotlin.${match[2]}`)
185
263
  if (!PLUGINS.has(plugin))
186
264
  throw new Error(`${at(match.index)}: plugin ${plugin} is not supported by Peach`)
265
+ if (
266
+ plugin === 'org.jetbrains.kotlin.plugin.serialization' &&
267
+ !/^(?:\s+version\s+"[^"]+")?\s+apply\s+false\b/.test(
268
+ gradle.text.slice(match.index + match[0].length),
269
+ )
270
+ )
271
+ usesSerialization = true
187
272
  }
188
273
  for (const block of gradle.text.matchAll(/\bdependencies\s*\{/g)) {
189
274
  // the block runs to its matching brace, on one line or many; every
@@ -197,28 +282,64 @@ function checkModuleGradle(gradle: { file: string; text: string }, pins: Android
197
282
  }
198
283
  if (depth > 0) throw new Error(`${at(block.index)}: dependencies block never closes`)
199
284
  const body = gradle.text.slice(start, end - 1)
285
+ const platformVariables = new Map<string, string>()
200
286
  for (const statement of body.matchAll(/[^\n;]+/g)) {
201
287
  const text = statement[0].replace(/\/\/.*$/, '').trim()
202
288
  if (!text) continue
203
289
  const where = at(start + statement.index)
290
+ const variable = /^val\s+(\w+)\s*=\s*(platform\(.*\))$/.exec(text)
291
+ if (variable?.[1] && variable[2]) {
292
+ platformVariables.set(variable[1], variable[2])
293
+ continue
294
+ }
204
295
  const call = /^(\w+)\s*\(\s*(.*?)\s*\)$/.exec(text)
205
296
  if (!call) throw new Error(`${where}: ${text} is not a literal dependency`)
206
297
  const [, configuration = '', value = ''] = call
207
298
  if (/^(test|androidTest|debug|release)/.test(configuration)) continue
208
- const coordinate = /^["']([^"':]+):([^"':]+):([^"']+)["']$/.exec(value)
209
- if (!coordinate)
210
- throw new Error(`${where}: ${value} is not a literal group:artifact:version`)
211
- const [, group = '', artifact, version] = coordinate
212
- const pin = ANDROID_PIN[`${group}:${artifact}`] ?? ANDROID_PIN[group]
213
- if (pin) {
214
- if (version !== pins[pin])
215
- throw new Error(
216
- `${where}: ${group}:${artifact}:${version} differs from Peach's ${pin} pin ${pins[pin]}`,
217
- )
218
- } else if (!PLATFORM_GROUPS.has(group))
219
- throw new Error(`${where}: ${group}:${artifact} is not in Peach's Kotlin closure`)
299
+ const platform = /^platform\(\s*(.*?)\s*\)$/.exec(
300
+ platformVariables.get(value) ?? value,
301
+ )
302
+ if (platform?.[1]) {
303
+ const declared = coordinates(platform[1], where)
304
+ if (declared.length !== 1 || !declared[0])
305
+ throw new Error(`${where}: platform expects one BOM coordinate`)
306
+ for (const [name, version] of await composeBomVersions(declared[0])) {
307
+ const previous = platforms.get(name)
308
+ if (previous && previous !== version)
309
+ throw new Error(
310
+ `${where}: conflicting BOM versions ${previous} and ${version} for ${name}`,
311
+ )
312
+ platforms.set(name, version)
313
+ }
314
+ } else {
315
+ for (const coordinate of coordinates(value, where))
316
+ dependencies.push({ coordinate, where })
317
+ }
220
318
  }
221
319
  }
320
+ for (const { coordinate, where } of dependencies) {
321
+ const parts = /^([^:]+):([^:]+)(?::([^:]+))?$/.exec(coordinate)
322
+ if (!parts)
323
+ throw new Error(`${where}: ${coordinate} is not a group:artifact[:version]`)
324
+ const [, group = '', artifact = '', requested] = parts
325
+ const name = `${group}:${artifact}`
326
+ const managed = platforms.get(name)
327
+ if (requested && managed && requested !== managed)
328
+ throw new Error(
329
+ `${where}: ${name} has explicit ${requested} and BOM ${managed}; Gradle conflict resolution is not supported by Peach`,
330
+ )
331
+ const version = requested ?? managed
332
+ if (!version) throw new Error(`${where}: ${name} has no version or BOM constraint`)
333
+ const pin = ANDROID_PIN[name] ?? ANDROID_PIN[group]
334
+ if (pin) {
335
+ if (version !== pins[pin])
336
+ throw new Error(
337
+ `${where}: ${name}:${version} differs from Peach's ${pin} pin ${pins[pin]}`,
338
+ )
339
+ } else if (!PLATFORM_GROUPS.has(group))
340
+ throw new Error(`${where}: ${name} is not in Peach's Kotlin closure`)
341
+ }
342
+ return { usesSerialization }
222
343
  }
223
344
 
224
345
  // Resources.selectDefaultTheme: the theme a context without one gets for its
@@ -375,10 +496,10 @@ function isLauncher(element: XmlElement): boolean {
375
496
  )
376
497
  }
377
498
 
378
- export function readKotlinApp(
499
+ export async function readKotlinApp(
379
500
  moduleArg: string,
380
501
  options: { activity?: string; pins: AndroidPins },
381
- ): KotlinAppProject {
502
+ ): Promise<KotlinAppProject> {
382
503
  const moduleDir = fs.realpathSync(path.resolve(moduleArg))
383
504
  const manifestFile = path.join(moduleDir, 'src/main/AndroidManifest.xml')
384
505
  if (!fs.existsSync(manifestFile))
@@ -398,13 +519,16 @@ export function readKotlinApp(
398
519
  }
399
520
  const gradle = readGradle(moduleDir)
400
521
  if (!gradle) throw new Error(`${moduleDir} has no build.gradle`)
401
- checkModuleGradle(gradle, options.pins)
402
- const namespace = gradleLiteral(gradle, 'namespace', '"[\\w.]+"')
403
- const applicationId = gradleLiteral(gradle, 'applicationId', '"[\\w.]+"')
404
- const targetSdk = Number(gradleLiteral(gradle, 'targetSdk(?:Version)?', '\\d+'))
522
+ const catalog = new KotlinVersionCatalog(projectDir)
523
+ const { usesSerialization } = await checkModuleGradle(gradle, options.pins, catalog)
524
+ const namespace = gradleLiteral(gradle, 'namespace', '"[\\w.]+"', catalog)
525
+ const applicationId = gradleLiteral(gradle, 'applicationId', '"[\\w.]+"', catalog)
526
+ const targetSdk = Number(
527
+ gradleLiteral(gradle, 'targetSdk(?:Version)?', '\\d+', catalog),
528
+ )
405
529
  if (!Number.isInteger(targetSdk) || targetSdk <= 0)
406
530
  throw new Error(`${gradle.file}: declares no literal targetSdk`)
407
- const kotlin = kotlinPluginVersion(projectDir, gradle)
531
+ const kotlin = kotlinPluginVersion(projectDir, gradle, catalog)
408
532
  const language = /^(\d+)\.(\d+)/.exec(kotlin)?.slice(1, 3).join('.')
409
533
  if (!language)
410
534
  throw new Error(`Kotlin plugin version ${kotlin} names no language version`)
@@ -560,6 +684,7 @@ export function readKotlinApp(
560
684
  moduleDir,
561
685
  sources: sources.sort(),
562
686
  language,
687
+ usesSerialization,
563
688
  packageName: applicationId ?? base,
564
689
  namespace: base,
565
690
  targetSdk,
@@ -0,0 +1,64 @@
1
+ import { parseXml, type XmlElement } from './android-xml'
2
+
3
+ const requests = new Map<string, Promise<ReadonlyMap<string, string>>>()
4
+ const field = (element: XmlElement, name: string) =>
5
+ element.children.find((child) => child.name === name)?.text.trim()
6
+
7
+ export function composeBomVersions(
8
+ coordinate: string,
9
+ ): Promise<ReadonlyMap<string, string>> {
10
+ const pending = requests.get(coordinate)
11
+ if (pending) return pending
12
+ const request = (async () => {
13
+ const match = /^(androidx\.compose):(compose-bom(?:-alpha|-beta)?):([\w.-]+)$/.exec(
14
+ coordinate,
15
+ )
16
+ if (!match) throw new Error(`unsupported Kotlin platform dependency ${coordinate}`)
17
+ const [, group = '', artifact = '', version = ''] = match
18
+ const url = `https://dl.google.com/dl/android/maven2/${group.replaceAll('.', '/')}/${artifact}/${version}/${artifact}-${version}.pom`
19
+ const response = await fetch(url)
20
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`)
21
+ const project = parseXml(await response.text(), url).children.find(
22
+ (element) => element.name === 'project',
23
+ )
24
+ if (
25
+ !project ||
26
+ field(project, 'groupId') !== group ||
27
+ field(project, 'artifactId') !== artifact ||
28
+ field(project, 'version') !== version ||
29
+ field(project, 'packaging') !== 'pom'
30
+ )
31
+ throw new Error(`${url} does not declare ${coordinate}`)
32
+ const management = project.children.find(
33
+ (element) => element.name === 'dependencyManagement',
34
+ )
35
+ const dependencies = management?.children.find(
36
+ (element) => element.name === 'dependencies',
37
+ )
38
+ if (!dependencies) throw new Error(`${url} has no managed dependencies`)
39
+ const versions = new Map<string, string>()
40
+ for (const dependency of dependencies.children) {
41
+ const dependencyGroup = field(dependency, 'groupId')
42
+ const dependencyArtifact = field(dependency, 'artifactId')
43
+ const dependencyVersion = field(dependency, 'version')
44
+ if (
45
+ dependency.name !== 'dependency' ||
46
+ !dependencyGroup ||
47
+ !dependencyArtifact ||
48
+ !dependencyVersion ||
49
+ dependencyVersion.includes('${') ||
50
+ field(dependency, 'scope') === 'import'
51
+ )
52
+ throw new Error(`${url} contains an unsupported managed dependency`)
53
+ const name = `${dependencyGroup}:${dependencyArtifact}`
54
+ if (versions.has(name)) throw new Error(`${url} repeats managed dependency ${name}`)
55
+ versions.set(name, dependencyVersion)
56
+ }
57
+ return versions
58
+ })().catch((error: unknown) => {
59
+ requests.delete(coordinate)
60
+ throw error
61
+ })
62
+ requests.set(coordinate, request)
63
+ return request
64
+ }
@@ -131,7 +131,7 @@ function entrySource(ids: string[]): string {
131
131
  '',
132
132
  '@OptIn(kotlin.js.ExperimentalJsExport::class)',
133
133
  '@JsExport',
134
- 'fun peachSetAndroidBuildInfo(model: String, release: String) = Build.setDevice(model, release)',
134
+ 'fun peachSetAndroidBuildInfo(model: String, release: String, apiLevel: Int) = Build.setDevice(model, release, apiLevel)',
135
135
  '',
136
136
  '@OptIn(kotlin.js.ExperimentalJsExport::class, kotlinx.coroutines.DelicateCoroutinesApi::class)',
137
137
  '@JsExport',
@@ -726,8 +726,8 @@ export async function expoKotlinArtifact(
726
726
  ' ))',
727
727
  '}',
728
728
  '',
729
- '@JsExport fun peachSetAndroidBuildInfo(model: String, release: String) =',
730
- ' android.os.Build.setDevice(model, release)',
729
+ '@JsExport fun peachSetAndroidBuildInfo(model: String, release: String, apiLevel: Int) =',
730
+ ' android.os.Build.setDevice(model, release, apiLevel)',
731
731
  '',
732
732
  '@JsExport fun peachExpoListen(notify: () -> Unit) {',
733
733
  ' registered',
@@ -884,6 +884,7 @@ export async function kotlinAppArtifact(
884
884
  generated,
885
885
  sdkProfile: 'app',
886
886
  usesCompose: true,
887
+ usesSerialization: app.usesSerialization,
887
888
  viewModels: {
888
889
  file: 'PeachAppEntry.kt',
889
890
  render: appEntry,
@@ -1103,6 +1104,7 @@ async function compileKotlin(
1103
1104
  origins?: Record<string, string>
1104
1105
  sdkProfile: KotlinSdkProfile
1105
1106
  usesCompose: boolean
1107
+ usesSerialization?: boolean
1106
1108
  // a generated file that names the app's view models: rendered empty for a
1107
1109
  // first compile, then from that klib's ABI
1108
1110
  viewModels?: {
@@ -1123,6 +1125,7 @@ async function compileKotlin(
1123
1125
  origins = {},
1124
1126
  sdkProfile,
1125
1127
  usesCompose,
1128
+ usesSerialization = false,
1126
1129
  viewModels,
1127
1130
  } = input
1128
1131
  const sdk = await loadKotlinSdk(moduleRoot, toolchain)
@@ -1161,6 +1164,7 @@ async function compileKotlin(
1161
1164
  language,
1162
1165
  sdk: sdk.sha256,
1163
1166
  sdkProfile,
1167
+ usesSerialization,
1164
1168
  }),
1165
1169
  )
1166
1170
  for (const { file, bytes } of inputs)
@@ -1226,6 +1230,11 @@ async function compileKotlin(
1226
1230
  `-Xplugin=${path.resolve(path.dirname(kotlinc), '../lib/compose-compiler-plugin.jar')}`,
1227
1231
  ]
1228
1232
  : []),
1233
+ ...(usesSerialization
1234
+ ? [
1235
+ `-Xplugin=${path.resolve(path.dirname(kotlinc), '../lib/kotlinx-serialization-compiler-plugin.jar')}`,
1236
+ ]
1237
+ : []),
1229
1238
  '-language-version',
1230
1239
  language,
1231
1240
  '-api-version',