peachsim 0.1.1716 → 0.1.1728

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 (234) hide show
  1. package/README.md +21 -3
  2. package/cli/app-bundle-resources.ts +2 -1
  3. package/cli/app-fonts.ts +4 -4
  4. package/cli/app-splash.ts +4 -4
  5. package/cli/app-stubs.ts +17 -0
  6. package/cli/command-registry.ts +1 -0
  7. package/cli/commands/control.ts +82 -822
  8. package/cli/commands/daemon.ts +8 -0
  9. package/cli/commands/detox.ts +3 -0
  10. package/cli/commands/doctor.ts +19 -2
  11. package/cli/commands/inspect/actions.ts +74 -14
  12. package/cli/commands/inspect/core.ts +5 -1
  13. package/cli/commands/inspect/settling.ts +5 -2
  14. package/cli/commands/inspect/wait-ready.ts +6 -0
  15. package/cli/commands/inspect.ts +48 -45
  16. package/cli/commands/kotlin.ts +12 -2
  17. package/cli/commands/package.ts +750 -0
  18. package/cli/commands/serve.ts +6 -0
  19. package/cli/commands/shell-url.ts +834 -0
  20. package/cli/commands/swift.ts +42 -102
  21. package/cli/commands/test.ts +20 -0
  22. package/cli/commands/upload.ts +1 -1
  23. package/cli/device-option.ts +1 -1
  24. package/cli/main.ts +13 -1
  25. package/cli/native-input.ts +199 -0
  26. package/cli/outbound-endpoints.ts +26 -1
  27. package/cli/packaged-app-launcher.ts +95 -0
  28. package/cli/scene-video.ts +13 -6
  29. package/detox/index.ts +187 -23
  30. package/dist-lib/agent-daemon-client.cjs +1 -1
  31. package/dist-lib/agent-events.cjs +1 -1
  32. package/dist-lib/attached-projects.cjs +1 -1
  33. package/dist-lib/auth/shared-session.cjs +1 -1
  34. package/dist-lib/backend-origin.cjs +1 -1
  35. package/dist-lib/beta.cjs +1 -1
  36. package/dist-lib/beta.mjs +1 -1
  37. package/dist-lib/bridge-constants.cjs +1 -1
  38. package/dist-lib/bridge-contract-input.cjs +1 -1
  39. package/dist-lib/bridge-contract-input.mjs +1 -1
  40. package/dist-lib/bridge-contract.cjs +1 -1
  41. package/dist-lib/bridge-contract.mjs +1 -1
  42. package/dist-lib/bundle-channel.cjs +38000 -31658
  43. package/dist-lib/capture-contract.cjs +1 -1
  44. package/dist-lib/capture-contract.mjs +1 -1
  45. package/dist-lib/cloud-contract.cjs +1 -1
  46. package/dist-lib/cloud-contract.mjs +1 -1
  47. package/dist-lib/cloud-test-args.cjs +1 -1
  48. package/dist-lib/cloud-test-args.mjs +1 -1
  49. package/dist-lib/cloud.cjs +1 -1
  50. package/dist-lib/cloud.mjs +1 -1
  51. package/dist-lib/config.cjs +1 -1
  52. package/dist-lib/config.mjs +1 -1
  53. package/dist-lib/detox/index.cjs +184 -60
  54. package/dist-lib/dev-bundle-resolution.cjs +14 -13
  55. package/dist-lib/expo-swift-bundle.cjs +18199 -11834
  56. package/dist-lib/expo-swift-metadata.cjs +4 -1
  57. package/dist-lib/expo-swift-metadata.mjs +3 -1
  58. package/dist-lib/home-paths.cjs +21 -2
  59. package/dist-lib/host/bridge-host.cjs +26509 -23850
  60. package/dist-lib/host/fetch-proxy-handler.cjs +221 -222
  61. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  62. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  63. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  64. package/dist-lib/host/websocket-proxy.cjs +1 -1
  65. package/dist-lib/index.cjs +876 -389
  66. package/dist-lib/jump-to-source-babel.cjs +1 -1
  67. package/dist-lib/jump-to-source-native.cjs +1 -1
  68. package/dist-lib/kotlin-host.cjs +127 -16
  69. package/dist-lib/menu.cjs +7 -1
  70. package/dist-lib/menu.mjs +7 -1
  71. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  72. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  73. package/dist-lib/metro-production-bundle.cjs +1 -1
  74. package/dist-lib/metro-production-bundle.mjs +1 -1
  75. package/dist-lib/metro.cjs +883 -404
  76. package/dist-lib/native-app-identity-project.cjs +694 -280
  77. package/dist-lib/native-app-identity-project.mjs +490 -83
  78. package/dist-lib/native-app-identity.cjs +13 -2
  79. package/dist-lib/native-app-identity.mjs +13 -2
  80. package/dist-lib/native-firebase-metadata.cjs +1 -1
  81. package/dist-lib/native-firebase-metadata.mjs +1 -1
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +1 -1
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +28 -23
  87. package/dist-lib/public-origins-lib.json +392 -224
  88. package/dist-lib/react-native-host-modules.cjs +32 -2
  89. package/dist-lib/react-native-host-modules.mjs +32 -2
  90. package/dist-lib/reap-browser.cjs +12 -4
  91. package/dist-lib/scripts/dev-server-scanner.cjs +15 -8
  92. package/dist-lib/sdk.cjs +17 -7
  93. package/dist-lib/sdk.mjs +16 -7
  94. package/dist-lib/skills.cjs +61838 -47851
  95. package/dist-lib/swift-compile.cjs +583 -360
  96. package/dist-lib/swift-compile.mjs +496 -275
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +1 -1
  99. package/dist-lib/swift-submit.cjs +2 -2
  100. package/dist-lib/swift-submit.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +105 -17
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vite-swift.cjs +4453 -2231
  104. package/dist-lib/vite.cjs +230 -228
  105. package/dist-lib/worklet-executable.cjs +1 -1
  106. package/dist-lib/worklet-executable.mjs +1 -1
  107. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-cookies.d.ts +17 -8
  108. package/dist-types/packages/peach-engine/src/engine/canvaskit-renderer.d.ts +1 -0
  109. package/dist-types/packages/peach-engine/src/engine/image-loader.d.ts +7 -5
  110. package/dist-types/packages/peach-engine/src/engine/memory-counts.d.ts +3 -1
  111. package/dist-types/packages/peach-engine/src/engine/node.d.ts +1 -11
  112. package/dist-types/packages/peach-engine/src/engine/types.d.ts +3 -0
  113. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +9 -0
  114. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  115. package/dist-types/packages/peach-engine/src/render-worker/native-ui-commandContract.d.ts +1 -1
  116. package/dist-types/packages/peach-engine/src/render-worker/shell-protocol.d.ts +4 -0
  117. package/dist-types/packages/peach-engine/src/render-worker/tree-sync-port.d.ts +1 -1
  118. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +23 -1
  119. package/dist-types/packages/peach-engine/src/shell-events.d.ts +1 -0
  120. package/dist-types/packages/peach-globals/src/audioBridgeContract.d.ts +5 -0
  121. package/dist-types/packages/peach-globals/src/index.d.ts +1 -1
  122. package/dist-types/packages/peach-globals/src/keyboardBridgeContract.d.ts +11 -0
  123. package/dist-types/packages/peach-globals/src/shellBridgeContract.d.ts +1 -0
  124. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +9 -2
  125. package/package.json +1 -1
  126. package/runtime-companion.json +1 -1
  127. package/scripts/dev-server-scanner.ts +12 -25
  128. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASFoundation.h +52 -0
  129. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASWebAuthenticationSession.h +128 -0
  130. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASWebAuthenticationSessionCallback.h +35 -0
  131. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/AuthenticationServices.h +3 -0
  132. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Modules/module.modulemap +5 -0
  133. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHTTPMessage.h +724 -0
  134. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +4 -0
  135. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetworkDefs.h +27 -0
  136. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Modules/module.modulemap +5 -0
  137. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CFURL.h +1301 -0
  138. package/sdk/ios/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.h +2 -0
  139. package/sdk/ios/System/Library/Frameworks/CoreLocation.framework/Headers/CLLocationManager.h +21 -50
  140. package/sdk/ios/System/Library/Frameworks/CoreLocation.framework/Headers/CLRegion.h +6 -6
  141. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h +75 -9
  142. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIApplication.h +12 -0
  143. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIInterface.h +23 -0
  144. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h +7 -9
  145. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIOrientation.h +14 -0
  146. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIStringDrawing.h +12 -0
  147. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIView.h +14 -0
  148. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIViewAnimating.h +12 -0
  149. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIViewController.h +16 -0
  150. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIWindow.h +2 -0
  151. package/sdk/ios/usr/include/ConditionalMacros.h +619 -0
  152. package/sdk/ios/usr/include/module.modulemap +1 -0
  153. package/sdk/ios/usr/include/objc/objc-sync.h +59 -0
  154. package/sdk/ios/usr/include/os.modulemap +5 -0
  155. package/sdk/ios/usr/include/sys/cdefs.h +5 -0
  156. package/sdk/ios/usr/include/sys/ioccom.h +99 -0
  157. package/sdk/ios/usr/include/sys/syslog.h +236 -0
  158. package/sdk/ios/usr/include/syslog.h +24 -0
  159. package/sdk/ios/wasm/include/fcntl.h +4 -2
  160. package/sdk/ios/wasm/include/stdio.h +24 -0
  161. package/sdk/ios/wasm/include/stdlib.h +32 -7
  162. package/sdk/ios/wasm/include/sys/file.h +7 -0
  163. package/sdk/ios/wasm/include/sys/ioctl.h +6 -0
  164. package/sdk/ios/wasm/include/sys/syscall.h +9 -0
  165. package/sdk/ios/wasm/include/sys/time.h +10 -0
  166. package/sdk/ios/wasm/include/unistd.h +12 -3
  167. package/sdk/native-hashes.json +1 -0
  168. package/skills/contrast/SKILL.md +2 -1
  169. package/skills/peach-test/SKILL.md +7 -3
  170. package/src/admitted-mac-build.ts +3 -0
  171. package/src/android-app-identity.ts +18 -0
  172. package/src/android-root-module.ts +9 -9
  173. package/src/appPackageContract.ts +81 -0
  174. package/src/bridge-contract.ts +50 -0
  175. package/src/bundle-channel.mjs +21 -4
  176. package/src/dev-bundle-resolution.ts +7 -27
  177. package/src/dom-source-reference.ts +15 -0
  178. package/src/expo-discovery-cache.ts +127 -23
  179. package/src/expo-manifest-body.ts +33 -0
  180. package/src/expo-native-workspace.ts +38 -13
  181. package/src/expo-swift-host.ts +264 -62
  182. package/src/expoSwiftContract.ts +3 -0
  183. package/src/generated/swift-c-predefines.json +1 -1
  184. package/src/home-paths.ts +35 -1
  185. package/src/host/app-package-handler.ts +47 -0
  186. package/src/host/bridge-host.ts +3 -0
  187. package/src/host/staged-host-files.ts +18 -0
  188. package/src/index.ts +3 -0
  189. package/src/kotlin-host.ts +21 -18
  190. package/src/kotlin-instance-source.ts +126 -0
  191. package/src/menu.ts +7 -0
  192. package/src/native-app-identity-project.ts +7 -2
  193. package/src/native-app-identity.ts +11 -0
  194. package/src/native-firebase-config.ts +24 -1
  195. package/src/nitro-adapter.lock.json +268 -268
  196. package/src/nitro-bundle.ts +8 -0
  197. package/src/nitro-compile.ts +35 -9
  198. package/src/nitro-dependencies.ts +21 -19
  199. package/src/nitro-source.ts +4 -0
  200. package/src/nitroContract.ts +7 -0
  201. package/src/react-native-bridge-modules.ts +68 -42
  202. package/src/react-native-host-modules.ts +31 -1
  203. package/src/reactNativeConfigurationContract.ts +14 -0
  204. package/src/reap-browser.ts +15 -3
  205. package/src/sdk.ts +5 -0
  206. package/src/settingsContract.ts +27 -1
  207. package/src/sim-client.ts +4 -1
  208. package/src/storageSnapshotContract.ts +3 -0
  209. package/src/swift-compile.ts +221 -41
  210. package/src/swift-coverage/provenance.ts +1 -0
  211. package/src/swift-coverage/xcode-asset-symbols.ts +922 -0
  212. package/src/swift-coverage/xcode-assets.ts +89 -131
  213. package/src/swift-coverage/xcode.ts +1 -1
  214. package/src/swift-cxx-reachable.ts +2 -1
  215. package/src/swift-distribution.lock.json +14 -13
  216. package/src/swift-host.ts +95 -22
  217. package/src/swift-icu.ts +1 -1
  218. package/src/swift-link-roots.ts +118 -0
  219. package/src/swift-objc-compile.ts +144 -22
  220. package/src/swift-objc-import.ts +6 -0
  221. package/src/swift-objc-standin.ts +2 -14
  222. package/src/swift-package-manifest.ts +14 -6
  223. package/src/swift-packages.ts +75 -11
  224. package/src/swift-pdf-raster.ts +1 -0
  225. package/src/swift-root-lock.ts +17 -1
  226. package/src/swift-source-pods.ts +2 -10
  227. package/src/swift-standin-emit.ts +592 -57
  228. package/src/swift-standins.ts +430 -49
  229. package/src/swift-submit.ts +3 -1
  230. package/src/swift-toolchain.ts +140 -17
  231. package/src/turbo-codegen-intake.ts +91 -0
  232. package/src/vite-plugin-one.ts +13 -9
  233. package/src/vite-plugin.ts +28 -15
  234. package/src/xcode-project.ts +223 -22
@@ -0,0 +1,750 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import {
7
+ extractAssetDescriptors,
8
+ metroAssetScaleFilename,
9
+ } from '../../../contrast-bundler/src/metroAssetArtifact'
10
+ import {
11
+ APP_PACKAGE_ORIGIN,
12
+ APP_PACKAGE_ADDRESS_PATTERN,
13
+ packageSettingDefaults,
14
+ type AppPackageManifest,
15
+ } from '../../src/appPackageContract'
16
+ import {
17
+ detachBundleGlobalFooter,
18
+ stripBundleMetadataFooter,
19
+ } from '../../src/bundleGlobalFooter'
20
+ import { getCliRuntime, verifyCliCompanion } from '../../src/cli-runtime'
21
+ import { produceConfiguredBundle } from '../../src/configured-bundle-producer'
22
+ import { activeDesktopHostApp } from '../../src/desktop-host-delivery'
23
+ import { insertExpoKotlinFooter } from '../../src/expoKotlinContract'
24
+ import { insertExpoSwiftFooter } from '../../src/expoSwiftContract'
25
+ import { readActiveRuntime } from '../../src/home-paths'
26
+ import {
27
+ captureStagedHostFiles,
28
+ stageHostBytes,
29
+ stageHostLaunchMetadata,
30
+ } from '../../src/host/staged-host-files'
31
+ import { readInstalledNativePackageVersionsAsync } from '../../src/installed-package-versions'
32
+ import { isRecord } from '../../src/is-record'
33
+ import { readNativeAppIdentityFromProject } from '../../src/native-app-identity-project'
34
+ import { readExpoConfigAsync } from '../../src/native-firebase-config'
35
+ import { insertNitroFooter } from '../../src/nitroContract'
36
+ import {
37
+ insertPackageVersionsFooter,
38
+ readPackageVersions,
39
+ readPackageVersionsFooter,
40
+ type PackageVersions,
41
+ } from '../../src/packageVersionsContract'
42
+ import { resolveActiveRuntimeRoot } from '../../src/runtime-assets'
43
+ import { loadRNXAppConfig } from '../app-config'
44
+ import { resolveAppProject } from '../app-project'
45
+ import {
46
+ parseAppSplashWire,
47
+ splashImageUrls,
48
+ splashImageContentType,
49
+ } from '../app-splash'
50
+ import { prepareNativeInput, resolveNativeInput } from '../native-input'
51
+ import { packagedAppLauncher } from '../packaged-app-launcher'
52
+ import { IS_STANDALONE } from '../standalone'
53
+ import {
54
+ buildShellUrl,
55
+ resolveAppProjectForBundleUrl,
56
+ stagePrebuiltBundle,
57
+ } from './control'
58
+
59
+ const origin = APP_PACKAGE_ORIGIN
60
+
61
+ async function projectIcon(
62
+ project: string,
63
+ scratch: string,
64
+ ): Promise<string | undefined> {
65
+ const config = await readExpoConfigAsync(project)
66
+ if (typeof config.icon === 'string') return path.resolve(project, config.icon)
67
+ const artwork = readNativeAppIdentityFromProject(project, 'ios')?.appIconArtwork
68
+ ?.primary?.[0]?.uri
69
+ if (!artwork?.startsWith('data:')) return undefined
70
+ const icon = path.join(scratch, 'icon.png')
71
+ fs.writeFileSync(icon, Buffer.from(artwork.slice(artwork.indexOf(',') + 1), 'base64'))
72
+ return icon
73
+ }
74
+
75
+ export async function runPackage(args: string[]): Promise<void> {
76
+ if (process.platform !== 'darwin')
77
+ throw new Error('peach package currently builds macOS apps')
78
+ const input = [...args]
79
+ const values = new Map<string, string>()
80
+ const settings: string[] = []
81
+ const positionals: string[] = []
82
+ for (let i = 0; i < input.length; i++) {
83
+ const flag = input[i]!
84
+ if (!flag.startsWith('-')) {
85
+ positionals.push(flag)
86
+ continue
87
+ }
88
+ if (
89
+ ![
90
+ '--name',
91
+ '--output',
92
+ '--identifier',
93
+ '--icon',
94
+ '--splash',
95
+ '--setting',
96
+ '--cli',
97
+ '--host-app',
98
+ '--target',
99
+ '--scheme',
100
+ '--activity',
101
+ '--package-versions',
102
+ '--project-root',
103
+ '--compositor',
104
+ '--sign',
105
+ '--notarize',
106
+ ].includes(flag)
107
+ )
108
+ throw new Error(`unknown peach package option: ${flag}`)
109
+ const value = input[++i]
110
+ if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`)
111
+ if (flag === '--setting') settings.push(value)
112
+ else values.set(flag, value)
113
+ }
114
+ const target = positionals[0]
115
+ if (!target || positionals.length !== 1)
116
+ throw new Error(
117
+ 'usage: peach package <target> --name <name> [--output <app|zip|dmg> --setting key=value --sign <identity> --notarize <profile>]',
118
+ )
119
+ const name = values.get('--name') ?? path.basename(target, path.extname(target))
120
+ const identifier =
121
+ values.get('--identifier') ??
122
+ `dev.peach.app.${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`
123
+ if (
124
+ !name.trim() ||
125
+ /[/\0]/.test(name) ||
126
+ !/^[A-Za-z0-9]+(?:[.-][A-Za-z0-9-]+)+$/.test(identifier)
127
+ )
128
+ throw new Error('package name or bundle identifier is invalid')
129
+ const output = path.resolve(values.get('--output') ?? `${name}.app`)
130
+ const archive = path.extname(output)
131
+ if (!['.app', '.zip', '.dmg'].includes(archive) || fs.existsSync(output))
132
+ throw new Error('--output must name a new .app, .zip or .dmg')
133
+ // a Developer ID identity signs with the hardened runtime; notarization reads
134
+ // credentials saved by `xcrun notarytool store-credentials <profile>`
135
+ const identity = values.get('--sign')
136
+ const notaryProfile = values.get('--notarize')
137
+ if (identity && !identity.startsWith('Developer ID Application: '))
138
+ throw new Error('--sign needs a Developer ID Application identity')
139
+ if (notaryProfile && !identity) throw new Error('--notarize needs --sign')
140
+ const defaults = packageSettingDefaults(settings)
141
+ const compositor = values.get('--compositor') ?? 'node'
142
+ if (!['native', 'webkit', 'node'].includes(compositor))
143
+ throw new Error('--compositor must be native, webkit or node')
144
+ const versionsFile = values.get('--package-versions')
145
+ const versions = versionsFile
146
+ ? readPackageVersions(JSON.parse(fs.readFileSync(path.resolve(versionsFile), 'utf8')))
147
+ : null
148
+ let configuredVersions: PackageVersions | null = null
149
+ const prepareBundle = async (source: string) => {
150
+ source = source.replaceAll(origin, '')
151
+ if (versions || configuredVersions)
152
+ source = insertPackageVersionsFooter(source, {
153
+ ...configuredVersions,
154
+ ...readPackageVersionsFooter(source),
155
+ ...versions,
156
+ })
157
+ return getCliRuntime().rolldown_bundle_inventory.attachRolldownBundleHttpPayload(
158
+ source,
159
+ 'application/javascript',
160
+ )
161
+ }
162
+ const selectedHost =
163
+ values.get('--host-app') ?? process.env.PEACH_DESKTOP_APP ?? activeDesktopHostApp()
164
+ const host = selectedHost ? path.resolve(selectedHost) : null
165
+ const runtime = resolveActiveRuntimeRoot()
166
+ const runtimeVersion = readActiveRuntime()
167
+ if (!host || !runtime || !runtimeVersion)
168
+ throw new Error(
169
+ 'install the Peach desktop app and an engine runtime before packaging',
170
+ )
171
+ verifyCliCompanion(runtime)
172
+ const cli =
173
+ values.get('--cli') ??
174
+ (IS_STANDALONE
175
+ ? process.execPath
176
+ : path.resolve(import.meta.dirname, '../../dist-bin/peach-darwin-arm64'))
177
+ if (!fs.existsSync(cli))
178
+ throw new Error('source packaging needs a built CLI binary; pass --cli <binary>')
179
+ // the app is assembled beside the output, so archives and the final move stay on its volume
180
+ const staging = `${output}.${randomUUID()}`
181
+ const temporary = path.join(staging, `${name}.app`)
182
+ fs.mkdirSync(staging)
183
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'peach-package-'))
184
+ const routes: AppPackageManifest['routes'] = {}
185
+ let icon = values.get('--icon')
186
+ let requiresServer = false
187
+ const route = (pathname: string, bytes: Uint8Array, contentType: string) => {
188
+ const extension = contentType === 'application/javascript' ? '.js' : ''
189
+ const url = stageHostBytes(bytes, origin, extension)
190
+ routes[pathname] = { file: path.basename(new URL(url).pathname), contentType }
191
+ return origin + pathname
192
+ }
193
+ try {
194
+ const captured = await captureStagedHostFiles(async () => {
195
+ let launchUrl: string
196
+ const native = resolveNativeInput(target)
197
+ const local = fs.statSync(path.resolve(target), { throwIfNoEntry: false })
198
+ const project = local
199
+ ? resolveAppProject(
200
+ local.isDirectory() ? target : path.dirname(path.resolve(target)),
201
+ )
202
+ : null
203
+ const configuredProject = values.has('--project-root')
204
+ ? resolveAppProject(values.get('--project-root')!)
205
+ : project
206
+ if (values.has('--project-root') && !configuredProject)
207
+ throw new Error('--project-root must name an app project')
208
+ if (configuredProject)
209
+ configuredVersions = await readInstalledNativePackageVersionsAsync(
210
+ configuredProject.appDir,
211
+ )
212
+ if (!icon && configuredProject)
213
+ icon = await projectIcon(configuredProject.appDir, scratch)
214
+ if (native) {
215
+ const app = await prepareNativeInput(native, {
216
+ origin,
217
+ target: values.get('--target'),
218
+ scheme: values.get('--scheme'),
219
+ activity: values.get('--activity'),
220
+ })
221
+ try {
222
+ for (const [pathname, asset] of app.assets)
223
+ route(pathname, asset.bytes, asset.contentType)
224
+ route(
225
+ app.metadataPath,
226
+ Buffer.from(JSON.stringify(app.metadata)),
227
+ 'application/json',
228
+ )
229
+ const bundle = route(
230
+ app.guestPath,
231
+ Buffer.from(app.guestSource),
232
+ 'application/javascript',
233
+ )
234
+ const url = new URL('/rn', origin)
235
+ url.searchParams.set('bundle', bundle)
236
+ launchUrl = url.href
237
+ if (!icon && app.icon) {
238
+ icon = path.join(scratch, 'icon.png')
239
+ fs.writeFileSync(icon, app.icon.bytes)
240
+ }
241
+ } finally {
242
+ app.dispose()
243
+ }
244
+ } else if (
245
+ (local?.isFile() && target.endsWith('.json')) ||
246
+ /^https?:\/\/.+\.json(?:\?.*)?$/.test(target)
247
+ ) {
248
+ const readChannel = async (): Promise<unknown> => {
249
+ if (local?.isFile())
250
+ return JSON.parse(fs.readFileSync(path.resolve(target), 'utf8'))
251
+ const response = await fetch(target)
252
+ if (!response.ok)
253
+ throw new Error(`app release metadata: HTTP ${response.status}`)
254
+ return response.json()
255
+ }
256
+ const channel = await readChannel()
257
+ if (
258
+ !isRecord(channel) ||
259
+ channel.schemaVersion !== 1 ||
260
+ typeof channel.bundleUrl !== 'string' ||
261
+ typeof channel.bundleHash !== 'string' ||
262
+ !/^[a-f0-9]{64}$/.test(channel.bundleHash) ||
263
+ typeof channel.iconUrl !== 'string'
264
+ )
265
+ throw new Error('invalid app release metadata')
266
+ const bundleResponse = await fetch(channel.bundleUrl)
267
+ if (!bundleResponse.ok)
268
+ throw new Error(`app release bundle: HTTP ${bundleResponse.status}`)
269
+ const bytes = Buffer.from(await bundleResponse.arrayBuffer())
270
+ if (createHash('sha256').update(bytes).digest('hex') !== channel.bundleHash)
271
+ throw new Error('app release bundle hash mismatch')
272
+ let source = bytes.toString('utf8')
273
+ const resources = new Set<string>()
274
+ const visit = (value: unknown) => {
275
+ if (Array.isArray(value)) {
276
+ for (const child of value) visit(child)
277
+ return
278
+ }
279
+ if (!isRecord(value)) return
280
+ for (const [key, child] of Object.entries(value)) {
281
+ if ((key === 'url' || key === 'icuUrl') && typeof child === 'string')
282
+ resources.add(child)
283
+ else visit(child)
284
+ }
285
+ }
286
+ if (configuredProject) {
287
+ const root = configuredProject.appDir
288
+ const config = await loadRNXAppConfig(configuredProject)
289
+ source = detachBundleGlobalFooter(source, '__peachExpoSwift').source
290
+ source = detachBundleGlobalFooter(source, '__peachExpoKotlin').source
291
+ source = stripBundleMetadataFooter(source, 'nitro')
292
+ if (channel.platform === 'android') {
293
+ const native = await (
294
+ await import('../../src/expo-kotlin-bundle')
295
+ ).buildExpoKotlinBundle(root)
296
+ if (native) {
297
+ for (const asset of native.assets)
298
+ route('/' + asset.path, asset.bytes, asset.contentType)
299
+ source = insertExpoKotlinFooter(source, native.metadata)
300
+ }
301
+ } else {
302
+ const native = await (
303
+ await import('../../src/expo-swift-bundle')
304
+ ).buildExpoSwiftBundle(root)
305
+ if (native) {
306
+ for (const asset of native.assets)
307
+ route('/' + asset.path, asset.bytes, asset.contentType)
308
+ source = insertExpoSwiftFooter(source, native.metadata)
309
+ }
310
+ const nitro = await (
311
+ await import('../../src/nitro-bundle')
312
+ ).buildNitroBundle(root)
313
+ if (nitro) {
314
+ for (const asset of nitro.assets)
315
+ route('/' + asset.path, asset.bytes, asset.contentType)
316
+ source = insertNitroFooter(source, nitro.metadata)
317
+ }
318
+ }
319
+ source = await produceConfiguredBundle(
320
+ source,
321
+ config,
322
+ new Set(Object.keys(versions ?? readPackageVersionsFooter(source) ?? {})),
323
+ )
324
+ } else {
325
+ visit(channel.expoSwift)
326
+ visit(channel.expoKotlin)
327
+ visit(channel.nitro)
328
+ }
329
+ for (const descriptor of extractAssetDescriptors(source)) {
330
+ if (!descriptor.httpServerLocation) continue
331
+ const directory = new URL(descriptor.httpServerLocation, channel.bundleUrl)
332
+ const packaged =
333
+ '/__peach/app-assets/' +
334
+ createHash('sha256').update(directory.href).digest('hex')
335
+ for (const scale of descriptor.scales) {
336
+ const filename = metroAssetScaleFilename(
337
+ descriptor.name,
338
+ descriptor.type,
339
+ scale,
340
+ )
341
+ const asset = await fetch(`${directory.href.replace(/\/$/, '')}/${filename}`)
342
+ if (!asset.ok) throw new Error(`app asset ${filename}: HTTP ${asset.status}`)
343
+ route(
344
+ `${packaged}/${filename}`,
345
+ new Uint8Array(await asset.arrayBuffer()),
346
+ asset.headers.get('content-type') ?? 'application/octet-stream',
347
+ )
348
+ }
349
+ source = source.replaceAll(
350
+ JSON.stringify(descriptor.httpServerLocation),
351
+ JSON.stringify(packaged),
352
+ )
353
+ }
354
+ for (const url of resources) {
355
+ const asset = await fetch(url)
356
+ if (!asset.ok) throw new Error(`native app resource: HTTP ${asset.status}`)
357
+ const packaged =
358
+ '/__peach/app-assets/' +
359
+ createHash('sha256').update(url).digest('hex') +
360
+ path.extname(new URL(url).pathname)
361
+ route(
362
+ packaged,
363
+ new Uint8Array(await asset.arrayBuffer()),
364
+ asset.headers.get('content-type') ?? 'application/octet-stream',
365
+ )
366
+ source = source.replaceAll(JSON.stringify(url), JSON.stringify(packaged))
367
+ }
368
+ if (!icon) {
369
+ const artwork = await fetch(channel.iconUrl)
370
+ if (!artwork.ok) throw new Error(`app icon: HTTP ${artwork.status}`)
371
+ icon = path.join(scratch, 'icon.png')
372
+ fs.writeFileSync(icon, Buffer.from(await artwork.arrayBuffer()))
373
+ }
374
+ const prepared = await prepareBundle(source)
375
+ const bundle = route(
376
+ '/__peach/app.js',
377
+ Buffer.from(prepared),
378
+ 'application/javascript',
379
+ )
380
+ const url = new URL('/rn', origin)
381
+ url.searchParams.set('bundle', bundle)
382
+ launchUrl = url.href
383
+ } else if (local?.isDirectory()) {
384
+ const { snapshotOneDevBundle, prepareBundleChannel } =
385
+ await import('../../src/bundle-channel.mjs')
386
+ const snapshot = await snapshotOneDevBundle(
387
+ path.resolve(target),
388
+ {},
389
+ // the project's own node: a notarized host's node refuses the
390
+ // project's ad hoc signed native addons under library validation.
391
+ { platforms: ['ios'], runtimeExecutable: 'node' },
392
+ )
393
+ const snapshotIcon = path.join(scratch, 'channel-icon.png')
394
+ execFileSync(
395
+ '/usr/bin/sips',
396
+ [
397
+ '-s',
398
+ 'format',
399
+ 'png',
400
+ icon ? path.resolve(icon) : path.join(host, 'Contents/Resources/Peach.icns'),
401
+ '--out',
402
+ snapshotIcon,
403
+ ],
404
+ { stdio: 'ignore' },
405
+ )
406
+ const release = prepareBundleChannel({
407
+ prefix: 'app',
408
+ publicOrigin: origin,
409
+ sourceSha: createHash('sha1')
410
+ .update(snapshot.platforms[0].bundle)
411
+ .digest('hex'),
412
+ runtimeVersion: '1',
413
+ name,
414
+ icon: fs.readFileSync(snapshotIcon),
415
+ ...snapshot,
416
+ })
417
+ const channel = release.channels[0]
418
+ for (const object of channel.objects) {
419
+ const bytes = object.key.endsWith('/bundle.js')
420
+ ? Buffer.from(await prepareBundle(object.bytes.toString('utf8')))
421
+ : object.bytes
422
+ route('/' + object.key, bytes, object.contentType)
423
+ }
424
+ launchUrl = await buildShellUrl(channel.metadata.bundleUrl, origin, {
425
+ bridgePort: 65534,
426
+ resolvedBundle: {
427
+ bundleUrl: channel.metadata.bundleUrl,
428
+ port: 65534,
429
+ framework: 'one',
430
+ },
431
+ project: resolveAppProject(target),
432
+ offline: true,
433
+ hot: false,
434
+ })
435
+ } else if (local?.isFile()) {
436
+ const bundle = await stagePrebuiltBundle(path.resolve(target), 65534)
437
+ launchUrl = await buildShellUrl(bundle.bundleUrl, origin, {
438
+ bridgePort: 65534,
439
+ resolvedBundle: bundle,
440
+ project: resolveAppProject(path.dirname(path.resolve(target))),
441
+ offline: true,
442
+ hot: false,
443
+ })
444
+ } else {
445
+ launchUrl = await buildShellUrl(target, origin, { bridgePort: 65534, hot: false })
446
+ requiresServer =
447
+ new URL(launchUrl).searchParams.has('bundle') ||
448
+ new URL(launchUrl).pathname.startsWith('/rn/')
449
+ if (!icon) {
450
+ const opened = await resolveAppProjectForBundleUrl(
451
+ new URL(launchUrl).searchParams.get('bundle') ?? undefined,
452
+ )
453
+ if (opened) icon = await projectIcon(opened.appDir, scratch)
454
+ }
455
+ }
456
+ if (project && !values.has('--splash')) {
457
+ const splash = new URL(launchUrl).searchParams.get('appSplash')
458
+ const spec = splash ? parseAppSplashWire(splash) : null
459
+ if (spec)
460
+ for (const image of splashImageUrls(spec)) {
461
+ const pathname = new URL(image).pathname
462
+ if (!pathname.startsWith('/assets/'))
463
+ throw new Error('app splash must name a project asset')
464
+ const file = path.resolve(
465
+ project.appDir,
466
+ decodeURIComponent(pathname.slice('/assets/'.length)),
467
+ )
468
+ if (!file.startsWith(project.appDir + path.sep))
469
+ throw new Error('app splash is outside its project')
470
+ route(pathname, fs.readFileSync(file), splashImageContentType(image))
471
+ }
472
+ }
473
+ if (values.has('--splash')) {
474
+ const url = new URL(launchUrl)
475
+ const image = stageHostBytes(
476
+ fs.readFileSync(path.resolve(values.get('--splash')!)),
477
+ origin,
478
+ path.extname(values.get('--splash')!),
479
+ )
480
+ const { encodeAppSplashWire } = await import('../app-splash')
481
+ url.searchParams.set(
482
+ 'appSplash',
483
+ encodeAppSplashWire({
484
+ source: 'one-native',
485
+ imageUrl: image,
486
+ backgroundColor: '#ffffff',
487
+ }),
488
+ )
489
+ launchUrl = url.href
490
+ }
491
+ return stageHostLaunchMetadata(new URL(launchUrl), origin)
492
+ })
493
+ fs.mkdirSync(path.dirname(output), { recursive: true })
494
+ execFileSync('/usr/bin/ditto', [host, temporary])
495
+ const contents = path.join(temporary, 'Contents')
496
+ const resources = path.join(contents, 'Resources')
497
+ const plist = path.join(contents, 'Info.plist')
498
+ const hostInfo: unknown = JSON.parse(
499
+ execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', plist], {
500
+ encoding: 'utf8',
501
+ }),
502
+ )
503
+ if (!isRecord(hostInfo) || typeof hostInfo.CFBundleExecutable !== 'string')
504
+ throw new Error('native host has no executable')
505
+ const hostExecutable = hostInfo.CFBundleExecutable
506
+ fs.cpSync(runtime, path.join(resources, 'runtime'), {
507
+ recursive: true,
508
+ dereference: true,
509
+ })
510
+ fs.copyFileSync(cli, path.join(resources, 'bin', 'peach'))
511
+ fs.mkdirSync(path.join(resources, 'payload'))
512
+ const relocatableFiles: string[] = []
513
+ for (const [file, source] of captured.files) {
514
+ const bytes = fs.readFileSync(source)
515
+ if (
516
+ bytes.includes(Buffer.from('127.0.0.1')) &&
517
+ new RegExp(APP_PACKAGE_ADDRESS_PATTERN, 'i').test(bytes.toString('utf8'))
518
+ )
519
+ relocatableFiles.push(file)
520
+ fs.copyFileSync(source, path.join(resources, 'payload', file))
521
+ }
522
+ const manifest: AppPackageManifest = {
523
+ schemaVersion: 1,
524
+ buildId: randomUUID(),
525
+ identifier,
526
+ name,
527
+ origin,
528
+ hostExecutable,
529
+ hostArguments: ['--compositor', compositor],
530
+ runtimeVersion,
531
+ launchUrl: captured.value,
532
+ defaults,
533
+ relocatableFiles,
534
+ routes,
535
+ requiresServer,
536
+ }
537
+ fs.writeFileSync(path.join(resources, 'peach-app.json'), JSON.stringify(manifest))
538
+ fs.writeFileSync(path.join(resources, 'app-launcher.cjs'), packagedAppLauncher)
539
+ fs.writeFileSync(
540
+ path.join(contents, 'MacOS', 'PeachApp'),
541
+ '#!/bin/sh\nexec "$(dirname "$0")/../Frameworks/node" "$(dirname "$0")/../Resources/app-launcher.cjs" "$@"\n',
542
+ { mode: 0o755 },
543
+ )
544
+ const bundleInfo: Record<string, unknown> = {
545
+ ...hostInfo,
546
+ CFBundleExecutable: 'PeachApp',
547
+ CFBundleIdentifier: identifier,
548
+ CFBundleName: name,
549
+ CFBundleDisplayName: name,
550
+ }
551
+ for (const key of ['CFBundleURLTypes', 'SUFeedURL', 'SUPublicEDKey'])
552
+ delete bundleInfo[key]
553
+ fs.writeFileSync(plist, JSON.stringify(bundleInfo))
554
+ execFileSync('/usr/bin/plutil', ['-convert', 'xml1', plist])
555
+ if (icon) {
556
+ const iconset = path.join(scratch, 'App.iconset')
557
+ fs.mkdirSync(iconset)
558
+ for (const size of [16, 32, 128, 256, 512]) {
559
+ execFileSync(
560
+ '/usr/bin/sips',
561
+ [
562
+ '-s',
563
+ 'format',
564
+ 'png',
565
+ '-z',
566
+ String(size),
567
+ String(size),
568
+ path.resolve(icon),
569
+ '--out',
570
+ path.join(iconset, `icon_${size}x${size}.png`),
571
+ ],
572
+ { stdio: 'ignore' },
573
+ )
574
+ execFileSync(
575
+ '/usr/bin/sips',
576
+ [
577
+ '-s',
578
+ 'format',
579
+ 'png',
580
+ '-z',
581
+ String(size * 2),
582
+ String(size * 2),
583
+ path.resolve(icon),
584
+ '--out',
585
+ path.join(iconset, `icon_${size}x${size}@2x.png`),
586
+ ],
587
+ { stdio: 'ignore' },
588
+ )
589
+ }
590
+ execFileSync('/usr/bin/iconutil', [
591
+ '-c',
592
+ 'icns',
593
+ iconset,
594
+ '-o',
595
+ path.join(resources, 'Peach.icns'),
596
+ ])
597
+ }
598
+ // each binary keeps the entitlements the host release gave it
599
+ const entitlementsOf = (relative: string) => {
600
+ const file = path.join(scratch, `${relative.replaceAll('/', '-')}.entitlements`)
601
+ fs.writeFileSync(
602
+ file,
603
+ execFileSync('/usr/bin/codesign', [
604
+ '--display',
605
+ '--entitlements',
606
+ '-',
607
+ '--xml',
608
+ path.join(host, 'Contents', relative),
609
+ ]),
610
+ )
611
+ return file
612
+ }
613
+ const appEntitlements = entitlementsOf(`MacOS/${hostExecutable}`)
614
+ if (identity) {
615
+ // the release order of the host's own signing: every nested binary, then
616
+ // nested bundles deepest first, then the entitled binaries and the app
617
+ const sign = (target: string, entitlements?: string) =>
618
+ execFileSync('/usr/bin/codesign', [
619
+ '--force',
620
+ '--sign',
621
+ identity,
622
+ '--options',
623
+ 'runtime',
624
+ '--timestamp',
625
+ ...(entitlements ? ['--entitlements', entitlements] : []),
626
+ target,
627
+ ])
628
+ const files = fs
629
+ .readdirSync(contents, { recursive: true, withFileTypes: true })
630
+ .filter((entry) => entry.isFile())
631
+ .map((entry) => path.join(entry.parentPath, entry.name))
632
+ for (const file of files.sort((a, b) => b.length - a.length)) {
633
+ const head = Buffer.alloc(4)
634
+ const fd = fs.openSync(file, 'r')
635
+ const read = fs.readSync(fd, head, 0, 4, 0)
636
+ fs.closeSync(fd)
637
+ // a thin arm64 or a universal mach-o
638
+ if (read === 4 && [0xcffaedfe, 0xcafebabe].includes(head.readUInt32BE(0)))
639
+ sign(file)
640
+ }
641
+ for (const bundle of fs
642
+ .readdirSync(contents, { recursive: true, withFileTypes: true })
643
+ .filter(
644
+ (entry) => entry.isDirectory() && /\.(app|xpc|framework)$/.test(entry.name),
645
+ )
646
+ .map((entry) => path.join(entry.parentPath, entry.name))
647
+ .sort((a, b) => b.length - a.length))
648
+ sign(bundle)
649
+ sign(path.join(resources, 'bin', 'peach'), entitlementsOf('Resources/bin/peach'))
650
+ sign(path.join(contents, 'Frameworks', 'node'), entitlementsOf('Frameworks/node'))
651
+ // the launcher script is the bundle executable, so the host binary
652
+ // needs its jit entitlements signed on directly
653
+ sign(path.join(contents, 'MacOS', hostExecutable), appEntitlements)
654
+ sign(temporary, appEntitlements)
655
+ } else {
656
+ for (const executable of [
657
+ path.join(contents, 'MacOS', hostExecutable),
658
+ path.join(resources, 'bin', 'peach'),
659
+ ])
660
+ execFileSync('/usr/bin/codesign', [
661
+ '--force',
662
+ '--sign',
663
+ '-',
664
+ '--entitlements',
665
+ appEntitlements,
666
+ executable,
667
+ ])
668
+ execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', temporary])
669
+ }
670
+ execFileSync('/usr/bin/codesign', ['--verify', '--deep', '--strict', temporary])
671
+ const notarize = (file: string) => {
672
+ const result: unknown = JSON.parse(
673
+ execFileSync(
674
+ '/usr/bin/xcrun',
675
+ [
676
+ 'notarytool',
677
+ 'submit',
678
+ file,
679
+ '--keychain-profile',
680
+ notaryProfile!,
681
+ '--wait',
682
+ '--output-format',
683
+ 'json',
684
+ ],
685
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] },
686
+ ),
687
+ )
688
+ if (!isRecord(result) || result.status !== 'Accepted') {
689
+ const id = isRecord(result) && typeof result.id === 'string' ? result.id : ''
690
+ if (id)
691
+ execFileSync(
692
+ '/usr/bin/xcrun',
693
+ ['notarytool', 'log', id, '--keychain-profile', notaryProfile!],
694
+ { stdio: 'inherit' },
695
+ )
696
+ throw new Error(
697
+ `notarization did not accept ${path.basename(file)}: ${JSON.stringify(result)}`,
698
+ )
699
+ }
700
+ }
701
+ const staple = (file: string) =>
702
+ execFileSync('/usr/bin/xcrun', ['stapler', 'staple', file], { stdio: 'ignore' })
703
+ const zip = (destination: string) =>
704
+ execFileSync('/usr/bin/ditto', [
705
+ '-c',
706
+ '-k',
707
+ '--sequesterRsrc',
708
+ '--keepParent',
709
+ temporary,
710
+ destination,
711
+ ])
712
+ if (notaryProfile) {
713
+ const submission = path.join(scratch, 'notarization.zip')
714
+ zip(submission)
715
+ notarize(submission)
716
+ staple(temporary)
717
+ }
718
+ if (archive === '.app') fs.renameSync(temporary, output)
719
+ else if (archive === '.zip') zip(output)
720
+ else {
721
+ // the disk image opens to the app beside an Applications shortcut
722
+ fs.symlinkSync('/Applications', path.join(staging, 'Applications'))
723
+ execFileSync(
724
+ '/usr/bin/hdiutil',
725
+ ['create', '-volname', name, '-srcfolder', staging, '-format', 'UDZO', output],
726
+ { stdio: 'ignore' },
727
+ )
728
+ if (identity)
729
+ execFileSync('/usr/bin/codesign', [
730
+ '--force',
731
+ '--sign',
732
+ identity,
733
+ '--timestamp',
734
+ output,
735
+ ])
736
+ if (notaryProfile) {
737
+ notarize(output)
738
+ staple(output)
739
+ }
740
+ }
741
+ console.log(output)
742
+ if (requiresServer)
743
+ console.error(
744
+ 'This app reconnects to its configured server; keep that server running.',
745
+ )
746
+ } finally {
747
+ fs.rmSync(staging, { recursive: true, force: true })
748
+ fs.rmSync(scratch, { recursive: true, force: true })
749
+ }
750
+ }