peachsim 0.1.2590 → 0.1.2592

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 (144) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +4184 -3613
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +2 -2
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-65FNEARV.mjs → acorn-67PU73QE.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-X2EKFONU.mjs → chunk-5FTHILIE.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-ADKUIQXX.mjs → chunk-6DB5FR7S.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-WPDY5IAD.mjs → chunk-CF3MTPMY.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-RGC2JNCL.mjs → chunk-D4LYKRRB.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-EFKDUMB5.mjs → chunk-DFF5XZ5M.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-2GUB5OLB.mjs → chunk-EHRSWFTD.mjs} +3 -3
  33. package/dist-lib/esm-chunks/{chunk-NZY4GOG5.mjs → chunk-EITX573K.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-SLPXTLBK.mjs → chunk-EWHA6X3Z.mjs} +5 -5
  35. package/dist-lib/esm-chunks/{chunk-BZS5SIYK.mjs → chunk-FYXXFYML.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-JG4AANWA.mjs → chunk-GQ3EO2UV.mjs} +107 -6
  37. package/dist-lib/esm-chunks/{chunk-N2II5SRJ.mjs → chunk-GY6TE4B4.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-HZTK7TP5.mjs → chunk-KDI5YYQ6.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-4VCRUQ36.mjs → chunk-L5T3HBPO.mjs} +973 -549
  40. package/dist-lib/esm-chunks/{chunk-SRFKOU76.mjs → chunk-M4QLI2SY.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-OZJ66CXY.mjs → chunk-PITO2NI2.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-5GNGHM5B.mjs → chunk-QSFWBVUO.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-YPPH6F77.mjs → chunk-R3WTQB5J.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-XE3VHAU2.mjs → chunk-RV4ACE6R.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-GBD26EBV.mjs → chunk-SW4PSSTF.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-V5TTEXYO.mjs → chunk-TJZPNFVF.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-WYDRQRJL.mjs → chunk-XSQH4R5E.mjs} +48 -15
  48. package/dist-lib/esm-chunks/{chunk-462CWTWI.mjs → chunk-XZ3FX3HW.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-CRI3GMCM.mjs → metro-layout-parser-EX65MARK.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-5XDZ2HZZ.mjs → swift-package-prebuilt-3BPDQVA7.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-6H3G6AXD.mjs → swift-sdk-app-module-CRX6E3TR.mjs} +151 -67
  52. package/dist-lib/esm-chunks/{swift-sdk-image-WAC7GG2R.mjs → swift-sdk-image-EJD5TPQH.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-B3L27QTG.mjs → swift-sdk-image-producer-QAZOSLTZ.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +3555 -2987
  55. package/dist-lib/expo-swift-metadata.cjs +1 -1
  56. package/dist-lib/expo-swift-metadata.mjs +7 -7
  57. package/dist-lib/home-paths.cjs +1 -1
  58. package/dist-lib/host/bridge-host.cjs +5981 -4986
  59. package/dist-lib/host/fetch-proxy-handler.cjs +310 -298
  60. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  61. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  62. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  63. package/dist-lib/host/websocket-proxy.cjs +1 -1
  64. package/dist-lib/index.cjs +1 -1
  65. package/dist-lib/kotlin-host.cjs +1 -1
  66. package/dist-lib/menu.cjs +1 -1
  67. package/dist-lib/menu.mjs +3 -3
  68. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  69. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  70. package/dist-lib/metro-production-bundle.cjs +1 -1
  71. package/dist-lib/metro-production-bundle.mjs +4 -4
  72. package/dist-lib/native-app-identity-project.cjs +238 -223
  73. package/dist-lib/native-app-identity-project.mjs +17 -17
  74. package/dist-lib/native-app-identity.cjs +1 -1
  75. package/dist-lib/native-app-identity.mjs +6 -6
  76. package/dist-lib/native-firebase-metadata.cjs +1 -1
  77. package/dist-lib/native-firebase-metadata.mjs +3 -3
  78. package/dist-lib/pdfium-raster.cjs +1 -1
  79. package/dist-lib/pdfium-raster.mjs +2 -2
  80. package/dist-lib/plist.cjs +1 -1
  81. package/dist-lib/plist.mjs +3 -3
  82. package/dist-lib/profiles.cjs +1 -1
  83. package/dist-lib/public-brand.cjs +1 -1
  84. package/dist-lib/public-origins-lib-esm.json +81 -81
  85. package/dist-lib/public-origins-lib.json +73 -71
  86. package/dist-lib/react-native-host-modules.cjs +1 -1
  87. package/dist-lib/react-native-host-modules.mjs +2 -2
  88. package/dist-lib/reap-browser.cjs +1 -1
  89. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  90. package/dist-lib/sdk.cjs +1 -1
  91. package/dist-lib/sdk.mjs +8 -8
  92. package/dist-lib/skills.cjs +6603 -5608
  93. package/dist-lib/swift-compile.cjs +1363 -778
  94. package/dist-lib/swift-compile.mjs +10 -10
  95. package/dist-lib/swift-package.cjs +1 -1
  96. package/dist-lib/swift-package.mjs +3 -3
  97. package/dist-lib/swift-submit.cjs +1 -1
  98. package/dist-lib/swift-submit.mjs +6 -6
  99. package/dist-lib/swift-svg-raster.cjs +1 -1
  100. package/dist-lib/swift-svg-raster.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +12 -6
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/dist-types/packages/peach-engine/src/engine/native-node-queries.d.ts +1 -0
  126. package/kotlin/sdk.tar.gz +0 -0
  127. package/package.json +1 -1
  128. package/runtime-companion.json +1 -1
  129. package/src/native-bundles.ts +2 -0
  130. package/src/one-native-controls-package.ts +141 -31
  131. package/src/one-sdk/source.ts +2 -1
  132. package/src/oneSdkContract.ts +13 -2
  133. package/src/swift-compile.ts +301 -48
  134. package/src/swift-guest-compile.ts +41 -8
  135. package/src/swift-guest-link.ts +3 -0
  136. package/src/swift-guest-source-inputs.ts +158 -30
  137. package/src/swift-host.ts +88 -16
  138. package/src/swift-reproducible.ts +16 -2
  139. package/src/swift-root-lock.ts +77 -5
  140. package/src/swift-sdk-app-module.ts +146 -59
  141. package/src/swift-sdk-image.ts +53 -10
  142. package/src/swift-startup-split.ts +65 -27
  143. package/src/swift-toolchain.ts +16 -5
  144. package/src/wasm-lazy-split.ts +46 -40
@@ -61,22 +61,47 @@ export const CLANG_TARGET_MODULE_WRAPPER = '.peach-clang'
61
61
 
62
62
  const PARALLEL_REPLAY = `
63
63
  const { spawn } = require('node:child_process')
64
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
64
+ const fs = require('node:fs')
65
+ const commands = JSON.parse(fs.readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
66
+ const results = new Array(commands.length)
65
67
  let next = 0
66
68
  const run = () => {
67
69
  if (next >= commands.length) return Promise.resolve()
68
- const [file, ...args] = commands[next++]
70
+ const index = next++
71
+ const [file, ...args] = commands[index]
69
72
  return new Promise((resolve, reject) => {
70
- const child = spawn(file, args, { stdio: 'inherit' })
73
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'inherit'] })
74
+ const metadata = []
75
+ let pending = ''
76
+ child.stdout.setEncoding('utf8')
77
+ child.stdout.on('data', (chunk) => {
78
+ const text = pending + chunk
79
+ let start = 0
80
+ for (let nl = text.indexOf('\\n'); nl !== -1; nl = text.indexOf('\\n', start)) {
81
+ if (text.charCodeAt(start) === 33) metadata.push(text.slice(start, nl))
82
+ start = nl + 1
83
+ }
84
+ pending = text.slice(start)
85
+ })
71
86
  child.on('error', reject)
72
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
87
+ child.on('close', (code) => {
88
+ if (pending.charCodeAt(0) === 33) metadata.push(pending)
89
+ if (code === 0) {
90
+ results[index] = metadata.join('\\n')
91
+ resolve()
92
+ } else reject(new Error('clang link replay failed: ' + file))
93
+ })
73
94
  }).then(run)
74
95
  }
75
96
  const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
76
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
77
- console.error(error.message)
78
- process.exit(1)
79
- })
97
+ Promise.all(Array.from({ length: jobs }, run))
98
+ .then(() => {
99
+ fs.writeFileSync(process.env.PEACH_CLANG_RESULTS, JSON.stringify(results))
100
+ })
101
+ .catch((error) => {
102
+ console.error(error.message)
103
+ process.exit(1)
104
+ })
80
105
  `
81
106
 
82
107
  function clangProducerStamp(file: string): string {
@@ -84,6 +109,89 @@ function clangProducerStamp(file: string): string {
84
109
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(':')
85
110
  }
86
111
 
112
+ function clangBinaryStamp(file: string): string {
113
+ const stat = statSync(file, { bigint: true })
114
+ return [file, stat.size, stat.mtimeNs].join(':')
115
+ }
116
+
117
+ function clangWrapperStamp(file: string): string {
118
+ return createHash('sha256').update(readFileSync(file)).digest('hex')
119
+ }
120
+
121
+ function clangArgsNeedCwd(args: readonly string[]): boolean {
122
+ const pathFlags = new Set([
123
+ '-I',
124
+ '-isystem',
125
+ '-iquote',
126
+ '-F',
127
+ '-iframework',
128
+ '-isysroot',
129
+ '-o',
130
+ '-MF',
131
+ ])
132
+ const includeFlags = new Set(['-include', '-imacros'])
133
+ const valueFlags = new Set([
134
+ '-x',
135
+ '-target',
136
+ '-MT',
137
+ '-MQ',
138
+ '-D',
139
+ '-U',
140
+ '-mllvm',
141
+ '-Xclang',
142
+ '-arch',
143
+ '-std',
144
+ ])
145
+ const prefixFlags = [
146
+ '-I',
147
+ '-F',
148
+ '-isystem',
149
+ '-iquote',
150
+ '--sysroot=',
151
+ '-fmodule-map-file=',
152
+ '-fmodules-cache-path=',
153
+ ]
154
+ const isRelativePath = (value: string) =>
155
+ value.length > 0 && !value.startsWith('/') && !value.startsWith('=/') && value !== '-'
156
+ for (let i = 1; i < args.length; i++) {
157
+ const arg = args[i]!
158
+ if (pathFlags.has(arg)) {
159
+ if (isRelativePath(args[++i] ?? '')) return true
160
+ continue
161
+ }
162
+ if (includeFlags.has(arg)) {
163
+ const value = args[++i] ?? ''
164
+ if (isRelativePath(value) && (value.includes('/') || existsSync(value))) return true
165
+ continue
166
+ }
167
+ if (valueFlags.has(arg)) {
168
+ i++
169
+ continue
170
+ }
171
+ if (arg.startsWith('@')) {
172
+ if (isRelativePath(arg.slice(1))) return true
173
+ continue
174
+ }
175
+ if (arg.startsWith('-')) {
176
+ if (arg.startsWith('-include') && arg.length > 8) {
177
+ const value = arg.slice(8)
178
+ if (isRelativePath(value) && (value.includes('/') || existsSync(value)))
179
+ return true
180
+ continue
181
+ }
182
+ for (const prefix of prefixFlags) {
183
+ if (arg.startsWith(prefix) && arg.length > prefix.length) {
184
+ if (isRelativePath(arg.slice(prefix.length))) return true
185
+ break
186
+ }
187
+ }
188
+ continue
189
+ }
190
+ if (isRelativePath(arg)) return true
191
+ }
192
+ return false
193
+ }
194
+
87
195
  function validateClangLinkOptions(flags: readonly string[]): void {
88
196
  for (let index = 0; index < flags.length; index++) {
89
197
  const flag = flags[index]!
@@ -184,14 +292,13 @@ export function sourceGuestClangLinkOptions(options: {
184
292
  file: string
185
293
  compiler: string
186
294
  args: string[]
187
- output: string
188
295
  cacheFile: string
189
296
  key: string
190
297
  }[] = []
191
298
  let clang: string | undefined
192
299
  let clangStamp: string | undefined
193
300
  let wrapperStamp: string | undefined
194
- for (const [index, file] of [...wanted].entries()) {
301
+ for (const file of wanted) {
195
302
  const command = commands.get(file)
196
303
  if (!command) throw new Error(`missing source object producer ${file}`)
197
304
  if (command.tool === 'shell') {
@@ -216,12 +323,12 @@ export function sourceGuestClangLinkOptions(options: {
216
323
  const key = createHash('sha256')
217
324
  .update(
218
325
  JSON.stringify([
219
- 'clang-link-options/v1',
220
- process.cwd(),
326
+ 'clang-link-options/v2',
327
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
221
328
  driverEnvironment,
222
329
  command.args,
223
- (clangStamp ??= clangProducerStamp(clang)),
224
- compiler === clang ? null : (wrapperStamp ??= clangProducerStamp(compiler)),
330
+ (clangStamp ??= clangBinaryStamp(clang)),
331
+ compiler === clang ? null : (wrapperStamp ??= clangWrapperStamp(compiler)),
225
332
  clangProducerStamp(file),
226
333
  ]),
227
334
  )
@@ -237,29 +344,41 @@ export function sourceGuestClangLinkOptions(options: {
237
344
  continue
238
345
  }
239
346
  result.set(file, [])
240
- const args = command.args.slice(1).filter((arg) => arg !== '-c')
241
- // the replay keeps the object's <target>.build directory name
347
+ // pipe IR to stdout without writing .ll or .d files; preserve .peach-clang's module name.
242
348
  const targetBuild = path
243
349
  .relative(options.buildDirectory, file)
244
350
  .split(path.sep)
245
351
  .findLast((part) => part !== '.build' && part.endsWith('.build'))
246
- const outputDirectory = path.join(
247
- options.directory,
248
- targetBuild ?? path.basename(path.dirname(file)),
249
- )
250
- mkdirSync(outputDirectory, { recursive: true })
251
- const output = path.join(outputDirectory, `clang-link-${index}.ll`)
252
- for (const flag of ['-o', '-MF']) {
253
- const index = args.lastIndexOf(flag)
254
- if (index < 0 || index + 1 >= args.length)
255
- throw new Error(`missing clang ${flag} for ${file}`)
256
- args[index + 1] = flag === '-o' ? output : `${output}.d`
352
+ const args: string[] = []
353
+ let sawOutput = false
354
+ let explicitModuleName = false
355
+ for (let i = 1; i < command.args.length; i++) {
356
+ const arg = command.args[i]!
357
+ if (arg === '-c' || arg === '-MD' || arg === '-MMD' || arg === '-MP') continue
358
+ if (arg === '-MF' || arg === '-MT' || arg === '-MQ') {
359
+ if (i + 1 >= command.args.length)
360
+ throw new Error(`missing clang ${arg} for ${file}`)
361
+ i++
362
+ continue
363
+ }
364
+ if (arg === '-o') {
365
+ if (i + 1 >= command.args.length) throw new Error(`missing clang -o for ${file}`)
366
+ i++
367
+ args.push('-o', '-')
368
+ sawOutput = true
369
+ continue
370
+ }
371
+ if (arg.startsWith('-fmodule-name=')) explicitModuleName = true
372
+ args.push(arg)
373
+ }
374
+ if (!sawOutput) throw new Error(`missing clang -o for ${file}`)
375
+ if (compiler !== clang && targetBuild && !explicitModuleName) {
376
+ args.unshift(`-fmodule-name=${targetBuild.slice(0, -'.build'.length)}`)
257
377
  }
258
378
  replays.push({
259
379
  file,
260
380
  compiler: command.args[0]!,
261
381
  args: [...args, '-S', '-emit-llvm', '-Xclang', '-disable-llvm-passes'],
262
- output,
263
382
  cacheFile,
264
383
  key,
265
384
  })
@@ -267,6 +386,7 @@ export function sourceGuestClangLinkOptions(options: {
267
386
  if (replays.length === 0) return result
268
387
  // the pruner's plan callback is synchronous, so one child runs the replays concurrently
269
388
  const plan = path.join(options.directory, 'clang-link-replays.json')
389
+ const resultsPath = path.join(options.directory, 'clang-link-results.json')
270
390
  writeFileSync(
271
391
  plan,
272
392
  JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args])),
@@ -279,12 +399,20 @@ export function sourceGuestClangLinkOptions(options: {
279
399
  ...process.env,
280
400
  [PEACH_FORKED_SCRIPT_ENV]: '1',
281
401
  PEACH_CLANG_REPLAYS: plan,
402
+ PEACH_CLANG_RESULTS: resultsPath,
282
403
  PEACH_CLANG_JOBS: String(options.jobs),
283
404
  },
284
405
  })
406
+ const replayMetadata: unknown = JSON.parse(readFileSync(resultsPath, 'utf8'))
407
+ if (
408
+ !Array.isArray(replayMetadata) ||
409
+ replayMetadata.length !== replays.length ||
410
+ !replayMetadata.every((item) => typeof item === 'string')
411
+ )
412
+ throw new Error('invalid clang link replay results')
285
413
  mkdirSync(cacheDirectory, { recursive: true })
286
- for (const { file, output, cacheFile, key } of replays) {
287
- const flags = clangIrLinkOptions(readFileSync(output, 'utf8'))
414
+ for (const [index, { file, cacheFile, key }] of replays.entries()) {
415
+ const flags = clangIrLinkOptions(replayMetadata[index]!)
288
416
  validateClangLinkOptions(flags)
289
417
  const temporary = `${cacheFile}.${process.pid}`
290
418
  writeFileSync(temporary, JSON.stringify({ key, flags }))
package/src/swift-host.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
- import { execFile, execFileSync } from 'node:child_process'
2
+ import { execFile, execFileSync, spawn } from 'node:child_process'
3
3
  import { createHash, type Hash } from 'node:crypto'
4
4
  // the node host for every Swift preview: package inputs, one compile and
5
5
  // immutable artifact addresses. vite and the foreground CLI adapt this host.
@@ -25,7 +25,11 @@ import { type NativeAppIdentity } from './native-app-identity'
25
25
  import { readNativeAppIdentityFromXcodeTarget } from './native-app-identity-project'
26
26
  import { rustStaticLibrary } from './native-static-libraries'
27
27
  import { parsePlistSource } from './plist'
28
- import { resolveActiveRuntimeRoot } from './runtime-assets'
28
+ import {
29
+ findMonorepoRoot,
30
+ resolveActiveRuntimeRoot,
31
+ resolveDevCheckoutRuntimeRoot,
32
+ } from './runtime-assets'
29
33
  import { swiftBinaryModules } from './swift-binary-modules'
30
34
  import { normalizeSwiftCatalogPng } from './swift-catalog-png'
31
35
  import {
@@ -3339,22 +3343,45 @@ export function compileInput(
3339
3343
  )
3340
3344
  }
3341
3345
 
3342
- export function swiftBuildRoot(packagePath: string, moduleRoot: string): string {
3343
- if (process.env.CONTRAST_SWIFT_BUILD_ROOT) return process.env.CONTRAST_SWIFT_BUILD_ROOT
3344
- const distribution = swiftDistributionAt(moduleRoot)
3345
- const compilerKey = distribution
3346
- ? `${distribution.release}\0${distribution.wasmSdkChecksum}`
3347
- : moduleRoot
3346
+ function normalizedSwiftPackagePath(packagePath: string): string {
3348
3347
  const resolvedPath = path.resolve(packagePath)
3349
3348
  const parts = resolvedPath.split(path.sep)
3350
3349
  const scopedAt = Math.max(
3351
3350
  parts.lastIndexOf('peach-expo-swift'),
3352
3351
  parts.lastIndexOf('peach-nitro-swift'),
3353
3352
  )
3354
- const buildKeyPath =
3355
- scopedAt >= 0 && parts.length >= scopedAt + 3
3356
- ? parts.slice(0, scopedAt + 2).join(path.sep)
3357
- : (sourceEntries().get(resolvedPath) ?? resolvedPath)
3353
+ if (scopedAt >= 0 && parts.length >= scopedAt + 3)
3354
+ return parts.slice(0, scopedAt + 2).join(path.sep)
3355
+ const keyedAt = Math.max(
3356
+ parts.lastIndexOf('one-native-controls'),
3357
+ parts.lastIndexOf('peach-one-sdk-swift'),
3358
+ )
3359
+ if (keyedAt >= 0 && parts.length >= keyedAt + 3)
3360
+ return [...parts.slice(0, keyedAt + 1), ...parts.slice(keyedAt + 2)].join(path.sep)
3361
+ return sourceEntries().get(resolvedPath) ?? resolvedPath
3362
+ }
3363
+
3364
+ export function swiftBuildRoot(packagePath: string, moduleRoot: string): string {
3365
+ if (process.env.CONTRAST_SWIFT_BUILD_ROOT) return process.env.CONTRAST_SWIFT_BUILD_ROOT
3366
+ const distribution = swiftDistributionAt(moduleRoot)
3367
+ const resolvedModuleRoot = path.resolve(moduleRoot)
3368
+ let compilerKey = distribution
3369
+ ? `${distribution.release}\0${distribution.wasmSdkChecksum}`
3370
+ : resolvedModuleRoot
3371
+ if (
3372
+ !distribution &&
3373
+ path.basename(resolvedModuleRoot) === 'sootsim-swift' &&
3374
+ path.basename(path.dirname(resolvedModuleRoot)) === 'packages' &&
3375
+ fs.existsSync(path.join(resolvedModuleRoot, 'toolchain.json'))
3376
+ ) {
3377
+ // worktrees on the same swift toolchain share one incremental build tree;
3378
+ // swiftLinkStamp retires stale app objects whenever framework products move.
3379
+ const release = JSON.parse(
3380
+ fs.readFileSync(path.join(resolvedModuleRoot, 'toolchain.json'), 'utf8'),
3381
+ ).release
3382
+ if (typeof release === 'string') compilerKey = `source-checkout\0${release}`
3383
+ }
3384
+ const buildKeyPath = normalizedSwiftPackagePath(packagePath)
3358
3385
  return path.join(
3359
3386
  swiftCacheDir(),
3360
3387
  'swift-builds',
@@ -4104,7 +4131,7 @@ export async function swiftPackageMetadata(
4104
4131
  let startup = profiles.get(key)
4105
4132
  if (!startup) {
4106
4133
  startup = (async () => {
4107
- const runtimeRoot = startupRuntimeUrl ?? resolveActiveRuntimeRoot()
4134
+ const runtimeRoot = startupRuntimeUrl ?? (await ensureSwiftStartupRuntimeRoot())
4108
4135
  if (!runtimeRoot)
4109
4136
  throw new Error('cannot profile Swift startup without the engine runtime')
4110
4137
  const { splitSwiftApp } = await import('./swift-startup-split')
@@ -4187,6 +4214,50 @@ function swiftCodePartAssets(
4187
4214
  return codePartUrls.length ? { codePartUrls } : {}
4188
4215
  }
4189
4216
 
4217
+ // inside a Contrast monorepo worktree, Swift startup profiling must run against
4218
+ // this checkout's own engine build rather than silently falling back to an older
4219
+ // installed runtime under ~/.peach/runtimes/active (which may lack new host imports).
4220
+ async function ensureSwiftStartupRuntimeRoot(): Promise<string | null> {
4221
+ if (process.env.PEACH_HOME) {
4222
+ const active = resolveActiveRuntimeRoot()
4223
+ if (active) return active
4224
+ }
4225
+ const repo = findMonorepoRoot()
4226
+ if (!repo) return resolveActiveRuntimeRoot()
4227
+ const { findStaleDevBuildRoutes } = await import('../cli/dev-build-freshness')
4228
+ const current = () => {
4229
+ const devRoot = resolveDevCheckoutRuntimeRoot()
4230
+ if (!devRoot) return null
4231
+ // a staged symlink tree carries an exact runtime build without local
4232
+ // dev-build freshness stamps; trust it instead of rebuilding over the links.
4233
+ if (fs.lstatSync(path.join(devRoot, 'engine')).isSymbolicLink()) return devRoot
4234
+ return findStaleDevBuildRoutes(repo).length === 0 ? devRoot : null
4235
+ }
4236
+ const ready = current()
4237
+ if (ready) return ready
4238
+ const { withSwiftRootLock } = await import('./swift-root-lock')
4239
+ return withSwiftRootLock(path.join(repo, 'public', 'sootsim'), async () => {
4240
+ const built = current()
4241
+ if (built) return built
4242
+ await new Promise<void>((resolveBuild, rejectBuild) => {
4243
+ const child = spawn(
4244
+ process.execPath,
4245
+ [path.join(repo, 'scripts/build/peach-public.ts')],
4246
+ { cwd: repo, env: { ...process.env, TM_WINDOW_WAIT: '1' }, stdio: 'inherit' },
4247
+ )
4248
+ child.once('error', rejectBuild)
4249
+ child.once('close', (code) => {
4250
+ if (code === 0) resolveBuild()
4251
+ else
4252
+ rejectBuild(
4253
+ new Error(`checkout engine runtime build failed (exit ${code ?? 'signal'})`),
4254
+ )
4255
+ })
4256
+ })
4257
+ return resolveDevCheckoutRuntimeRoot()
4258
+ })
4259
+ }
4260
+
4190
4261
  export function swiftSdkEntryAssets(
4191
4262
  origin: string,
4192
4263
  image: SwiftArtifact,
@@ -4211,10 +4282,11 @@ function swiftSdkStartup(
4211
4282
  runtimeRootOverride?: URL,
4212
4283
  ) {
4213
4284
  const { key } = sdk
4285
+ const normalizedPackage = normalizedSwiftPackagePath(packagePath)
4214
4286
  const app = createHash('sha256')
4215
4287
  .update(
4216
4288
  JSON.stringify([
4217
- packagePath,
4289
+ normalizedPackage,
4218
4290
  launch.environment,
4219
4291
  runtimeRootOverride?.origin,
4220
4292
  ...(launch.arguments?.length ? [launch.arguments] : []),
@@ -4225,9 +4297,9 @@ function swiftSdkStartup(
4225
4297
  .slice(0, 16)
4226
4298
  const cacheKey = `${key}/${app}`
4227
4299
  const cached = sdkStartups.get(cacheKey)
4228
- if (cached?.artifactHash === artifactHash) return cached.startup
4300
+ if (cached) return cached.startup
4229
4301
  const startup = (async () => {
4230
- const runtimeRoot = runtimeRootOverride ?? resolveActiveRuntimeRoot()
4302
+ const runtimeRoot = runtimeRootOverride ?? (await ensureSwiftStartupRuntimeRoot())
4231
4303
  if (!runtimeRoot)
4232
4304
  throw new Error('cannot profile Swift startup without the engine runtime')
4233
4305
  const [{ splitSwiftSdkImage }, { swiftSdkImageFile }] = await Promise.all([
@@ -1,5 +1,19 @@
1
- import { realpathSync } from 'node:fs'
1
+ import { existsSync, realpathSync } from 'node:fs'
2
2
  import os from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ function canonicalHomeDir(): string {
6
+ const home = os.homedir()
7
+ // agent profiles set HOME to a subdirectory whose ~/.peach symlinks into the
8
+ // host user's real home; map the enclosing real home so shared llbuild slots
9
+ // emit identical -file-prefix-map flags across sessions.
10
+ const dotPeach = path.join(home, '.peach')
11
+ if (existsSync(dotPeach)) {
12
+ const realHome = path.dirname(realpathSync(dotPeach))
13
+ if (home === realHome || home.startsWith(`${realHome}${path.sep}`)) return realHome
14
+ }
15
+ return home
16
+ }
3
17
 
4
18
  // a wasm names its inputs by the paths they compiled from, so its bytes would
5
19
  // depend on the host user, cache directory and checkout path. every build maps
@@ -9,7 +23,7 @@ import os from 'node:os'
9
23
  export function swiftReproducibleBuildFlags(
10
24
  roots: readonly (readonly [root: string, name: string])[],
11
25
  ): string[] {
12
- return [[os.homedir(), 'home'] as const, ...roots]
26
+ return [[canonicalHomeDir(), 'home'] as const, ...roots]
13
27
  .flatMap(([root, name]) =>
14
28
  [...new Set([root, realpathSync(root)])].map((from) => `${from}=/peach/${name}`),
15
29
  )
@@ -235,6 +235,82 @@ export function swiftRootLocksDir(): string {
235
235
  * a waiter names what it waits on once per holder on stderr. locks share one
236
236
  * user directory across Peach homes: the shared build tree has one writer
237
237
  * even with isolated app state. */
238
+ export interface SwiftRootReadHold {
239
+ release(): void
240
+ }
241
+
242
+ function lockDirectoryFor(root: string): string {
243
+ const directory = path.join(
244
+ swiftRootLocksDir(),
245
+ createHash('sha256').update(rootLockKey(root)).digest('hex').slice(0, 32),
246
+ )
247
+ mkdirSync(directory, { recursive: true })
248
+ return directory
249
+ }
250
+
251
+ // records a live shared reader on `root` while the caller holds its exclusive
252
+ // lock, so writers wait or choose another slot instead of evicting products
253
+ // another build is compiling or linking against.
254
+ export function acquireSwiftRootReadHold(root: string): SwiftRootReadHold {
255
+ const directory = lockDirectoryFor(root)
256
+ const token = randomUUID()
257
+ const pending = path.join(directory, `pending.reader.${token}`)
258
+ const reader = path.join(directory, `reader.${token}`)
259
+ writeFileSync(pending, JSON.stringify(ownIdentity(process.pid)))
260
+ try {
261
+ linkSync(pending, reader)
262
+ } finally {
263
+ rmSync(pending, { force: true })
264
+ }
265
+ let released = false
266
+ return {
267
+ release() {
268
+ if (released) return
269
+ released = true
270
+ rmSync(reader, { force: true })
271
+ },
272
+ }
273
+ }
274
+
275
+ export async function hasLiveSwiftRootReaders(
276
+ root: string,
277
+ signal?: AbortSignal,
278
+ ): Promise<boolean> {
279
+ const directory = lockDirectoryFor(root)
280
+ const entries = readdirSync(directory).filter((entry) => entry.startsWith('reader.'))
281
+ if (entries.length === 0) return false
282
+ for (const entry of entries) {
283
+ const file = path.join(directory, entry)
284
+ let text: string
285
+ try {
286
+ text = readFileSync(file, 'utf8')
287
+ } catch (error) {
288
+ if (errorCode(error) === 'ENOENT') continue
289
+ throw error
290
+ }
291
+ const identity = parseIdentity(text)
292
+ const rows = await processTableWithRetry(identity.pid, signal)
293
+ if (rows.some((row) => !row.zombie && sameProcess(row, identity))) return true
294
+ rmSync(file, { force: true })
295
+ }
296
+ return false
297
+ }
298
+
299
+ export async function waitForNoSwiftRootReaders(
300
+ root: string,
301
+ signal?: AbortSignal,
302
+ ): Promise<void> {
303
+ let announced = false
304
+ while (await hasLiveSwiftRootReaders(root, signal)) {
305
+ signal?.throwIfAborted()
306
+ if (!announced) {
307
+ announced = true
308
+ process.stderr.write(`[swift-root-lock] waiting for readers of ${root}\n`)
309
+ }
310
+ await pause(POLL_MS, signal)
311
+ }
312
+ }
313
+
238
314
  export async function withSwiftRootLock<T>(
239
315
  root: string,
240
316
  work: (lease: SwiftRootLease) => Promise<T>,
@@ -254,11 +330,7 @@ export async function withSwiftRootLock<T>(
254
330
  signal?: AbortSignal,
255
331
  wait = true,
256
332
  ): Promise<T | undefined> {
257
- const directory = path.join(
258
- swiftRootLocksDir(),
259
- createHash('sha256').update(rootLockKey(root)).digest('hex').slice(0, 32),
260
- )
261
- mkdirSync(directory, { recursive: true })
333
+ const directory = lockDirectoryFor(root)
262
334
  const token = randomUUID()
263
335
  const ownRow = (await processTableWithRetry(process.pid, signal)).find(
264
336
  (candidate) => candidate.pid === process.pid && !candidate.zombie,