peachsim 0.1.1728 → 0.1.1738

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 (172) hide show
  1. package/cli/commands/control.ts +1 -0
  2. package/cli/commands/coverage-swift.ts +112 -4
  3. package/cli/commands/package.ts +11 -1
  4. package/cli/commands/shell-url.ts +4 -0
  5. package/cli/scene-video.ts +24 -7
  6. package/detox/index.ts +9 -1
  7. package/dist-lib/agent-daemon-client.cjs +1 -1
  8. package/dist-lib/agent-events.cjs +1 -1
  9. package/dist-lib/attached-projects.cjs +5 -2
  10. package/dist-lib/auth/shared-session.cjs +5 -2
  11. package/dist-lib/backend-origin.cjs +1 -1
  12. package/dist-lib/beta.cjs +1 -1
  13. package/dist-lib/beta.mjs +1 -1
  14. package/dist-lib/bridge-constants.cjs +1 -1
  15. package/dist-lib/bridge-contract-input.cjs +1 -1
  16. package/dist-lib/bridge-contract-input.mjs +1 -1
  17. package/dist-lib/bridge-contract.cjs +1 -1
  18. package/dist-lib/bridge-contract.mjs +1 -1
  19. package/dist-lib/bundle-channel.cjs +3592 -1918
  20. package/dist-lib/capture-contract.cjs +1 -1
  21. package/dist-lib/capture-contract.mjs +1 -1
  22. package/dist-lib/cloud-contract.cjs +1 -1
  23. package/dist-lib/cloud-contract.mjs +1 -1
  24. package/dist-lib/cloud-test-args.cjs +1 -1
  25. package/dist-lib/cloud-test-args.mjs +1 -1
  26. package/dist-lib/cloud.cjs +1 -1
  27. package/dist-lib/cloud.mjs +1 -1
  28. package/dist-lib/config.cjs +1 -1
  29. package/dist-lib/config.mjs +1 -1
  30. package/dist-lib/detox/index.cjs +13 -5
  31. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  32. package/dist-lib/expo-swift-bundle.cjs +1329 -1022
  33. package/dist-lib/expo-swift-metadata.cjs +2 -2
  34. package/dist-lib/expo-swift-metadata.mjs +2 -2
  35. package/dist-lib/home-paths.cjs +7 -2
  36. package/dist-lib/host/bridge-host.cjs +3773 -2149
  37. package/dist-lib/host/fetch-proxy-handler.cjs +16 -5
  38. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  39. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  40. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  41. package/dist-lib/host/websocket-proxy.cjs +1 -1
  42. package/dist-lib/index.cjs +97 -68
  43. package/dist-lib/jump-to-source-babel.cjs +1 -1
  44. package/dist-lib/jump-to-source-native.cjs +1 -1
  45. package/dist-lib/kotlin-host.cjs +209 -32
  46. package/dist-lib/menu.cjs +7 -1
  47. package/dist-lib/menu.mjs +7 -1
  48. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  49. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  50. package/dist-lib/metro-production-bundle.cjs +1 -1
  51. package/dist-lib/metro-production-bundle.mjs +1 -1
  52. package/dist-lib/metro.cjs +93 -65
  53. package/dist-lib/native-app-identity-project.cjs +37 -31
  54. package/dist-lib/native-app-identity-project.mjs +37 -31
  55. package/dist-lib/native-app-identity.cjs +1 -1
  56. package/dist-lib/native-app-identity.mjs +1 -1
  57. package/dist-lib/native-firebase-metadata.cjs +1 -1
  58. package/dist-lib/native-firebase-metadata.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +5 -2
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/public-origins-lib-esm.json +23 -23
  64. package/dist-lib/public-origins-lib.json +79 -53
  65. package/dist-lib/react-native-host-modules.cjs +5 -2
  66. package/dist-lib/react-native-host-modules.mjs +5 -2
  67. package/dist-lib/reap-browser.cjs +1 -1
  68. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  69. package/dist-lib/sdk.cjs +1 -1
  70. package/dist-lib/sdk.mjs +1 -1
  71. package/dist-lib/skills.cjs +4486 -2789
  72. package/dist-lib/swift-compile.cjs +53 -60
  73. package/dist-lib/swift-compile.mjs +52 -60
  74. package/dist-lib/swift-package.cjs +1 -1
  75. package/dist-lib/swift-package.mjs +1 -1
  76. package/dist-lib/swift-submit.cjs +2 -2
  77. package/dist-lib/swift-submit.mjs +2 -2
  78. package/dist-lib/swift-toolchain.cjs +17 -17
  79. package/dist-lib/swift.cjs +1 -1
  80. package/dist-lib/vite-swift.cjs +1056 -870
  81. package/dist-lib/vite.cjs +20 -8
  82. package/dist-lib/worklet-executable.cjs +1 -1
  83. package/dist-lib/worklet-executable.mjs +1 -1
  84. package/dist-types/packages/peach-engine/src/engine/font-config.d.ts +7 -4
  85. package/dist-types/packages/peach-engine/src/engine/image-loader.d.ts +2 -1
  86. package/dist-types/packages/peach-engine/src/engine/liquid-glass.d.ts +0 -5
  87. package/dist-types/packages/peach-engine/src/engine/memory-counts.d.ts +8 -0
  88. package/dist-types/packages/peach-engine/src/engine/node.d.ts +4 -1
  89. package/dist-types/packages/peach-engine/src/engine/render-damage.d.ts +2 -2
  90. package/dist-types/packages/peach-engine/src/engine/text-first-baseline.d.ts +5 -0
  91. package/dist-types/packages/peach-engine/src/engine/text-paragraph.d.ts +1 -0
  92. package/dist-types/packages/peach-engine/src/native-preview-bundle.d.ts +2 -0
  93. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +7 -2
  94. package/dist-types/packages/peach-engine/src/render-worker/shell-protocol.d.ts +1 -0
  95. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +13 -1
  96. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  97. package/kotlin/README.md +3 -0
  98. package/kotlin/sdk.tar.gz +0 -0
  99. package/package.json +1 -1
  100. package/runtime-companion.json +1 -1
  101. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/ACAccount.h +55 -0
  102. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/ACAccountCredential.h +35 -0
  103. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/ACAccountStore.h +94 -0
  104. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/ACAccountType.h +53 -0
  105. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/ACError.h +37 -0
  106. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/Accounts.h +13 -0
  107. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Headers/AccountsDefines.h +13 -0
  108. package/sdk/ios/System/Library/Frameworks/Accounts.framework/Modules/module.modulemap +5 -0
  109. package/sdk/ios/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.h +1 -1
  110. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes +58 -3
  111. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h +636 -37
  112. package/sdk/ios/usr/include/os/signpost.h +414 -0
  113. package/sdk/ios/usr/include/os.modulemap +5 -0
  114. package/sdk/ios/wasm/include/errno.h +4 -20
  115. package/sdk/ios/wasm/include/pthread.h +3 -0
  116. package/sdk/ios/wasm/include/setjmp.h +57 -0
  117. package/sdk/ios/wasm/include/sys/resource.h +2 -2
  118. package/sdk/native-hashes.json +3 -3
  119. package/skills/peach-debug/SKILL.md +0 -1
  120. package/skills/peach-perf/SKILL.md +0 -1
  121. package/skills/peach-setup/SKILL.md +0 -1
  122. package/skills/peach-test/SKILL.md +0 -1
  123. package/skills/peach-visual/SKILL.md +0 -1
  124. package/src/android-autolinking.ts +1 -0
  125. package/src/android-bridge-packages.ts +279 -0
  126. package/src/appPackageContract.ts +2 -0
  127. package/src/bundle-channel.mjs +20 -2
  128. package/src/cli-runtime.ts +9 -5
  129. package/src/expo-discovery-cache.ts +7 -3
  130. package/src/expo-kotlin-host.ts +97 -26
  131. package/src/expo-native-workspace.ts +135 -40
  132. package/src/expo-swift-host.ts +93 -20
  133. package/src/expo-swift-ready.ts +5 -1
  134. package/src/expoKotlinContract.ts +12 -2
  135. package/src/expoSwiftContract.ts +9 -2
  136. package/src/generated/swift-c-predefines.json +1 -1
  137. package/src/home-paths.ts +6 -1
  138. package/src/host/bridge-host.ts +5 -0
  139. package/src/host/fetch-proxy-handler.ts +10 -0
  140. package/src/kotlin-host.ts +204 -30
  141. package/src/kotlinSdkContract.ts +2 -1
  142. package/src/menu.ts +7 -0
  143. package/src/native-prebuilt.ts +154 -0
  144. package/src/nitro-adapter.lock.json +251 -251
  145. package/src/nitro-adapter.ts +56 -50
  146. package/src/nitro-bundle.ts +84 -74
  147. package/src/nitro-compile.ts +10 -5
  148. package/src/nitro-dependencies.ts +43 -28
  149. package/src/nitro-source.ts +60 -26
  150. package/src/nitroAdapterContract.ts +146 -98
  151. package/src/nitroContract.ts +64 -21
  152. package/src/react-native-bridge-modules.ts +2 -0
  153. package/src/react-native-host-modules.ts +4 -1
  154. package/src/settingsContract.ts +11 -0
  155. package/src/storageSnapshotContract.ts +29 -81
  156. package/src/swift-compile.ts +49 -50
  157. package/src/swift-coverage/indexdump.ts +22 -6
  158. package/src/swift-coverage/indexing.ts +4 -4
  159. package/src/swift-coverage/sdk.ts +104 -20
  160. package/src/swift-coverage/types.ts +34 -0
  161. package/src/swift-coverage/xcode.ts +9 -1
  162. package/src/swift-distribution.lock.json +15 -12
  163. package/src/swift-host.ts +3 -0
  164. package/src/swift-standin-emit.ts +6 -1
  165. package/src/swift-standins.ts +172 -10
  166. package/src/swift-submit.ts +5 -1
  167. package/src/swift-toolchain.ts +16 -16
  168. package/src/turbo-bundle.ts +81 -0
  169. package/src/turbo-compile.ts +120 -0
  170. package/src/turbo-runtime.lock.json +69 -0
  171. package/src/turbo-source.ts +754 -0
  172. package/src/vite-plugin-one.ts +4 -3
@@ -0,0 +1,754 @@
1
+ // the original native source of an app's C++ TurboModules, collected as
2
+ // CocoaPods builds it for iOS: every autolinked pod whose sources register a
3
+ // module into React Native's global C++ module map
4
+ // (registerCxxModuleToGlobalModuleMap) compiles from its podspec's own
5
+ // source_files, beside React Native's TurboModule core from the app's installed
6
+ // react-native. a pod that registers from an Objective-C +load has that body
7
+ // transcribed to the same C++ call, run before the runtime installs its
8
+ // binding, as +load runs before the app starts. codegen's Objective-C spec
9
+ // classes are left out: React Native never reaches them for a C++ module.
10
+ import { createHash } from 'node:crypto'
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { nitroDependencyReader, prepareNitroDependencies } from './nitro-dependencies'
14
+ import { iosAutolinkedDependencies } from './nitro-source'
15
+ import { TURBO_RUNTIME_HEADER } from './nitroAdapterContract'
16
+ import { readPackageFile } from './swift-source-file'
17
+ import { MAX_SWIFT_COMPILE_SOURCE_BYTES } from './swift-submit'
18
+ import { runInstalledTurboCodegen } from './turbo-codegen-intake'
19
+ import type { SwiftCompileInput } from './swift-compile'
20
+ import type { SwiftPackageTarget } from './swift-package'
21
+
22
+ type TurboPackage = { name: string; version: string; root: string }
23
+
24
+ export interface TurboProvider {
25
+ /** the autolinked package name. */
26
+ name: string
27
+ root: string
28
+ podspecPath: string
29
+ }
30
+
31
+ /** source fragments for the common Swift host. the caller owns the executable,
32
+ * which runs every `loads` symbol and then `peachTurboInitialize`. */
33
+ export interface TurboSourceCollection {
34
+ files: SwiftCompileInput['files']
35
+ targets: SwiftPackageTarget[]
36
+ /** each transcribed +load, sorted by package; `target` declares it. */
37
+ loads: { symbol: string; target: string }[]
38
+ providers: TurboPackage[]
39
+ reactNative: TurboPackage
40
+ sources: {
41
+ file: string
42
+ source: string
43
+ sha256: string
44
+ derivation?: { upstreamCommit: string; originalSha256: string }
45
+ }[]
46
+ }
47
+
48
+ export const TURBO_CORE_TARGET = 'TurboCore'
49
+ export const TURBO_ENTRY_HEADER = 'PeachTurboEntry.hpp'
50
+
51
+ const REGISTRATION = 'registerCxxModuleToGlobalModuleMap'
52
+ const CODEGEN_OBJC = /@generated by codegen project: GenerateModuleObjCpp\b/
53
+ const UNIT = /\.(?:c|cc|cpp|cxx)$/
54
+ const HEADER = /\.(?:h|hh|hpp|hxx|inl|ipp)$/
55
+ const OBJC = /\.(?:m|mm)$/
56
+
57
+ // the TurboModule core every module pod links (ReactCommon/turbomodule/core
58
+ // and the pods it depends on), and the header search roots CocoaPods exposes
59
+ // for them: jsi, ReactCommon's header_dir, callinvoker, perflogger.
60
+ const REACT_NATIVE_UNITS = [
61
+ 'ReactCommon/jsi/jsi/jsi.cpp',
62
+ 'ReactCommon/react/nativemodule/core/ReactCommon/**/*.cpp',
63
+ 'ReactCommon/react/bridging/*.cpp',
64
+ 'ReactCommon/react/debug/react_native_assert.cpp',
65
+ 'ReactCommon/react/utils/jsi-utils.cpp',
66
+ ]
67
+ const REACT_NATIVE_INCLUDE_ROOTS = [
68
+ 'ReactCommon/jsi',
69
+ 'ReactCommon',
70
+ 'ReactCommon/callinvoker',
71
+ 'ReactCommon/react/nativemodule/core',
72
+ 'ReactCommon/reactperflogger',
73
+ ]
74
+
75
+ function object(value: unknown): value is Record<string, unknown> {
76
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
77
+ }
78
+
79
+ function packageInfo(root: string): TurboPackage {
80
+ root = fs.realpathSync(root)
81
+ const value: unknown = JSON.parse(
82
+ fs.readFileSync(path.join(root, 'package.json'), 'utf8'),
83
+ )
84
+ if (
85
+ !object(value) ||
86
+ typeof value.name !== 'string' ||
87
+ typeof value.version !== 'string'
88
+ )
89
+ throw new Error(`${root}: package.json needs a name and version`)
90
+ return { name: value.name, version: value.version, root }
91
+ }
92
+
93
+ const sha256 = (data: string | Uint8Array) =>
94
+ createHash('sha256').update(data).digest('hex')
95
+
96
+ // a CocoaPods file glob (Dir.glob with braces) as a regular expression over
97
+ // pod-relative posix paths
98
+ function globRegex(glob: string): RegExp {
99
+ let out = ''
100
+ let depth = 0
101
+ for (let index = 0; index < glob.length; index++) {
102
+ const char = glob[index]!
103
+ if (glob.startsWith('**/', index)) {
104
+ out += '(?:[^/]+/)*'
105
+ index += 2
106
+ } else if (char === '*') out += '[^/]*'
107
+ else if (char === '?') out += '[^/]'
108
+ else if (char === '{') {
109
+ depth++
110
+ out += '(?:'
111
+ } else if (char === '}' && depth > 0) {
112
+ depth--
113
+ out += ')'
114
+ } else if (char === ',' && depth > 0) out += '|'
115
+ else out += char.replace(/[.+^$()|[\]\\]/g, '\\$&')
116
+ }
117
+ return new RegExp(`^${out}$`)
118
+ }
119
+
120
+ // the directory a glob's literal prefix names, so a walk reads only it
121
+ function globBase(glob: string): string {
122
+ const literal = glob.split('/')
123
+ const index = literal.findIndex((part) => /[*?{]/.test(part))
124
+ return literal.slice(0, index === -1 ? literal.length - 1 : index).join('/')
125
+ }
126
+
127
+ function walkFiles(root: string, base: string, into: Set<string>): void {
128
+ const disk = path.join(root, base)
129
+ if (!fs.existsSync(disk) || !fs.statSync(disk).isDirectory()) return
130
+ for (const entry of fs.readdirSync(disk, { withFileTypes: true })) {
131
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
132
+ const relative = base ? `${base}/${entry.name}` : entry.name
133
+ if (entry.isDirectory()) walkFiles(root, relative, into)
134
+ else if (entry.isFile()) into.add(relative)
135
+ }
136
+ }
137
+
138
+ /** a podspec attribute assigned a list of string literals, null when the
139
+ * podspec does not assign it, or 'computed' for a value only CocoaPods
140
+ * evaluating the Ruby could answer. */
141
+ function podspecList(text: string, attribute: string): string[] | 'computed' | null {
142
+ const assignments = [
143
+ ...text.matchAll(new RegExp(`^\\s*\\w+\\.${attribute}\\s*=\\s*`, 'gm')),
144
+ ]
145
+ if (assignments.length === 0) return null
146
+ if (assignments.length > 1) return 'computed'
147
+ const rest = text.slice(assignments[0]!.index + assignments[0]![0].length)
148
+ const value = (
149
+ rest.startsWith('[') ? rest.slice(1, rest.indexOf(']')) : (rest.split('\n')[0] ?? '')
150
+ ).trim()
151
+ const items: string[] = []
152
+ const pattern = /("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*(?:,\s*|$)/y
153
+ for (let at = 0; at < value.length; at = pattern.lastIndex) {
154
+ pattern.lastIndex = at
155
+ const match = pattern.exec(value)
156
+ if (!match) return 'computed'
157
+ const literal = match[1]!
158
+ if (literal.startsWith('"') && literal.includes('#{')) return 'computed'
159
+ items.push(literal.slice(1, -1))
160
+ }
161
+ return items
162
+ }
163
+
164
+ type Pod = { root: string; directory: string; text: string; name: string }
165
+
166
+ function readPod(provider: TurboProvider): Pod {
167
+ const root = fs.realpathSync(provider.root)
168
+ const podspec = fs.realpathSync(provider.podspecPath)
169
+ return {
170
+ root,
171
+ // CocoaPods resolves every glob against the podspec's own directory
172
+ directory: path.relative(root, path.dirname(podspec)).split(path.sep).join('/'),
173
+ text: readPackageFile(root, podspec, MAX_SWIFT_COMPILE_SOURCE_BYTES).toString('utf8'),
174
+ name: path.basename(podspec, '.podspec'),
175
+ }
176
+ }
177
+
178
+ // the package-relative files a podspec's literal globs select
179
+ function podGlobFiles(pod: Pod): string[] | 'computed' | null {
180
+ const sources = podspecList(pod.text, 'source_files')
181
+ const excludes = podspecList(pod.text, 'exclude_files') ?? []
182
+ if (sources === 'computed' || excludes === 'computed') return 'computed'
183
+ if (!sources) return null
184
+ const prefix = pod.directory ? `${pod.directory}/` : ''
185
+ const candidates = new Set<string>()
186
+ for (const glob of sources) walkFiles(pod.root, prefix + globBase(glob), candidates)
187
+ const included = sources.map(globRegex)
188
+ const excluded = excludes.map(globRegex)
189
+ return [...candidates]
190
+ .filter((file) => {
191
+ const relative = file.slice(prefix.length)
192
+ return (
193
+ included.some((glob) => glob.test(relative)) &&
194
+ !excluded.some((glob) => glob.test(relative))
195
+ )
196
+ })
197
+ .sort()
198
+ }
199
+
200
+ // the files a provider's podspec compiles, refused when the pod ships binaries
201
+ // or subspecs this reading cannot follow
202
+ function podFiles(pod: Pod): string[] {
203
+ const file = `${pod.name}.podspec`
204
+ if (/^\s*\w+\.subspec\b/m.test(pod.text))
205
+ throw new Error(`${file}: TurboModule pods with subspecs are not supported yet`)
206
+ for (const binary of ['vendored_frameworks', 'vendored_libraries'])
207
+ if (new RegExp(`\\.${binary}\\s*=`).test(pod.text))
208
+ throw new Error(
209
+ `${file}: the pod links prebuilt ${binary}, which only its own wasm build can replace`,
210
+ )
211
+ const files = podGlobFiles(pod)
212
+ if (files === 'computed')
213
+ throw new Error(
214
+ `${file}: source_files is computed by Ruby, which only CocoaPods can evaluate`,
215
+ )
216
+ if (!files?.length) throw new Error(`${file}: no source_files`)
217
+ return files
218
+ }
219
+
220
+ function stripComments(text: string): string {
221
+ return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')
222
+ }
223
+
224
+ /** the C++ an Objective-C file runs, when the file is only a class whose
225
+ * +load registers C++ TurboModules: its includes, using-directives and the
226
+ * +load body. any other Objective-C needs the Objective-C runtime. */
227
+ function transcribeLoad(text: string, file: string) {
228
+ const code = stripComments(text)
229
+ const refuse = (why: string) =>
230
+ new Error(
231
+ `${file}: ${why}; Objective-C TurboModule sources need the Objective-C runtime`,
232
+ )
233
+ const implementations = [...code.matchAll(/@implementation\s+(\w+)\s*([\s\S]*?)@end/g)]
234
+ if (implementations.length !== 1) throw refuse('expected one @implementation')
235
+ const [whole, className, inside] = implementations[0]!
236
+ const outside = code
237
+ .replace(whole, '')
238
+ .replace(new RegExp(`@interface\\s+${className}\\s*:\\s*NSObject\\s*@end`), '')
239
+ const includes: string[] = []
240
+ const usings: string[] = []
241
+ for (const line of outside.split('\n').map((value) => value.trim())) {
242
+ if (!line) continue
243
+ const include = /^#\s*(?:import|include)\s*([<"][^>"]+[>"])$/.exec(line)
244
+ const using = /^using namespace [\w:]+;$/.exec(line)
245
+ if (include) {
246
+ // the Objective-C frameworks the class itself needs, not its +load body
247
+ if (!/^<(?:Foundation|UIKit)\//.test(include[1]!)) includes.push(include[1]!)
248
+ } else if (using) usings.push(using[0])
249
+ else throw refuse(`unsupported top-level code \`${line}\``)
250
+ }
251
+ const load = /\+\s*\(\s*void\s*\)\s*load\s*\{/.exec(inside!)
252
+ if (!load) throw refuse('no +load')
253
+ let depth = 1
254
+ let end = load.index + load[0].length
255
+ for (; end < inside!.length && depth > 0; end++) {
256
+ if (inside![end] === '{') depth++
257
+ else if (inside![end] === '}') depth--
258
+ }
259
+ if (depth !== 0) throw refuse('unbalanced +load')
260
+ const body = inside!.slice(load.index + load[0].length, end - 1)
261
+ for (const line of (inside!.slice(0, load.index) + inside!.slice(end))
262
+ .split('\n')
263
+ .map((value) => value.trim())) {
264
+ if (!line) continue
265
+ if (/^using namespace [\w:]+;$/.test(line)) usings.push(line)
266
+ else throw refuse(`unsupported member \`${line}\``)
267
+ }
268
+ if (!body.includes(REGISTRATION)) throw refuse(`+load does not call ${REGISTRATION}`)
269
+ if (body.includes('@') || /\[\s*[A-Za-z_]\w*\s+[A-Za-z_]\w*\s*[\]:]/.test(body))
270
+ throw refuse('+load sends Objective-C messages')
271
+ return { includes, usings, body }
272
+ }
273
+
274
+ function registers(root: string, files: Iterable<string>): boolean {
275
+ for (const file of files)
276
+ if (
277
+ (UNIT.test(file) || OBJC.test(file)) &&
278
+ fs.readFileSync(path.join(root, file), 'utf8').includes(REGISTRATION)
279
+ )
280
+ return true
281
+ return false
282
+ }
283
+
284
+ /** the autolinked iOS pods whose own sources register a C++ TurboModule. a
285
+ * pod whose sources are computed is read whole, so a provider among them is
286
+ * refused by name instead of left out. */
287
+ export async function discoverTurboProviders(appRoot: string): Promise<TurboProvider[]> {
288
+ const providers: TurboProvider[] = []
289
+ for (const { name, root, podspecPath } of await iosAutolinkedDependencies(appRoot)) {
290
+ if (!podspecPath) continue
291
+ const provider = { name, root, podspecPath }
292
+ const pod = readPod(provider)
293
+ const files = podGlobFiles(pod)
294
+ if (files === null) continue
295
+ if (files !== 'computed') {
296
+ if (registers(pod.root, files)) providers.push(provider)
297
+ continue
298
+ }
299
+ const tree = new Set<string>()
300
+ walkFiles(pod.root, pod.directory, tree)
301
+ if (registers(pod.root, tree)) podFiles(pod)
302
+ }
303
+ return providers
304
+ }
305
+
306
+ function readFollyConfig(reactNativeRoot: string) {
307
+ const helpers = fs.readFileSync(
308
+ path.join(reactNativeRoot, 'scripts/cocoapods/helpers.rb'),
309
+ 'utf8',
310
+ )
311
+ const config = /@@folly_config\s*=\s*\{([\s\S]*?)\n\s*\}/.exec(helpers)?.[1]
312
+ const flags = config && /:compiler_flags\s*=>\s*'([^']*)'/.exec(config)?.[1]
313
+ const lines = config && /:config_file\s*=>\s*\[([\s\S]*?)\]/.exec(config)?.[1]
314
+ if (!flags || !lines)
315
+ throw new Error(`${reactNativeRoot}: helpers.rb has no folly config`)
316
+ const header = [...lines.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)]
317
+ .map((match) => match[1] ?? match[2] ?? '')
318
+ .join('\n')
319
+ const defines = [...flags.matchAll(/-D(\w+(?:=\S+)?)/g)].map((match) => match[1]!)
320
+ return { header: `${header}\n`, defines }
321
+ }
322
+
323
+ /** fetch the installed RN release's pinned C++ dependencies before collection. */
324
+ export function prepareTurboSourceDependencies(reactNativeRoot: string): Promise<void> {
325
+ return prepareNitroDependencies(packageInfo(reactNativeRoot).version)
326
+ }
327
+
328
+ /** collect each provider's podspec sources, its codegen output and React
329
+ * Native's TurboModule core, without reading or rewriting package JavaScript.
330
+ * `codegenDir` is scratch for the app's own codegen run, used only when a
331
+ * provider ships no generated code. */
332
+ export async function collectTurboSources(options: {
333
+ appRoot: string
334
+ reactNativeRoot: string
335
+ providers: TurboProvider[]
336
+ codegenDir: string
337
+ }): Promise<TurboSourceCollection> {
338
+ if (options.providers.length === 0)
339
+ throw new Error('TurboModule compilation needs at least one provider')
340
+ const reactNative = packageInfo(options.reactNativeRoot)
341
+ if (reactNative.name !== 'react-native')
342
+ throw new Error(`${options.reactNativeRoot} is not react-native`)
343
+ const providers = options.providers
344
+ .map((provider) => ({ ...provider, info: packageInfo(provider.root) }))
345
+ .sort((a, b) => a.info.name.localeCompare(b.info.name))
346
+ const targetPath = (name: string) => `Sources/${name}`
347
+ const providerTarget = (name: string) => `TurboPackage_${sha256(name).slice(0, 16)}`
348
+ const folly = readFollyConfig(reactNative.root)
349
+ // the compile builds for production, as an app's Release configuration does.
350
+ // Debug also compiles React Native's asserts, which need the glog headers
351
+ // its pod generates at install.
352
+ const defines = ['NDEBUG', 'RCT_NEW_ARCH_ENABLED=1', ...folly.defines]
353
+ const target = (name: string, dependencies: string[]) => ({
354
+ name,
355
+ path: targetPath(name),
356
+ executable: false,
357
+ languageMode: 5,
358
+ mainActorIsolation: false,
359
+ resources: false,
360
+ dependencies: dependencies.map((dependency) => ({
361
+ kind: 'target' as const,
362
+ name: dependency,
363
+ })),
364
+ cxxDefines: defines,
365
+ })
366
+ const result: TurboSourceCollection = {
367
+ files: {},
368
+ targets: [target(TURBO_CORE_TARGET, [])],
369
+ loads: [],
370
+ providers: providers.map(({ info }) => info),
371
+ reactNative,
372
+ sources: [],
373
+ }
374
+ const add = (file: string, text: string) => {
375
+ if (Object.hasOwn(result.files, file)) {
376
+ if (result.files[file] !== text)
377
+ throw new Error(`ambiguous TurboModule source include: ${file}`)
378
+ return false
379
+ }
380
+ result.files[file] = text
381
+ return true
382
+ }
383
+ const alias = (file: string, original: string) => {
384
+ if (file !== original)
385
+ add(
386
+ file,
387
+ `#include ${JSON.stringify(path.posix.relative(path.posix.dirname(file), original))}\n`,
388
+ )
389
+ }
390
+ // an original file under a target, by its root-relative path. returns the
391
+ // compile key; reading it again is free.
392
+ const original = (
393
+ targetName: string,
394
+ label: string,
395
+ root: string,
396
+ relative: string,
397
+ ) => {
398
+ const key = `${targetPath(targetName)}/upstream/${label}/${relative}`
399
+ if (Object.hasOwn(result.files, key)) return key
400
+ const disk = path.join(root, relative)
401
+ const bytes = readPackageFile(root, disk, Infinity)
402
+ const text = bytes.toString('utf8')
403
+ if (!Buffer.from(text).equals(bytes))
404
+ throw new Error(`TurboModule source is not UTF-8: ${disk}`)
405
+ add(key, text)
406
+ result.sources.push({ file: key, source: disk, sha256: sha256(bytes) })
407
+ pending.push({ key, targetName, label, root, relative })
408
+ return key
409
+ }
410
+ type Scan = {
411
+ key: string
412
+ targetName: string
413
+ label: string
414
+ root: string
415
+ relative: string
416
+ }
417
+ const pending: Scan[] = []
418
+ const dependencyHeader = nitroDependencyReader(reactNative.version)
419
+ const core = targetPath(TURBO_CORE_TARGET)
420
+ // each provider's headers by the names its search paths give them, collected
421
+ // only once a compiled file includes one
422
+ const podHeaders = new Map<
423
+ string,
424
+ Map<string, { label: string; root: string; relative: string }>
425
+ >()
426
+ // an include a file names, resolved as clang would against the pod's own
427
+ // directory, then the search paths CocoaPods gives a module pod. unresolved
428
+ // names are the SDK's own headers.
429
+ const resolve = (from: Scan, include: string, quoted: boolean) => {
430
+ if (quoted) {
431
+ const relative = path.posix.normalize(
432
+ path.posix.join(path.posix.dirname(from.relative), include),
433
+ )
434
+ if (!relative.startsWith('../') && fs.existsSync(path.join(from.root, relative))) {
435
+ original(from.targetName, from.label, from.root, relative)
436
+ return
437
+ }
438
+ }
439
+ const own = `${targetPath(from.targetName)}/include/${include}`
440
+ if (Object.hasOwn(result.files, own)) return
441
+ const podHeader = podHeaders.get(from.targetName)?.get(include)
442
+ if (podHeader) {
443
+ alias(
444
+ own,
445
+ original(from.targetName, podHeader.label, podHeader.root, podHeader.relative),
446
+ )
447
+ return
448
+ }
449
+ if (Object.hasOwn(result.files, `${core}/include/${include}`)) return
450
+ if (include === 'folly/folly-config.h') {
451
+ add(`${core}/include/${include}`, folly.header)
452
+ return
453
+ }
454
+ for (const base of REACT_NATIVE_INCLUDE_ROOTS) {
455
+ const relative = `${base}/${include}`
456
+ if (!fs.existsSync(path.join(reactNative.root, relative))) continue
457
+ alias(
458
+ `${core}/include/${include}`,
459
+ original(TURBO_CORE_TARGET, 'react-native', reactNative.root, relative),
460
+ )
461
+ return
462
+ }
463
+ const header = dependencyHeader(include)
464
+ if (!header) return
465
+ const key = `${core}/dependencies/${header.name}/${header.relative}`
466
+ if (add(key, header.text)) {
467
+ result.sources.push({
468
+ file: key,
469
+ source: header.source,
470
+ sha256: header.sha256,
471
+ ...(header.derivation && { derivation: header.derivation }),
472
+ })
473
+ scanText(
474
+ { key, targetName: TURBO_CORE_TARGET, label: '', root: '', relative: include },
475
+ header.text,
476
+ true,
477
+ )
478
+ }
479
+ alias(`${core}/include/${include}`, key)
480
+ }
481
+ const scanText = (from: Scan, text: string, dependency = false) => {
482
+ for (const [, quote, name] of stripComments(text).matchAll(
483
+ /^\s*#\s*(?:include|import)\s*([<"])([^>"\n]+)[>"]/gm,
484
+ ))
485
+ if (!dependency) resolve(from, name!, quote === '"')
486
+ // a quoted include names its own header's directory first
487
+ else if (
488
+ quote !== '"' ||
489
+ !resolveDependency(
490
+ path.posix.normalize(path.posix.join(path.posix.dirname(from.relative), name!)),
491
+ )
492
+ )
493
+ resolveDependency(name!)
494
+ }
495
+ // a third-party header's includes stay inside the third-party archives
496
+ const resolveDependency = (include: string): boolean => {
497
+ if (Object.hasOwn(result.files, `${core}/include/${include}`)) return true
498
+ if (include === 'folly/folly-config.h') {
499
+ add(`${core}/include/${include}`, folly.header)
500
+ return true
501
+ }
502
+ const header = dependencyHeader(include)
503
+ if (!header) return false
504
+ const key = `${core}/dependencies/${header.name}/${header.relative}`
505
+ alias(`${core}/include/${include}`, key)
506
+ if (add(key, header.text)) {
507
+ result.sources.push({
508
+ file: key,
509
+ source: header.source,
510
+ sha256: header.sha256,
511
+ ...(header.derivation && { derivation: header.derivation }),
512
+ })
513
+ scanText(
514
+ { key, targetName: TURBO_CORE_TARGET, label: '', root: '', relative: include },
515
+ header.text,
516
+ true,
517
+ )
518
+ }
519
+ return true
520
+ }
521
+
522
+ // react native's core units
523
+ const units = new Set<string>()
524
+ for (const glob of REACT_NATIVE_UNITS) {
525
+ const candidates = new Set<string>()
526
+ walkFiles(reactNative.root, globBase(glob), candidates)
527
+ const matched = [...candidates].filter((file) => globRegex(glob).test(file)).sort()
528
+ if (matched.length === 0)
529
+ throw new Error(`react-native ${reactNative.version} has no ${glob}`)
530
+ for (const file of matched) units.add(file)
531
+ }
532
+ for (const unit of units)
533
+ original(TURBO_CORE_TARGET, 'react-native', reactNative.root, unit)
534
+
535
+ // the host: the binding installed on the process's JSI runtime, answered
536
+ // from the global C++ module map as RCTTurboModuleManager answers a C++
537
+ // module. React Native 0.84 passes the runtime to the provider.
538
+ const binding = fs.readFileSync(
539
+ path.join(
540
+ reactNative.root,
541
+ 'ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h',
542
+ ),
543
+ 'utf8',
544
+ )
545
+ const withRuntime = binding.includes('TurboModuleProviderFunctionTypeWithRuntime')
546
+ add(`${core}/include/PeachJsiRuntime.hpp`, TURBO_RUNTIME_HEADER)
547
+ add(
548
+ `${core}/include/${TURBO_ENTRY_HEADER}`,
549
+ '#pragma once\nextern "C" void peachTurboInitialize();\n',
550
+ )
551
+ add(
552
+ `${core}/include/module.modulemap`,
553
+ `module ${TURBO_CORE_TARGET} { header "${TURBO_ENTRY_HEADER}" export * }\n`,
554
+ )
555
+ const host = `${core}/PeachTurboHost.cpp`
556
+ add(host, turboHostSource(withRuntime))
557
+ scanText(
558
+ {
559
+ key: host,
560
+ targetName: TURBO_CORE_TARGET,
561
+ label: '',
562
+ root: core,
563
+ relative: 'PeachTurboHost.cpp',
564
+ },
565
+ result.files[host]!,
566
+ )
567
+
568
+ // generated code a provider does not ship comes from the app's own codegen,
569
+ // the ReactCodegen pod pod install builds
570
+ let codegen: string | null = null
571
+ for (const provider of providers) {
572
+ const targetName = providerTarget(provider.info.name)
573
+ const label = provider.info.name
574
+ const root = provider.info.root
575
+ result.targets.push(target(targetName, [TURBO_CORE_TARGET]))
576
+ const pod = readPod(provider)
577
+ const files = podFiles(pod)
578
+ const headers = new Map<string, { label: string; root: string; relative: string }>()
579
+ podHeaders.set(targetName, headers)
580
+ // CocoaPods flattens a pod's headers: `Name.h` and `<pod>/Name.h`
581
+ const header = (
582
+ names: string[],
583
+ entry: { label: string; root: string; relative: string },
584
+ ) => {
585
+ for (const name of names) {
586
+ const prior = headers.get(name)
587
+ if (prior && prior.relative !== entry.relative)
588
+ throw new Error(`${label}: two pod headers are named ${name}`)
589
+ headers.set(name, entry)
590
+ }
591
+ }
592
+ const sources: string[] = []
593
+ const loads: { file: string; load: ReturnType<typeof transcribeLoad> }[] = []
594
+ for (const file of files) {
595
+ if (HEADER.test(file)) {
596
+ const base = path.posix.basename(file)
597
+ header([base, `${pod.name}/${base}`], { label, root, relative: file })
598
+ } else if (UNIT.test(file)) sources.push(file)
599
+ else if (OBJC.test(file)) {
600
+ const text = fs.readFileSync(path.join(root, file), 'utf8')
601
+ if (CODEGEN_OBJC.test(text)) continue
602
+ loads.push({ file, load: transcribeLoad(text, `${label}/${file}`) })
603
+ } else if (file.endsWith('.swift'))
604
+ throw new Error(
605
+ `${label}/${file}: Swift TurboModule sources are not supported yet`,
606
+ )
607
+ }
608
+ if (loads.length === 0 && !registers(root, files))
609
+ throw new Error(`${label}: its pod sources register no C++ TurboModule`)
610
+ const manifest: unknown = JSON.parse(
611
+ fs.readFileSync(path.join(root, 'package.json'), 'utf8'),
612
+ )
613
+ const codegenConfig =
614
+ object(manifest) && object(manifest.codegenConfig) ? manifest.codegenConfig : null
615
+ if (codegenConfig && codegenConfig.includesGeneratedCode !== true) {
616
+ if (typeof codegenConfig.name !== 'string')
617
+ throw new Error(`${label}: codegenConfig has no name`)
618
+ codegen ??= (await runInstalledTurboCodegen(options.appRoot, options.codegenDir))
619
+ .generatedRoot
620
+ const generated = path.join(codegen, 'ReactCodegen')
621
+ const owned = new Set<string>()
622
+ walkFiles(generated, '', owned)
623
+ const spec = codegenConfig.name
624
+ for (const file of [...owned].sort()) {
625
+ const base = path.posix.basename(file)
626
+ if (!base.startsWith(`${spec}JSI`)) continue
627
+ if (HEADER.test(base))
628
+ header([base, `${pod.name}/${base}`, `ReactCodegen/${base}`], {
629
+ label: 'ReactCodegen',
630
+ root: generated,
631
+ relative: file,
632
+ })
633
+ else original(targetName, 'ReactCodegen', generated, file)
634
+ }
635
+ }
636
+ for (const file of sources) original(targetName, label, root, file)
637
+ const declared: string[] = []
638
+ for (const [count, { file, load }] of loads.entries()) {
639
+ const symbol = `peach_turbo_load_${targetName}_${count}`
640
+ declared.push(symbol)
641
+ result.loads.push({ symbol, target: targetName })
642
+ const unit = `${targetPath(targetName)}/PeachTurboLoad${count}.cpp`
643
+ add(
644
+ unit,
645
+ [
646
+ `// the +load of ${file}, run before the runtime installs its binding`,
647
+ ...load.includes.map((include) => `#include ${include}`),
648
+ ...load.usings,
649
+ `extern "C" void ${symbol}() {${load.body}}`,
650
+ '',
651
+ ].join('\n'),
652
+ )
653
+ scanText(
654
+ { key: unit, targetName, label, root, relative: file },
655
+ result.files[unit]!,
656
+ )
657
+ }
658
+ add(
659
+ `${targetPath(targetName)}/include/PeachTurboLoad.hpp`,
660
+ `#pragma once\n${declared.map((symbol) => `extern "C" void ${symbol}();\n`).join('')}`,
661
+ )
662
+ add(
663
+ `${targetPath(targetName)}/include/module.modulemap`,
664
+ `module ${targetName} { header "PeachTurboLoad.hpp" export * }\n`,
665
+ )
666
+ }
667
+
668
+ // every collected file's includes, transitively
669
+ for (let next = pending.shift(); next; next = pending.shift())
670
+ scanText(next, result.files[next.key]!)
671
+ return result
672
+ }
673
+
674
+ function turboHostSource(withRuntime: boolean): string {
675
+ return `// React Native's TurboModuleBinding on the process's JSI runtime, answered
676
+ // from the global C++ module map as RCTTurboModuleManager answers a C++ module:
677
+ // each module is created once, with the JS thread's call invoker.
678
+ #include "${TURBO_ENTRY_HEADER}"
679
+ #include "PeachJsiRuntime.hpp"
680
+ #include <ReactCommon/CallInvoker.h>
681
+ #include <ReactCommon/CxxTurboModuleUtils.h>
682
+ #include <ReactCommon/TurboModuleBinding.h>
683
+ #include <deque>
684
+ #include <memory>
685
+ #include <string>
686
+ #include <unordered_map>
687
+
688
+ using namespace facebook;
689
+
690
+ namespace {
691
+ // async work runs once the host's current call returns; sync work runs
692
+ // inline, both on the one JS thread.
693
+ class JsCallInvoker final : public react::CallInvoker {
694
+ public:
695
+ explicit JsCallInvoker(jsi::Runtime& runtime) : runtime(runtime) {}
696
+ void invokeAsync(react::CallFunc&& func) noexcept override {
697
+ pending.push_back(std::move(func));
698
+ peach::jsi_runtime::scheduleDrain();
699
+ }
700
+ void invokeSync(react::CallFunc&& func) override {
701
+ func(runtime);
702
+ }
703
+ void drain() {
704
+ while (!pending.empty()) {
705
+ auto work = std::move(pending.front());
706
+ pending.pop_front();
707
+ work(runtime);
708
+ }
709
+ }
710
+
711
+ private:
712
+ jsi::Runtime& runtime;
713
+ std::deque<react::CallFunc> pending;
714
+ };
715
+
716
+ std::shared_ptr<JsCallInvoker> invoker;
717
+ std::unordered_map<std::string, std::shared_ptr<react::TurboModule>> modules;
718
+ std::string names;
719
+
720
+ std::shared_ptr<react::TurboModule> provide(const std::string& name) {
721
+ if (auto found = modules.find(name); found != modules.end()) return found->second;
722
+ auto& providers = react::globalExportedCxxTurboModuleMap();
723
+ auto provider = providers.find(name);
724
+ if (provider == providers.end()) return nullptr;
725
+ auto module = provider->second(invoker);
726
+ modules.emplace(name, module);
727
+ return module;
728
+ }
729
+ } // namespace
730
+
731
+ extern "C" void peachTurboInitialize() {
732
+ auto& runtime = peach::jsi_runtime::create(
733
+ [] { invoker->drain(); },
734
+ [] {
735
+ modules.clear();
736
+ invoker.reset();
737
+ });
738
+ invoker = std::make_shared<JsCallInvoker>(runtime);
739
+ react::TurboModuleBinding::install(
740
+ runtime,
741
+ ${withRuntime ? '[](jsi::Runtime&, const std::string& name) { return provide(name); }' : '[](const std::string& name) { return provide(name); }'});
742
+ }
743
+
744
+ // the names the global map holds, newline separated, for the host to claim
745
+ extern "C" __attribute__((export_name("peach_turbo_module_names"))) const char* peachTurboModuleNames() {
746
+ names.clear();
747
+ for (const auto& [name, provider] : react::globalExportedCxxTurboModuleMap()) {
748
+ if (!names.empty()) names += '\\n';
749
+ names += name;
750
+ }
751
+ return names.c_str();
752
+ }
753
+ `
754
+ }