peachsim 0.1.2591 → 0.1.2593

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 (149) 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 +5684 -5254
  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-EMX4WZ72.mjs → acorn-DLENU3SM.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-VYZ5DC3M.mjs → chunk-23D4W2EY.mjs} +1015 -703
  28. package/dist-lib/esm-chunks/{chunk-MC6NMYWY.mjs → chunk-2MWUVSRW.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-UIVXVMS5.mjs → chunk-2UERF2EN.mjs} +2 -2
  30. package/dist-lib/esm-chunks/{chunk-VRVXRZI4.mjs → chunk-4YJJKKKF.mjs} +112 -58
  31. package/dist-lib/esm-chunks/{chunk-AKKHSVJ4.mjs → chunk-6O2M4J2Y.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-EGKH2L6J.mjs → chunk-BMKI4WBL.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-4QHHRGO4.mjs → chunk-DLSPHUHQ.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-UYJXLDCG.mjs → chunk-E6OGMX3T.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-VF5WVB3D.mjs → chunk-GFMQ5PNX.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-JHXDM3YU.mjs → chunk-IT4CC3HU.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-J676B57D.mjs → chunk-JPNUGMLE.mjs} +5 -5
  38. package/dist-lib/esm-chunks/{chunk-RKQZGWX2.mjs → chunk-KWMJUJJS.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-QBMFX3J2.mjs → chunk-LK3KQ4X3.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-ZL5N6ENT.mjs → chunk-LN7ZTBNS.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-Q4NA6PUR.mjs → chunk-NIYJBFXV.mjs} +3 -3
  42. package/dist-lib/esm-chunks/{chunk-7627LKJK.mjs → chunk-OIHSBING.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-YR6DNV76.mjs → chunk-P3A4MQHR.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-VD27WNCT.mjs → chunk-TXBZEHNH.mjs} +4 -4
  45. package/dist-lib/esm-chunks/{chunk-TFG4LZ5T.mjs → chunk-UM4DCXPA.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-ILWFGZWW.mjs → chunk-UZPLSN2V.mjs} +107 -6
  47. package/dist-lib/esm-chunks/{chunk-SOAYP72T.mjs → chunk-XFFPOSW2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-NX23AMX4.mjs → chunk-ZT5ZXQC2.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-ANKZARNW.mjs → metro-layout-parser-DHGC2DVE.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-4N5CXBOZ.mjs → swift-package-prebuilt-ROIDLGLU.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-5IUSRXYA.mjs → swift-sdk-app-module-5VU63S56.mjs} +30 -20
  52. package/dist-lib/esm-chunks/{swift-sdk-image-7T2LMQS5.mjs → swift-sdk-image-SNFZVUQ3.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-7QJ3BF6E.mjs → swift-sdk-image-producer-5RQDIX53.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +3561 -3134
  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 +6082 -5142
  59. package/dist-lib/host/fetch-proxy-handler.cjs +314 -301
  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 +241 -226
  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 +75 -73
  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 +6704 -5764
  93. package/dist-lib/swift-compile.cjs +1333 -922
  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/binaryen.lock.json +3 -3
  130. package/src/native-bundles.ts +2 -0
  131. package/src/one-native-controls-package.ts +235 -40
  132. package/src/one-sdk/source.ts +2 -1
  133. package/src/one-sdk-preparation.ts +40 -2
  134. package/src/oneSdkContract.ts +13 -2
  135. package/src/swift-compile.ts +301 -48
  136. package/src/swift-guest-compile.ts +11 -2
  137. package/src/swift-guest-projection-storage.ts +45 -26
  138. package/src/swift-guest-runtime-plan.ts +1 -1
  139. package/src/swift-host.ts +88 -16
  140. package/src/swift-reproducible.ts +16 -2
  141. package/src/swift-root-lock.ts +77 -5
  142. package/src/swift-sdk-app-module.ts +15 -6
  143. package/src/swift-sdk-image-wasm.ts +5 -2
  144. package/src/swift-sdk-image.ts +122 -59
  145. package/src/swift-startup-split.ts +65 -27
  146. package/src/swift-toolchain.ts +16 -5
  147. package/src/swift-wasm-prune.ts +51 -34
  148. package/src/wasm-lazy-split.ts +46 -40
  149. package/src/wasm-optimize.ts +146 -140
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,
@@ -115,12 +115,21 @@ export async function buildSwiftAppModule(options: {
115
115
  work,
116
116
  readInput,
117
117
  })
118
- await link.lower()
119
- const usage = readSwiftSdkUsage(
120
- project ? projectOutputFile(buildRoot, map, project) : map,
121
- pruned,
122
- )
123
- const binding = createSwiftSdkBinding(link.linkage, sdk, usage)
118
+ const lowerPromise = link.lower()
119
+ await new Promise((resolve) => setImmediate(resolve))
120
+ let usage: SwiftSdkUsage
121
+ let binding: SwiftSdkBindingAsset
122
+ try {
123
+ usage = readSwiftSdkUsage(
124
+ project ? projectOutputFile(buildRoot, map, project) : map,
125
+ pruned,
126
+ )
127
+ binding = createSwiftSdkBinding(link.linkage, sdk, usage)
128
+ } catch (error) {
129
+ await lowerPromise.catch(() => {})
130
+ throw error
131
+ }
132
+ await lowerPromise
124
133
  if (!project)
125
134
  writeSwiftSdkAppLink(path.join(work, 'app-link.json.gz'), {
126
135
  linkage: link.linkage,
@@ -12,6 +12,9 @@ export interface WasmSection {
12
12
  }
13
13
 
14
14
  export function wasmReader(bytes: Uint8Array, start: number) {
15
+ const rawBuf = Buffer.isBuffer(bytes)
16
+ ? bytes
17
+ : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
15
18
  let at = start
16
19
  const u = () => {
17
20
  let value = 0
@@ -40,7 +43,7 @@ export function wasmReader(bytes: Uint8Array, start: number) {
40
43
  name: () => {
41
44
  const length = u()
42
45
  at += length
43
- return Buffer.from(bytes.subarray(at - length, at)).toString()
46
+ return rawBuf.toString('utf8', at - length, at)
44
47
  },
45
48
  skip: (length: number) => {
46
49
  at += length
@@ -503,7 +506,7 @@ export function codeOnlySdkImage(bytes: Uint8Array, constructorMask: number): Bu
503
506
  // the start function keeps its once-only guard and tls setup; its data copies and bss fill
504
507
  // go, since the loader has already written this app's sdk data
505
508
  {
506
- const body = Uint8Array.from(bodies[initMemory]!)
509
+ const body = new Uint8Array(bodies[initMemory]!)
507
510
  const r = wasmReader(body, 0)
508
511
  if (r.u() !== 0) throw new Error('sdk memory initializer has locals')
509
512
  while (r.at < body.length) {
@@ -7,6 +7,7 @@ import {
7
7
  readFileSync,
8
8
  renameSync,
9
9
  rmSync,
10
+ statSync,
10
11
  writeFileSync,
11
12
  } from 'node:fs'
12
13
  import path from 'node:path'
@@ -217,24 +218,56 @@ export function swiftSdkImageEntry(key: string, scopedLookups: boolean) {
217
218
  }
218
219
  }
219
220
 
221
+ // bounded in-memory caches avoid reparsing 70+ MB sdk json across repeated builds in one process.
222
+ const MAX_CACHED_SDK_IMAGES = 4
223
+ const cachedSdkInterfaces = new Map<string, SwiftSdkInterface>()
224
+ const cachedSdkManifestIndices = new Map<string, SwiftSdkManifest>()
225
+ const cachedSdkManifests = new Map<
226
+ string,
227
+ {
228
+ manifest: SwiftSdkManifest
229
+ block: (name: SwiftSdkManifestBlock) => Uint32Array
230
+ segments: Array<SwiftSdkManifest['segments'][number] & { data: Uint8Array }>
231
+ }
232
+ >()
233
+
234
+ function setBoundedCache<T>(cache: Map<string, T>, key: string, value: T): T {
235
+ cache.delete(key)
236
+ cache.set(key, value)
237
+ while (cache.size > MAX_CACHED_SDK_IMAGES) {
238
+ const oldest = cache.keys().next().value
239
+ if (oldest !== undefined) cache.delete(oldest)
240
+ }
241
+ return value
242
+ }
243
+
220
244
  function cached(directory: string, key: string): SwiftSdkImage | undefined {
221
- const sdkInterface = path.join(directory, INTERFACE_FILE)
245
+ const sdkInterfacePath = path.join(directory, INTERFACE_FILE)
222
246
  const image = path.join(directory, IMAGE_FILE)
223
247
  const address = path.join(directory, IMAGE_DIGEST)
224
248
  if (
225
249
  !existsSync(image) ||
226
250
  !existsSync(address) ||
227
- !existsSync(sdkInterface) ||
251
+ !existsSync(sdkInterfacePath) ||
228
252
  !existsSync(path.join(directory, MANIFEST_FILE)) ||
229
253
  !existsSync(path.join(directory, MANIFEST_DATA_FILE))
230
254
  )
231
255
  return undefined
256
+ const sha256 = readFileSync(address, 'utf8')
257
+ const cacheKey = `${directory}\0${sha256}`
258
+ let loadedInterface: SwiftSdkInterface | undefined
232
259
  return {
233
260
  key,
234
261
  directory,
235
262
  image,
236
- sha256: readFileSync(address, 'utf8'),
237
- sdkInterface: JSON.parse(readFileSync(sdkInterface, 'utf8')),
263
+ sha256,
264
+ get sdkInterface(): SwiftSdkInterface {
265
+ if (loadedInterface) return loadedInterface
266
+ const memo = cachedSdkInterfaces.get(cacheKey)
267
+ if (memo) return (loadedInterface = memo)
268
+ const parsed: SwiftSdkInterface = JSON.parse(readFileSync(sdkInterfacePath, 'utf8'))
269
+ return (loadedInterface = setBoundedCache(cachedSdkInterfaces, cacheKey, parsed))
270
+ },
238
271
  }
239
272
  }
240
273
 
@@ -401,9 +434,11 @@ async function linkSwiftSdkImage(
401
434
  objects.push({ path: object, bytes, instrumentDynamicLookups: false })
402
435
  guestObjects.set(product, objects)
403
436
  }
404
- const classifyFile = (file: string) => {
437
+ const classifyFile = (file: string, collectAutolink = false) => {
405
438
  const bytes = readFileSync(file)
406
439
  if (!file.endsWith('.a')) {
440
+ if (collectAutolink)
441
+ for (const library of autolinkLibraries(bytes)) libraries.add(library)
407
442
  const scoped = lookups?.rewrite(file, bytes) ?? bytes
408
443
  return addObject(file, scoped, file)
409
444
  }
@@ -411,6 +446,8 @@ async function linkSwiftSdkImage(
411
446
  mkdirSync(path.join(members, archive))
412
447
  const ordinals = new Map<string, number>()
413
448
  readArMembers(bytes).forEach((member, index) => {
449
+ if (collectAutolink)
450
+ for (const library of autolinkLibraries(member.bytes)) libraries.add(library)
414
451
  const object = path.join(members, archive, `${index}-${path.basename(member.name)}`)
415
452
  const ordinal = (ordinals.get(member.name) ?? 0) + 1
416
453
  ordinals.set(member.name, ordinal)
@@ -425,10 +462,8 @@ async function linkSwiftSdkImage(
425
462
  })
426
463
  }
427
464
  for (const object of [...link.objects, ...link.providers]) {
428
- classifyFile(object)
429
465
  // the sdk's own library dependencies; an app's other libraries stay in its module
430
- for (const bytes of objectMembers(object))
431
- for (const library of autolinkLibraries(bytes)) libraries.add(library)
466
+ classifyFile(object, true)
432
467
  }
433
468
  for (const library of libraries) {
434
469
  if (unpacked.has(library.slice(2))) continue
@@ -443,6 +478,7 @@ async function linkSwiftSdkImage(
443
478
  const hostExports = sdkHostExports(appRoot)
444
479
  const guestMap = new Map<string, SwiftSdkGuestObject>()
445
480
  const guestMetadataNames: Record<string, string> = {}
481
+ const compiles: Promise<unknown>[] = []
446
482
  if (lookups) {
447
483
  const ledger = lookups.link(guestObjects, [
448
484
  ...hostExports,
@@ -481,33 +517,38 @@ async function linkSwiftSdkImage(
481
517
  const scopeLedger = path.join(work, 'guest-ledger.ll')
482
518
  const scopeObject = path.join(work, 'guest-ledger.o')
483
519
  writeFileSync(scopeLedger, ledger.llvmIR)
484
- await run(path.join(toolchain.toolchainBin, 'clang'), [
485
- `--target=${SWIFT_WASM_TRIPLE}`,
486
- '-matomics',
487
- '-mbulk-memory',
488
- '-c',
489
- scopeLedger,
490
- '-o',
491
- scopeObject,
492
- ])
520
+ compiles.push(
521
+ run(path.join(toolchain.toolchainBin, 'clang'), [
522
+ `--target=${SWIFT_WASM_TRIPLE}`,
523
+ '-matomics',
524
+ '-mbulk-memory',
525
+ '-c',
526
+ scopeLedger,
527
+ '-o',
528
+ scopeObject,
529
+ ]),
530
+ )
493
531
  eager.push(scopeObject)
494
532
  }
495
533
  writeFileSync(
496
534
  path.join(work, 'image-tables.c'),
497
535
  IMAGE_TABLES + (guestLookups?.source ?? ''),
498
536
  )
499
- await run(path.join(toolchain.toolchainBin, 'clang'), [
500
- `--target=${SWIFT_WASM_TRIPLE}`,
501
- '-O2',
502
- '-matomics',
503
- '-mbulk-memory',
504
- '-ffreestanding',
505
- ...(lookups ? ['-DPEACH_SDK_GUEST_LINK'] : []),
506
- '-c',
507
- path.join(work, 'image-tables.c'),
508
- '-o',
509
- tables,
510
- ])
537
+ compiles.push(
538
+ run(path.join(toolchain.toolchainBin, 'clang'), [
539
+ `--target=${SWIFT_WASM_TRIPLE}`,
540
+ '-O2',
541
+ '-matomics',
542
+ '-mbulk-memory',
543
+ '-ffreestanding',
544
+ ...(lookups ? ['-DPEACH_SDK_GUEST_LINK'] : []),
545
+ '-c',
546
+ path.join(work, 'image-tables.c'),
547
+ '-o',
548
+ tables,
549
+ ]),
550
+ )
551
+ await Promise.all(compiles)
511
552
  const quote = (value: string) => JSON.stringify(value)
512
553
  writeFileSync(
513
554
  path.join(work, 'exports.rsp'),
@@ -566,25 +607,33 @@ async function linkSwiftSdkImage(
566
607
  if (mask === undefined) throw new Error('sdk image lacks its constructor mask')
567
608
  const code = path.join(work, 'code.wasm')
568
609
  writeFileSync(code, codeOnlySdkImage(finished, mask))
569
- await lowerWasm(code, path.join(work, IMAGE_FILE), {
610
+ const lowerPromise = lowerWasm(code, path.join(work, IMAGE_FILE), {
570
611
  optimize: true,
571
612
  skipPasses: lookups ? ['duplicate-function-elimination'] : undefined,
572
613
  })
614
+ // let lowerWasm spawn its child process before synchronous manifest work runs.
615
+ await new Promise((resolve) => setImmediate(resolve))
616
+ try {
617
+ writeSdkManifest(
618
+ work,
619
+ linkMap,
620
+ linkedBytes,
621
+ finished,
622
+ readFileSync(withRelocs),
623
+ functionSlots,
624
+ lookups && { inputs: guestMap, metadataNames: guestMetadataNames },
625
+ )
626
+ } catch (error) {
627
+ await lowerPromise.catch(() => {})
628
+ throw error
629
+ }
630
+ await lowerPromise
573
631
  // a startup split gives a deferred function that startup code calls directly a new slot past
574
632
  // the image's table, so app modules start their table after room for every such function
575
633
  const image = readFileSync(path.join(work, IMAGE_FILE))
576
634
  sdkInterface.layout.tableEnd += unslottedFunctions(image)
577
635
  if (sdkInterface.layout.tableEnd > SWIFT_SDK_APP_TABLE_BASE)
578
636
  throw new Error('Swift SDK image exceeds its reserved function table range')
579
- writeSdkManifest(
580
- work,
581
- linkMap,
582
- linkedBytes,
583
- finished,
584
- readFileSync(withRelocs),
585
- functionSlots,
586
- lookups && { inputs: guestMap, metadataNames: guestMetadataNames },
587
- )
588
637
  writeFileSync(path.join(work, INTERFACE_FILE), JSON.stringify(sdkInterface))
589
638
  writeFileSync(
590
639
  path.join(work, IMAGE_DIGEST),
@@ -675,18 +724,14 @@ function sdkLinkInputs(appRoot: string) {
675
724
  return { flags, libraries, objects: [crt, ...objects], providers }
676
725
  }
677
726
 
678
- function objectMembers(file: string): Uint8Array[] {
679
- const bytes = readFileSync(file)
680
- return file.endsWith('.a')
681
- ? readArMembers(bytes).map((member) => member.bytes)
682
- : [bytes]
683
- }
684
-
685
727
  function autolinkLibraries(bytes: Uint8Array): string[] {
686
728
  const entries = wasmSections(bytes).find((s) => s.name === '.swift1_autolink_entries')
687
729
  if (!entries) return []
688
- return Buffer.from(bytes.subarray(entries.start, entries.end))
689
- .toString()
730
+ const raw = Buffer.isBuffer(bytes)
731
+ ? bytes
732
+ : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
733
+ return raw
734
+ .toString('utf8', entries.start, entries.end)
690
735
  .split('\0')
691
736
  .filter((entry) => entry.startsWith('-l'))
692
737
  }
@@ -829,10 +874,18 @@ function writeSdkManifest(
829
874
  starts.push(targets.length)
830
875
  return { starts, targets }
831
876
  }
832
- const byAddress = (edges: readonly number[]) => {
833
- const pairs: [number, number][] = []
834
- for (let i = 0; i < edges.length; i += 2) pairs.push([edges[i]!, edges[i + 1]!])
835
- return pairs.sort((a, b) => a[0] - b[0]).flat()
877
+ const byAddress = (edges: readonly number[]): Uint32Array => {
878
+ const count = edges.length >>> 1
879
+ const order = new Uint32Array(count)
880
+ for (let i = 0; i < count; i++) order[i] = i
881
+ order.sort((a, b) => edges[a * 2]! - edges[b * 2]!)
882
+ const sorted = new Uint32Array(edges.length)
883
+ for (let i = 0; i < count; i++) {
884
+ const src = order[i]! * 2
885
+ sorted[i * 2] = edges[src]!
886
+ sorted[i * 2 + 1] = edges[src + 1]!
887
+ }
888
+ return sorted
836
889
  }
837
890
  const functionData = flatten(edges.code)
838
891
  const functionCalls = flatten(edges.calls)
@@ -847,7 +900,7 @@ function writeSdkManifest(
847
900
  functionCalls: functionCalls.targets,
848
901
  dataEdges: byAddress(edges.data),
849
902
  dataFunctions: byAddress(edges.dataFunctions),
850
- } satisfies Record<SwiftSdkManifestBlock, number[]>
903
+ } satisfies Record<SwiftSdkManifestBlock, ArrayLike<number>>
851
904
  const shipped = segmentNames.filter((name) => name !== '.bss')
852
905
  const segmentData = passiveSegments(finished)
853
906
  if (shipped.length !== segmentData.length)
@@ -903,18 +956,28 @@ function writeSdkManifest(
903
956
  export function readSwiftSdkManifestIndex(
904
957
  image: Pick<SwiftSdkImage, 'directory'>,
905
958
  ): SwiftSdkManifest {
906
- const manifest: SwiftSdkManifest = JSON.parse(
907
- readFileSync(path.join(image.directory, MANIFEST_FILE), 'utf8'),
908
- )
959
+ const manifestPath = path.join(image.directory, MANIFEST_FILE)
960
+ const stat = statSync(manifestPath, { bigint: true })
961
+ const cacheKey = `${manifestPath}\0${stat.size}:${stat.mtimeNs}`
962
+ const memo = cachedSdkManifestIndices.get(cacheKey)
963
+ if (memo) return memo
964
+ const manifest: SwiftSdkManifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
909
965
  if (manifest.version !== SWIFT_SDK_IMAGE_VERSION)
910
966
  throw new Error(`sdk manifest version ${manifest.version}`)
911
- return manifest
967
+ return setBoundedCache(cachedSdkManifestIndices, cacheKey, manifest)
912
968
  }
913
969
 
914
970
  /** the manifest of a built sdk image, its u32 blocks and the shipped segments' bytes. */
915
971
  export function readSwiftSdkManifest(image: Pick<SwiftSdkImage, 'directory'>) {
972
+ const manifestPath = path.join(image.directory, MANIFEST_FILE)
973
+ const dataPath = path.join(image.directory, MANIFEST_DATA_FILE)
974
+ const mStat = statSync(manifestPath, { bigint: true })
975
+ const dStat = statSync(dataPath, { bigint: true })
976
+ const cacheKey = `${image.directory}\0${mStat.size}:${mStat.mtimeNs}\0${dStat.size}:${dStat.mtimeNs}`
977
+ const memo = cachedSdkManifests.get(cacheKey)
978
+ if (memo) return memo
916
979
  const manifest = readSwiftSdkManifestIndex(image)
917
- const data = readFileSync(path.join(image.directory, MANIFEST_DATA_FILE))
980
+ const data = readFileSync(dataPath)
918
981
  const words = new Uint32Array(data.buffer, data.byteOffset, manifest.segmentBytes / 4)
919
982
  const blocks = new Map<SwiftSdkManifestBlock, Uint32Array>()
920
983
  let at = 0
@@ -928,7 +991,7 @@ export function readSwiftSdkManifest(image: Pick<SwiftSdkImage, 'directory'>) {
928
991
  ...segment,
929
992
  data: data.subarray(segment.bytes, segment.bytes + segment.length),
930
993
  }))
931
- return { manifest, block, segments }
994
+ return setBoundedCache(cachedSdkManifests, cacheKey, { manifest, block, segments })
932
995
  }
933
996
 
934
997
  const MANIFEST_BLOCKS: readonly string[] = [