peachsim 0.1.2595 → 0.1.2597

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 (139) 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 +982 -431
  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 +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-J5DSQG5R.mjs → acorn-55PXV665.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-D4XFTOV2.mjs → chunk-3DRJIOHV.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-NZEHZIHZ.mjs → chunk-42RIRPTB.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-CDGSSOLF.mjs → chunk-56YYEI6C.mjs} +16 -13
  30. package/dist-lib/esm-chunks/{chunk-MTGZYNXH.mjs → chunk-7ECUAVIA.mjs} +2 -2
  31. package/dist-lib/esm-chunks/{chunk-YYAPBU4L.mjs → chunk-7J65FNXI.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-FHFNRCCX.mjs → chunk-AJHFCIEU.mjs} +4 -4
  33. package/dist-lib/esm-chunks/{chunk-G35VGABO.mjs → chunk-CKUEWEY4.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-NCMIX32U.mjs → chunk-DCL2ZEGA.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-3Z2POHJV.mjs → chunk-GECWNEHA.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-BCLZPP3O.mjs → chunk-GRGNTIO7.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-RYCGXYYL.mjs → chunk-GZD5CTG7.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-5U76J6OF.mjs → chunk-HATXI62T.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-GCOZNVG7.mjs → chunk-INA4S3MF.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-AEI4FOZK.mjs → chunk-IPN35TGX.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-U4X644Y4.mjs → chunk-LH524OUR.mjs} +3 -3
  42. package/dist-lib/esm-chunks/{chunk-ESKLJRT5.mjs → chunk-MMHNSEZY.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-POM7QBEW.mjs → chunk-NWLCTKBM.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-ZSJEHQ3R.mjs → chunk-O5FDNHDG.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-D6RI7LMX.mjs → chunk-ROFBHGEA.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-LLO2FLAP.mjs → chunk-V6SI2XY7.mjs} +967 -491
  47. package/dist-lib/esm-chunks/{chunk-JVVPCJEO.mjs → chunk-VN7BXTMG.mjs} +5 -5
  48. package/dist-lib/esm-chunks/{chunk-VZY2J2YJ.mjs → chunk-Y4XMEBRN.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-ZHPHHXG3.mjs → metro-layout-parser-5FUYCP6P.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-UXU6DFC3.mjs → swift-package-prebuilt-W3VMDYHC.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-25XPGJ4P.mjs → swift-sdk-app-module-ZHGBY6T7.mjs} +126 -56
  52. package/dist-lib/esm-chunks/{swift-sdk-image-7JKGAHEW.mjs → swift-sdk-image-2PC4PKHZ.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-KG5I2NUP.mjs → swift-sdk-image-producer-WDN6BXQL.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +981 -430
  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 +1019 -434
  59. package/dist-lib/host/fetch-proxy-handler.cjs +36 -6
  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 +34 -4
  73. package/dist-lib/native-app-identity-project.mjs +16 -16
  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 +69 -69
  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 +1020 -435
  93. package/dist-lib/swift-compile.cjs +979 -428
  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 +1 -1
  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/render-worker/nativeAnimMirrorContract.d.ts +0 -2
  126. package/package.json +1 -1
  127. package/src/one-native-controls-package.ts +32 -1
  128. package/src/swift-compile.ts +421 -175
  129. package/src/swift-guest-compile.ts +16 -0
  130. package/src/swift-guest-image-ledger.ts +65 -14
  131. package/src/swift-guest-link.ts +25 -3
  132. package/src/swift-guest-manifest.ts +27 -5
  133. package/src/swift-guest-source-inputs.ts +119 -14
  134. package/src/swift-sdk-app-module.ts +128 -55
  135. package/src/swift-sdk-image-wasm.ts +76 -39
  136. package/src/swift-sdk-image.ts +13 -9
  137. package/src/swift-wasm-prune.ts +282 -222
  138. package/src/wasm-optimize.ts +1 -1
  139. package/src/write-build-file.ts +9 -8
@@ -343,7 +343,59 @@ export function swiftBuildJobs(): number {
343
343
  }
344
344
 
345
345
  function swiftCompilerJobs(): number {
346
- return Math.min(16, swiftBuildJobs(), Math.max(1, Math.floor(os.totalmem() / 2 ** 31)))
346
+ return Math.min(32, swiftBuildJobs(), Math.max(1, Math.floor(os.totalmem() / 2 ** 31)))
347
+ }
348
+
349
+ // swiftpm hashes the entire process environment into its build plan signature,
350
+ // so volatile caller vars (PEACH_HOME, TM_*, REMOTE_*) force it to regenerate
351
+ // huge build manifests on every run. keep only compiler-relevant vars.
352
+ const SWIFT_COMPILER_ENV_KEYS = [
353
+ 'PATH',
354
+ 'HOME',
355
+ 'USER',
356
+ 'LOGNAME',
357
+ 'LANG',
358
+ 'LC_ALL',
359
+ 'LC_CTYPE',
360
+ 'TZ',
361
+ 'SDKROOT',
362
+ 'DEVELOPER_DIR',
363
+ 'DYLD_LIBRARY_PATH',
364
+ 'SYSTEMROOT',
365
+ 'COMSPEC',
366
+ 'SSL_CERT_FILE',
367
+ 'SSL_CERT_DIR',
368
+ 'HTTP_PROXY',
369
+ 'HTTPS_PROXY',
370
+ 'NO_PROXY',
371
+ 'http_proxy',
372
+ 'https_proxy',
373
+ 'no_proxy',
374
+ ] as const
375
+
376
+ function swiftCompilerBaseEnv(
377
+ toolchainBin: string,
378
+ sourceEnv: NodeJS.ProcessEnv,
379
+ includePeachHome = false,
380
+ ): NodeJS.ProcessEnv {
381
+ const env: NodeJS.ProcessEnv = {}
382
+ for (const key of SWIFT_COMPILER_ENV_KEYS) {
383
+ const value = sourceEnv[key]
384
+ if (value !== undefined) env[key] = value
385
+ }
386
+ if (includePeachHome && sourceEnv.PEACH_HOME !== undefined)
387
+ env.PEACH_HOME = sourceEnv.PEACH_HOME
388
+ if (process.platform === 'linux') {
389
+ env.LD_LIBRARY_PATH = [
390
+ path.resolve(toolchainBin, '../lib/swift/linux'),
391
+ path.resolve(toolchainBin, '../lib/swift/host'),
392
+ sourceEnv.LD_LIBRARY_PATH,
393
+ ]
394
+ .filter(Boolean)
395
+ .join(':')
396
+ }
397
+ env.PEACH_DEFER_WASM_LINK = '1'
398
+ return env
347
399
  }
348
400
 
349
401
  // a one-core grant (tm exec --local without --cores) runs a large app's
@@ -2471,12 +2523,24 @@ export function emitSwiftPackageManifest(args: {
2471
2523
  const available = distribution.objects.filter(
2472
2524
  (object) => !isProvider(object) && !replacedObjects.has(object),
2473
2525
  )
2526
+ const targetNamesWithDash = targets
2527
+ .filter((target) => target.name.includes('-'))
2528
+ .map((target) => `lib/${target.name}-`)
2529
+ const targetNameSet = new Set(targets.map((target) => target.name))
2530
+ const optionalSet = new Set([...OPTIONAL_FRAMEWORKS, ...GAME_FAMILY, 'PeachBox2D'])
2531
+ const isTargetObject = (object: string) => {
2532
+ const dash = object.indexOf('-', 4)
2533
+ if (dash > 4 && targetNameSet.has(object.slice(4, dash))) return true
2534
+ return targetNamesWithDash.some((prefix) => object.startsWith(prefix))
2535
+ }
2536
+ const isUnreachedOptional = (object: string) => {
2537
+ const dash = object.indexOf('-', 4)
2538
+ if (dash <= 4) return false
2539
+ const name = object.slice(4, dash)
2540
+ return optionalSet.has(name) && !reachedFrameworks.has(name)
2541
+ }
2474
2542
  const objects = available.filter(
2475
- (object) =>
2476
- !targets.some((target) => object.startsWith(`lib/${target.name}-`)) &&
2477
- [...OPTIONAL_FRAMEWORKS, ...GAME_FAMILY, 'PeachBox2D'].every(
2478
- (name) => !object.startsWith(`lib/${name}-`) || reachedFrameworks.has(name),
2479
- ),
2543
+ (object) => !isTargetObject(object) && !isUnreachedOptional(object),
2480
2544
  )
2481
2545
  const quoted = (object: string) =>
2482
2546
  `"${path.join(moduleRoot, object).replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
@@ -2583,21 +2647,65 @@ export function emitSwiftPackageManifest(args: {
2583
2647
  }
2584
2648
  // a binary framework's headers are found as <Framework/header.h> through -F,
2585
2649
  // as xcode passes for the xcframework; swiftpm adds only its module map directory
2586
- const frameworkDirectories = (name: string, seen = new Set<string>()): string[] =>
2587
- (siblings.get(name) ?? []).flatMap((dependency) => {
2588
- if (seen.has(dependency)) return []
2589
- seen.add(dependency)
2590
- const owner = args.targets.find((other) => other.name === dependency)
2591
- const framework = /^(.*)\/[^/]+\.framework\/Modules$/.exec(
2592
- owner?.publicHeadersPath ?? '',
2650
+ const targetByName = new Map(targets.map((target) => [target.name, target]))
2651
+ const ownFrameworkDir = new Map<string, string>()
2652
+ for (const target of targets) {
2653
+ const framework = /^(.*)\/[^/]+\.framework\/Modules$/.exec(
2654
+ target.publicHeadersPath ?? '',
2655
+ )
2656
+ if (framework)
2657
+ ownFrameworkDir.set(
2658
+ target.name,
2659
+ path.posix.join(args.root, target.path, framework[1]!),
2593
2660
  )
2594
- return [
2595
- ...(owner && framework
2596
- ? [path.posix.join(args.root, owner.path, framework[1]!)]
2597
- : []),
2598
- ...frameworkDirectories(dependency, seen),
2599
- ]
2600
- })
2661
+ }
2662
+ const frameworkDirectoriesCache = new Map<string, string[]>()
2663
+ const frameworkDirectories = (name: string): string[] => {
2664
+ if (ownFrameworkDir.size === 0) return []
2665
+ const cached = frameworkDirectoriesCache.get(name)
2666
+ if (cached) return cached
2667
+ const dirs: string[] = []
2668
+ const seen = new Set<string>()
2669
+ const visit = (current: string) => {
2670
+ for (const dependency of siblings.get(current) ?? []) {
2671
+ if (seen.has(dependency)) continue
2672
+ seen.add(dependency)
2673
+ const dir = ownFrameworkDir.get(dependency)
2674
+ if (dir) dirs.push(dir)
2675
+ visit(dependency)
2676
+ }
2677
+ }
2678
+ visit(name)
2679
+ frameworkDirectoriesCache.set(name, dirs)
2680
+ return dirs
2681
+ }
2682
+ const targetSwiftXccFlags = new Map<string, string[]>()
2683
+ for (const target of targets) {
2684
+ const flags = target.swiftFlags
2685
+ if (!flags || flags.length === 0) continue
2686
+ const xcc: string[] = []
2687
+ for (let index = 1; index < flags.length; index++) {
2688
+ if (flags[index - 1] === '-Xcc')
2689
+ xcc.push(flags[index]!.replaceAll(SWIFT_NATIVE_INPUT_ROOT, args.root))
2690
+ }
2691
+ if (xcc.length > 0) targetSwiftXccFlags.set(target.name, xcc)
2692
+ }
2693
+ const binaryImports = args.binaryModules
2694
+ ? `, "-I", ${JSON.stringify(args.binaryModules)}`
2695
+ : ''
2696
+ const sharedImports =
2697
+ binaryImports +
2698
+ (distributionModules
2699
+ ? `, "-Isystem", ${JSON.stringify(
2700
+ providedModulesPath(args.root, distributionModules, args.moduleExcludes),
2701
+ )}${distributionClangModuleOptions(args.root, distributionModules)
2702
+ .map((flag) => `, ${JSON.stringify(flag)}`)
2703
+ .join('')}`
2704
+ : prebuilt
2705
+ ? `, "-Isystem", ${JSON.stringify(providedModulesPath(args.root, prebuilt.modules, args.moduleExcludes))}${prebuilt.moduleMaps
2706
+ .map((map) => `, "-Xcc", ${JSON.stringify(`-fmodule-map-file=${map}`)}`)
2707
+ .join('')}`
2708
+ : '')
2601
2709
  const frameworkSearchFlags = (
2602
2710
  target: SwiftPackageTarget | undefined,
2603
2711
  tool: 'c' | 'cxx',
@@ -2683,22 +2791,7 @@ export function emitSwiftPackageManifest(args: {
2683
2791
  // clang loads configuration inputs before command-line libraries. forward
2684
2792
  // the file opaquely so swift neither expands it nor scans every framework
2685
2793
  // object for autolinks; distribution.link supplies those libraries.
2686
- const binaryImports = args.binaryModules
2687
- ? `, "-I", ${JSON.stringify(args.binaryModules)}`
2688
- : ''
2689
- const imports =
2690
- binaryImports +
2691
- (distributionModules
2692
- ? `, "-Isystem", ${JSON.stringify(
2693
- providedModulesPath(args.root, distributionModules, args.moduleExcludes),
2694
- )}${distributionClangModuleOptions(args.root, distributionModules)
2695
- .map((flag) => `, ${JSON.stringify(flag)}`)
2696
- .join('')}`
2697
- : prebuilt
2698
- ? `, "-Isystem", ${JSON.stringify(providedModulesPath(args.root, prebuilt.modules, args.moduleExcludes))}${prebuilt.moduleMaps
2699
- .map((map) => `, "-Xcc", ${JSON.stringify(`-fmodule-map-file=${map}`)}`)
2700
- .join('')}`
2701
- : '')
2794
+ const imports = sharedImports
2702
2795
  const nativeFlags = [
2703
2796
  ...(args.nativeFlags?.get(target.name) ?? []),
2704
2797
  ...(args.nativeHeaderFlags ?? []),
@@ -2723,14 +2816,7 @@ export function emitSwiftPackageManifest(args: {
2723
2816
  return map ? ['-fmodule-map-file=' + map] : []
2724
2817
  }),
2725
2818
  ...[...importContext].flatMap((name) => args.native?.get(name)?.importFlags ?? []),
2726
- ...[...importContext].flatMap((name) => {
2727
- const flags = targets.find((target) => target.name === name)?.swiftFlags ?? []
2728
- return flags.flatMap((flag, index) =>
2729
- flags[index - 1] === '-Xcc'
2730
- ? [flag.replaceAll(SWIFT_NATIVE_INPUT_ROOT, args.root)]
2731
- : [],
2732
- )
2733
- }),
2819
+ ...[...importContext].flatMap((name) => targetSwiftXccFlags.get(name) ?? []),
2734
2820
  ]
2735
2821
  // framework lookups precede the flat aliases used by non-framework targets.
2736
2822
  const nativeImportFlags = [
@@ -2759,10 +2845,7 @@ export function emitSwiftPackageManifest(args: {
2759
2845
  .join('')
2760
2846
  const header =
2761
2847
  args.headerDirectory &&
2762
- (args.nativeHeaderDeclarations?.[target.name] ||
2763
- [...(args.native?.values() ?? [])].some((value) =>
2764
- value.late?.producers.includes(target.name),
2765
- ))
2848
+ (args.nativeHeaderDeclarations?.[target.name] || lateProducers.has(target.name))
2766
2849
  ? `, "-emit-objc-header-path", ${JSON.stringify(path.join(args.headerDirectory, `${target.name}-Swift.original.h`))}`
2767
2850
  : ''
2768
2851
  const clangMode = target.cxxInterop ? '' : ', "-Xcc", "-fno-cxx-modules"'
@@ -2811,13 +2894,9 @@ export function emitSwiftPackageManifest(args: {
2811
2894
  // textual native headers can include one another without imposing
2812
2895
  // an object build order. the executable already links every native
2813
2896
  // target; only generated Swift headers require producer ordering.
2814
- (args.native?.get(dependency)?.clang ||
2815
- [...(args.native?.values() ?? [])].some((value) =>
2816
- value.late?.producers.includes(dependency),
2817
- ))
2897
+ (args.native?.get(dependency)?.clang || lateProducers.has(dependency))
2818
2898
  ? []
2819
- : OPTIONAL_FRAMEWORKS.has(dependency) &&
2820
- !targets.some((candidate) => candidate.name === dependency)
2899
+ : OPTIONAL_FRAMEWORKS.has(dependency) && !targetNames.has(dependency)
2821
2900
  ? linkedObjects
2822
2901
  ? []
2823
2902
  : [`.product(name: "${dependency}", package: "sootsim-swift")`]
@@ -2946,7 +3025,7 @@ export function emitSwiftPackageManifest(args: {
2946
3025
  ...(args.nativeFlags?.get(name) ?? []),
2947
3026
  ...(args.nativeHeaderFlags ?? []),
2948
3027
  ]
2949
- const owner = targets.find((target) => target.name === name)
3028
+ const owner = targetByName.get(name)
2950
3029
  // a mixed target's units include the headers its swift half imports, so
2951
3030
  // they search its dependencies' clang modules as that half does.
2952
3031
  const context = new Set<string>()
@@ -3047,12 +3126,22 @@ export function emitSwiftPackageManifest(args: {
3047
3126
  // the build tree mirrors the input: a file is written only when its text
3048
3127
  // changed and a file the input dropped is removed, so an unchanged source
3049
3128
  // keeps its mtime and swiftpm rebuilds only what moved. `.build` stays.
3050
- export function syncSwiftTree(base: string, files: Map<string, string | Buffer>): void {
3129
+ export function syncSwiftTree(
3130
+ base: string,
3131
+ files: Map<string, string | Buffer>,
3132
+ alreadySynced?: ReadonlyMap<string, string | Buffer>,
3133
+ ): void {
3051
3134
  mkdirSync(base, { recursive: true })
3052
3135
  // on a case-insensitive volume an input path can differ in case from the
3053
3136
  // directory entry holding it, so a kept file is matched by inode too.
3054
- const kept = new Set<number>()
3055
- for (const file of files.keys()) if (existsSync(file)) kept.add(statSync(file).ino)
3137
+ let kept: Set<number> | undefined
3138
+ if (process.platform !== 'linux') {
3139
+ kept = new Set<number>()
3140
+ for (const file of files.keys()) {
3141
+ const stat = statSync(file, { throwIfNoEntry: false })
3142
+ if (stat) kept.add(stat.ino)
3143
+ }
3144
+ }
3056
3145
  const walk = (dir: string): void => {
3057
3146
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
3058
3147
  const full = path.join(dir, entry.name)
@@ -3069,12 +3158,13 @@ export function syncSwiftTree(base: string, files: Map<string, string | Buffer>)
3069
3158
  )
3070
3159
  continue
3071
3160
  if (entry.isDirectory()) walk(full)
3072
- else if (!files.has(full) && !kept.has(lstatSync(full).ino))
3161
+ else if (!files.has(full) && (!kept || !kept.has(lstatSync(full).ino)))
3073
3162
  rmSync(full, { force: true })
3074
3163
  }
3075
3164
  }
3076
3165
  walk(base)
3077
3166
  for (const [full, contents] of files) {
3167
+ if (alreadySynced?.get(full) === contents) continue
3078
3168
  writeBuildFile(full, contents)
3079
3169
  }
3080
3170
  }
@@ -3245,6 +3335,53 @@ function swiftWasmCallGuards(source: string, unavailable: ReadonlySet<string>):
3245
3335
  return out
3246
3336
  }
3247
3337
 
3338
+ function matchesPathPrefixSet(file: string, set: ReadonlySet<string>): boolean {
3339
+ if (set.has(file)) return true
3340
+ for (
3341
+ let slash = file.lastIndexOf('/');
3342
+ slash !== -1;
3343
+ slash = file.lastIndexOf('/', slash - 1)
3344
+ ) {
3345
+ if (set.has(file.slice(0, slash))) return true
3346
+ }
3347
+ return false
3348
+ }
3349
+
3350
+ function indexTargetsByDirectory(
3351
+ targets: readonly SwiftPackageTarget[],
3352
+ ): ReadonlyMap<string, SwiftPackageTarget[]> {
3353
+ const byDir = new Map<string, SwiftPackageTarget[]>()
3354
+ for (const target of targets) {
3355
+ const key = target.path === '.' ? '' : target.path.replace(/\/+$/, '')
3356
+ let list = byDir.get(key)
3357
+ if (!list) byDir.set(key, (list = []))
3358
+ list.push(target)
3359
+ }
3360
+ return byDir
3361
+ }
3362
+
3363
+ function findTargetForFile(
3364
+ file: string,
3365
+ byDir: ReadonlyMap<string, readonly SwiftPackageTarget[]>,
3366
+ predicate: (target: SwiftPackageTarget, relative: string) => boolean,
3367
+ ): SwiftPackageTarget | undefined {
3368
+ for (
3369
+ let slash = file.lastIndexOf('/');
3370
+ slash !== -1;
3371
+ slash = file.lastIndexOf('/', slash - 1)
3372
+ ) {
3373
+ const candidates = byDir.get(file.slice(0, slash))
3374
+ if (!candidates) continue
3375
+ const relative = file.slice(slash + 1)
3376
+ for (const target of candidates) if (predicate(target, relative)) return target
3377
+ }
3378
+ const rootCandidates = byDir.get('')
3379
+ if (rootCandidates) {
3380
+ for (const target of rootCandidates) if (predicate(target, file)) return target
3381
+ }
3382
+ return undefined
3383
+ }
3384
+
3248
3385
  function compiledSwiftSources(
3249
3386
  files: Record<string, string>,
3250
3387
  targets: SwiftPackageTarget[],
@@ -3253,25 +3390,30 @@ function compiledSwiftSources(
3253
3390
  nativeSourceGlue = false,
3254
3391
  ): Map<string, string> {
3255
3392
  const ordered = [...targets].sort((a, b) => b.path.length - a.path.length)
3256
- const owners = new Map(
3257
- Object.entries(files)
3258
- .filter(([file]) => file.endsWith('.swift'))
3259
- .map(([file, source]) => {
3260
- const owner = ordered.find((target) => {
3261
- const prefix = target.path === '.' ? '' : target.path + '/'
3262
- if (!file.startsWith(prefix)) return false
3263
- const relative = file.slice(prefix.length)
3264
- return !target.exclude?.some(
3265
- (excluded) => relative === excluded || relative.startsWith(excluded + '/'),
3266
- )
3267
- })
3268
- return [file, { source, owner }] as const
3269
- }),
3270
- )
3393
+ const byDir = indexTargetsByDirectory(ordered)
3394
+ const excludeSets = new Map<string, ReadonlySet<string>>()
3395
+ for (const target of ordered) {
3396
+ if (target.exclude?.length) excludeSets.set(target.name, new Set(target.exclude))
3397
+ }
3398
+ const owners = new Map<
3399
+ string,
3400
+ { source: string; owner: SwiftPackageTarget | undefined }
3401
+ >()
3402
+ for (const [file, source] of Object.entries(files)) {
3403
+ if (!file.endsWith('.swift')) continue
3404
+ const owner = findTargetForFile(file, byDir, (target, relative) => {
3405
+ const excluded = excludeSets.get(target.name)
3406
+ return !excluded || !matchesPathPrefixSet(relative, excluded)
3407
+ })
3408
+ owners.set(file, { source, owner })
3409
+ }
3271
3410
  const swiftSources = new Map<string, string[]>()
3272
- for (const { source, owner } of owners.values())
3273
- if (owner)
3274
- swiftSources.set(owner.name, [...(swiftSources.get(owner.name) ?? []), source])
3411
+ for (const { source, owner } of owners.values()) {
3412
+ if (!owner) continue
3413
+ let list = swiftSources.get(owner.name)
3414
+ if (!list) swiftSources.set(owner.name, (list = []))
3415
+ list.push(source)
3416
+ }
3275
3417
  const { onWasm, withoutWasm } = swiftTargetArchitectures(targets, swiftSources, headers)
3276
3418
  return new Map(
3277
3419
  [...owners].map(([file, { source, owner }]) => {
@@ -4789,6 +4931,8 @@ export function writeSwiftProject(
4789
4931
  generatedOwners: Map<string, string>
4790
4932
  targetToolset: boolean
4791
4933
  headerCompiler: boolean
4934
+ usesObjcPrebuilt: boolean
4935
+ nativeStageObjects: ReadonlyMap<string, readonly string[]>
4792
4936
  } {
4793
4937
  const nativeToolset = needsNativeToolset(input, prebuilt)
4794
4938
  if (input.headerAliases !== undefined && !isSwiftHeaderAliases(input.headerAliases))
@@ -4870,22 +5014,47 @@ export function writeSwiftProject(
4870
5014
  const bySourcePath = [...targets].sort(
4871
5015
  (left, right) => right.path.length - left.path.length,
4872
5016
  )
5017
+ const targetsByDir = indexTargetsByDirectory(bySourcePath)
5018
+ const targetByName = new Map(targets.map((target) => [target.name, target]))
5019
+ const nativeTargets = input.nativeTargets ?? []
5020
+ const nativeTargetByName = new Map(nativeTargets.map((target) => [target.name, target]))
5021
+ const nativeTargetIndex = new Map(
5022
+ nativeTargets.map((target, index) => [target.name, index]),
5023
+ )
5024
+ const resourceTargetByName = new Map(
5025
+ resourceTargets.map((target) => [target.name, target]),
5026
+ )
5027
+ const targetSourceSets = new Map<string, ReadonlySet<string>>()
5028
+ const targetExcludeFullSets = new Map<string, ReadonlySet<string>>()
5029
+ const targetExcludeExactSets = new Map<string, ReadonlySet<string>>()
5030
+ for (const target of targets) {
5031
+ const prefix = target.path === '.' ? '' : `${target.path}/`
5032
+ if (target.sources !== undefined) {
5033
+ targetSourceSets.set(
5034
+ target.name,
5035
+ new Set(target.sources.map((source) => path.posix.join(prefix, source))),
5036
+ )
5037
+ }
5038
+ if (target.exclude?.length) {
5039
+ targetExcludeFullSets.set(
5040
+ target.name,
5041
+ new Set(target.exclude.map((excluded) => `${prefix}${excluded}`)),
5042
+ )
5043
+ targetExcludeExactSets.set(
5044
+ target.name,
5045
+ new Set(target.exclude.map((name) => path.posix.join(target.path, name))),
5046
+ )
5047
+ }
5048
+ }
4873
5049
  const swiftTargets = new Set<string>()
4874
5050
  for (const file of Object.keys(input.files)) {
4875
5051
  if (!file.endsWith('.swift')) continue
4876
- const target = bySourcePath.find(
4877
- (candidate) =>
4878
- (candidate.path === '.' || file.startsWith(`${candidate.path}/`)) &&
4879
- (candidate.sources === undefined ||
4880
- candidate.sources.some((source) => {
4881
- const selected = path.posix.join(candidate.path, source)
4882
- return file === selected || file.startsWith(`${selected}/`)
4883
- })),
4884
- )
5052
+ const target = findTargetForFile(file, targetsByDir, (candidate) => {
5053
+ const selected = targetSourceSets.get(candidate.name)
5054
+ return !selected || matchesPathPrefixSet(file, selected)
5055
+ })
4885
5056
  // swiftpm never compiles an excluded file (a prebuilt core's Swift)
4886
- const excluded = target?.exclude?.some(
4887
- (name) => file === path.posix.join(target.path, name),
4888
- )
5057
+ const excluded = target && targetExcludeExactSets.get(target.name)?.has(file)
4889
5058
  if (target && !excluded) swiftTargets.add(target.name)
4890
5059
  }
4891
5060
  // swiftpm builds a clang target's module only for an importer: a swift
@@ -4931,8 +5100,8 @@ export function writeSwiftProject(
4931
5100
  return checkedToolchain
4932
5101
  }
4933
5102
  const deploymentTarget = (name: string) =>
4934
- input.nativeTargets?.find((value) => value.name === name)?.deploymentTarget ??
4935
- targets.find((value) => value.name === name)?.iosDeploymentTarget ??
5103
+ nativeTargetByName.get(name)?.deploymentTarget ??
5104
+ targetByName.get(name)?.iosDeploymentTarget ??
4936
5105
  null
4937
5106
  const targetStagedFiles = new Map<string, Map<string, string | Buffer | undefined>>()
4938
5107
  const stageTargetFile = (
@@ -4955,31 +5124,51 @@ export function writeSwiftProject(
4955
5124
  targetStagedFiles.set(target, staged)
4956
5125
  files.set(file, contents)
4957
5126
  }
5127
+ const entriesByPrefix = new Map<string, [string, string][]>()
5128
+ for (const target of targets) {
5129
+ const prefix = target.path === '.' ? '' : `${target.path}/`
5130
+ if (!entriesByPrefix.has(prefix)) entriesByPrefix.set(prefix, [])
5131
+ }
5132
+ for (const entry of Object.entries(input.files)) {
5133
+ const [file] = entry
5134
+ entriesByPrefix.get('')?.push(entry)
5135
+ for (let end = file.indexOf('/'); end !== -1; end = file.indexOf('/', end + 1)) {
5136
+ entriesByPrefix.get(file.slice(0, end + 1))?.push(entry)
5137
+ }
5138
+ }
5139
+ const targetEntriesCache = new Map<string, [string, string][]>()
4958
5140
  const targetEntries = (target: SwiftPackageTarget) => {
5141
+ const cached = targetEntriesCache.get(target.name)
5142
+ if (cached) return cached
4959
5143
  const prefix = target.path === '.' ? '' : `${target.path}/`
5144
+ const selectedSources = targetSourceSets.get(target.name)
5145
+ const excludedPaths = targetExcludeFullSets.get(target.name)
5146
+ const nestedPrefixes: string[] = []
5147
+ for (const candidate of targets) {
5148
+ if (
5149
+ candidate.name !== target.name &&
5150
+ candidate.path !== '.' &&
5151
+ candidate.path.startsWith(prefix)
5152
+ )
5153
+ nestedPrefixes.push(`${candidate.path}/`)
5154
+ }
4960
5155
  // targets may share a directory and pick their compiled files with `sources`;
4961
5156
  // swiftpm leaves every header on disk for relative includes
4962
- return Object.entries(input.files).filter(
4963
- ([file]) =>
4964
- file.startsWith(prefix) &&
4965
- (target.sources === undefined ||
4966
- !(file.endsWith('.swift') || isSwiftNativeTranslationUnit(file)) ||
4967
- target.sources.some((source) => {
4968
- const selected = path.posix.join(prefix, source)
4969
- return file === selected || file.startsWith(`${selected}/`)
4970
- })) &&
4971
- !target.exclude?.some(
4972
- (excluded) =>
4973
- file === `${prefix}${excluded}` || file.startsWith(`${prefix}${excluded}/`),
4974
- ) &&
4975
- !targets.some(
4976
- (candidate) =>
4977
- candidate.name !== target.name &&
4978
- candidate.path !== '.' &&
4979
- candidate.path.startsWith(prefix) &&
4980
- file.startsWith(`${candidate.path}/`),
4981
- ),
4982
- )
5157
+ const matched = (entriesByPrefix.get(prefix) ?? []).filter(([file]) => {
5158
+ if (
5159
+ selectedSources !== undefined &&
5160
+ (file.endsWith('.swift') || isSwiftNativeTranslationUnit(file)) &&
5161
+ !matchesPathPrefixSet(file, selectedSources)
5162
+ )
5163
+ return false
5164
+ if (excludedPaths !== undefined && matchesPathPrefixSet(file, excludedPaths))
5165
+ return false
5166
+ if (nestedPrefixes.length > 0 && nestedPrefixes.some((p) => file.startsWith(p)))
5167
+ return false
5168
+ return true
5169
+ })
5170
+ targetEntriesCache.set(target.name, matched)
5171
+ return matched
4983
5172
  }
4984
5173
  const failTargetPreparation = (target: SwiftPackageTarget, message: string) => {
4985
5174
  const prefix = target.path === '.' ? '' : `${target.path}/`
@@ -5031,16 +5220,17 @@ export function writeSwiftProject(
5031
5220
  return value
5032
5221
  }
5033
5222
  const podHeaders = new Map<string, { owner: string; content: unknown }[]>()
5034
- for (const settings of input.nativeTargets ?? [])
5223
+ for (const settings of nativeTargets)
5035
5224
  for (const file of settings.headers) {
5036
5225
  const owner = /\/Headers\/(?:Public|Private)\/([\w+-]+)\/(?:\1\/)?[^/]+\.h$/.exec(
5037
5226
  file,
5038
5227
  )?.[1]
5039
- if (owner)
5040
- podHeaders.set(path.basename(file), [
5041
- ...(podHeaders.get(path.basename(file)) ?? []),
5042
- { owner, content: input.files[file] },
5043
- ])
5228
+ if (owner) {
5229
+ const base = path.basename(file)
5230
+ let list = podHeaders.get(base)
5231
+ if (!list) podHeaders.set(base, (list = []))
5232
+ list.push({ owner, content: input.files[file] })
5233
+ }
5044
5234
  }
5045
5235
  const podHeaderOwner = (file: string, content: unknown): string | undefined =>
5046
5236
  /\/Headers\/(?:Public|Private)\/([\w+-]+)\//.exec(file)?.[1] ??
@@ -5049,7 +5239,8 @@ export function writeSwiftProject(
5049
5239
  // headers keep their original project paths. an xcode target's product
5050
5240
  // headers additionally occupy the flat Module/Header.h namespace it
5051
5241
  // publishes; a swiftpm target's stay under its public headers directory.
5052
- for (const settings of input.nativeTargets ?? []) {
5242
+ const alreadySynced = new Map<string, string | Buffer>()
5243
+ for (const settings of nativeTargets) {
5053
5244
  for (const file of settings.headers) {
5054
5245
  const destination = path.join(layout.root, file)
5055
5246
  if (files.has(destination)) continue
@@ -5080,12 +5271,12 @@ export function writeSwiftProject(
5080
5271
  )
5081
5272
  : rawContents
5082
5273
  writeBuildFile(destination, contents)
5274
+ alreadySynced.set(destination, contents)
5083
5275
  files.set(destination, contents)
5084
5276
  }
5085
5277
  }
5086
5278
  // xcode's header maps and product header overlay, naming the headers
5087
5279
  // written above, bound into every clang command of their target.
5088
- const nativeTargets = input.nativeTargets ?? []
5089
5280
  const fromInputRoot = (file: string) =>
5090
5281
  file.startsWith(`${SWIFT_NATIVE_INPUT_ROOT}/`)
5091
5282
  ? path.join(layout.root, file.slice(SWIFT_NATIVE_INPUT_ROOT.length + 1))
@@ -5170,21 +5361,18 @@ export function writeSwiftProject(
5170
5361
  const prefix = target.path === '.' ? '' : `${target.path}/`
5171
5362
  const entries = targetEntries(target)
5172
5363
  const units = entries.filter(([file]) => isSwiftNativeTranslationUnit(file))
5364
+ const settings = nativeTargetByName.get(target.name)
5173
5365
  if (
5174
5366
  units.length === 0 &&
5175
5367
  !(
5176
5368
  entries.some(([file]) => file.endsWith('.swift')) &&
5177
- input.nativeTargets?.some(
5178
- (settings) =>
5179
- settings.name === target.name &&
5180
- (settings.publicHeaders.length > 0 || settings.bridgingHeader !== null),
5181
- )
5369
+ settings !== undefined &&
5370
+ (settings.publicHeaders.length > 0 || settings.bridgingHeader !== null)
5182
5371
  )
5183
5372
  )
5184
5373
  continue
5185
5374
  const includes = `${prefix}include/`
5186
5375
  // a quoted include may name a file relative to a declared header search path
5187
- const settings = input.nativeTargets?.find((value) => value.name === target.name)
5188
5376
  const searchRoots = [
5189
5377
  ...(settings?.userHeaderSearchPaths ?? []),
5190
5378
  ...(settings?.headerSearchPaths ?? []),
@@ -5221,7 +5409,9 @@ export function writeSwiftProject(
5221
5409
  ...searchRoots.map((root) => path.posix.join(root, include)),
5222
5410
  ].find((candidate) => input.files[candidate] !== undefined)
5223
5411
  if (local) {
5224
- reverse.set(local, [...(reverse.get(local) ?? []), file])
5412
+ let parents = reverse.get(local)
5413
+ if (!parents) reverse.set(local, (parents = []))
5414
+ parents.push(file)
5225
5415
  if (xcodeTarget && !seenHeaders.has(local)) {
5226
5416
  seenHeaders.add(local)
5227
5417
  searchEntries.push([local, input.files[local]!])
@@ -5283,9 +5473,11 @@ export function writeSwiftProject(
5283
5473
  .replaceAll(SWIFT_NATIVE_INPUT_ROOT, layout.root)
5284
5474
  .replaceAll(SWIFT_NATIVE_SDK_INCLUDE, sdkInclude),
5285
5475
  )
5476
+ const settingsHeaderFlags =
5477
+ headerSearch.flags[nativeTargetIndex.get(settings.name)!]!
5286
5478
  const originalFlags = [
5287
5479
  ...settings.flags,
5288
- ...headerSearch.flags[nativeTargets.indexOf(settings)]!,
5480
+ ...settingsHeaderFlags,
5289
5481
  ...search,
5290
5482
  ...(settings?.frameworkSearchPaths ?? []).flatMap((dir) => [
5291
5483
  '-F',
@@ -5305,7 +5497,7 @@ export function writeSwiftProject(
5305
5497
  const importOriginalFlags = settings.flattensPublicHeaders
5306
5498
  ? [
5307
5499
  ...settings.importerFlags,
5308
- ...headerSearch.flags[nativeTargets.indexOf(settings)]!,
5500
+ ...settingsHeaderFlags,
5309
5501
  ...search,
5310
5502
  ...settings.frameworkSearchPaths.flatMap((dir) => [
5311
5503
  '-F',
@@ -5331,7 +5523,7 @@ export function writeSwiftProject(
5331
5523
  }
5332
5524
  return [
5333
5525
  ...kept,
5334
- ...headerSearch.flags[nativeTargets.indexOf(settings)]!,
5526
+ ...settingsHeaderFlags,
5335
5527
  ...search,
5336
5528
  ...(settings?.frameworkSearchPaths ?? []).flatMap((dir) => [
5337
5529
  '-F',
@@ -5369,9 +5561,7 @@ export function writeSwiftProject(
5369
5561
  : swiftObjCResourceBundleName({
5370
5562
  target: target.name,
5371
5563
  path: target.path,
5372
- resources:
5373
- resourceTargets.find((candidate) => candidate.name === target.name)
5374
- ?.resources ?? false,
5564
+ resources: resourceTargetByName.get(target.name)?.resources ?? false,
5375
5565
  usesBundleMacro: entries.some(
5376
5566
  ([file, contents]) =>
5377
5567
  (isSwiftNativeTranslationUnit(file) ||
@@ -5587,10 +5777,7 @@ export function writeSwiftProject(
5587
5777
  ...(/\.mm?$/.test(file) ? ['-fobjc-exceptions'] : []),
5588
5778
  ...stageFlags(
5589
5779
  [...(objcCxx ? settings.cxxFlags : []), ...fileFlags],
5590
- path.join(
5591
- swiftSdkPaths(moduleRoot, toolchainBin).sysroot,
5592
- 'darwin/usr/include',
5593
- ),
5780
+ sdkInclude,
5594
5781
  ),
5595
5782
  ]
5596
5783
  const moduleFlag = perFile.some((flag) => flag.startsWith('-fmodule-name='))
@@ -5637,13 +5824,7 @@ export function writeSwiftProject(
5637
5824
  ...flags,
5638
5825
  ...prefixHeader,
5639
5826
  ...accessorFlags,
5640
- ...stageFlags(
5641
- cxx ? settings.cxxFlags : [],
5642
- path.join(
5643
- swiftSdkPaths(moduleRoot, toolchainBin).sysroot,
5644
- 'darwin/usr/include',
5645
- ),
5646
- ),
5827
+ ...stageFlags(cxx ? settings.cxxFlags : [], sdkInclude),
5647
5828
  ...perFile,
5648
5829
  ...moduleFlag,
5649
5830
  ],
@@ -5948,10 +6129,9 @@ export function writeSwiftProject(
5948
6129
  ? `extern module ${moduleName} ${JSON.stringify(originalPath)}\nmodule ${moduleName}.Swift {\n header ${JSON.stringify(path.join(headerDirectory, name + '-Swift.h'))}\n requires objc\n}\n`
5949
6130
  : swiftObjCModuleMap(
5950
6131
  moduleName,
5951
- (
5952
- input.nativeTargets?.find((target) => target.name === name)
5953
- ?.publicHeaders ?? []
5954
- ).map((header) => path.join(layout.root, header)),
6132
+ (nativeTargetByName.get(name)?.publicHeaders ?? []).map((header) =>
6133
+ path.join(layout.root, header),
6134
+ ),
5955
6135
  submoduleImports.get(moduleName),
5956
6136
  path.join(headerDirectory, name + '-Swift.h'),
5957
6137
  ),
@@ -6637,6 +6817,7 @@ export function writeSwiftProject(
6637
6817
  files.set(destination, Buffer.from(bytes, 'base64'))
6638
6818
  }
6639
6819
  const targetToolset = nativeToolset || native.size > 0
6820
+ let usesObjcPrebuilt = false
6640
6821
  if (targetToolset) {
6641
6822
  const nativeToolsetFlags = [
6642
6823
  ...headerAliasFlags,
@@ -6669,6 +6850,7 @@ export function writeSwiftProject(
6669
6850
  objcPrebuiltStage,
6670
6851
  )
6671
6852
  : []
6853
+ usesObjcPrebuilt = prebuiltCompiler.length > 0
6672
6854
  files.set(
6673
6855
  clangWrapper,
6674
6856
  [
@@ -7001,16 +7183,41 @@ export function writeSwiftProject(
7001
7183
  (name) => !nativePrerequisiteSet.has(name),
7002
7184
  )
7003
7185
  const nativeTargetUnitCount = new Map<string, number>()
7186
+ const nativeTargetSources = new Map<string, readonly string[]>()
7004
7187
  for (const target of manifestTargets)
7005
- if (target.sources?.length)
7188
+ if (target.sources?.length) {
7006
7189
  nativeTargetUnitCount.set(target.name, target.sources.length)
7190
+ nativeTargetSources.set(target.name, target.sources)
7191
+ }
7007
7192
  for (const [name, plan] of native) {
7008
- if (!plan.mixed && plan.sources.length > 0)
7009
- nativeTargetUnitCount.set(name, plan.clang?.sources.length ?? plan.sources.length)
7010
- for (const group of plan.groups ?? [])
7193
+ if (!plan.mixed && plan.sources.length > 0) {
7194
+ const sources = plan.clang?.sources ?? plan.sources
7195
+ nativeTargetUnitCount.set(name, sources.length)
7196
+ nativeTargetSources.set(name, sources)
7197
+ }
7198
+ for (const group of plan.groups ?? []) {
7011
7199
  nativeTargetUnitCount.set(group.name, group.sources.length)
7012
- if (plan.late && !plan.groups?.length)
7200
+ nativeTargetSources.set(group.name, group.sources)
7201
+ }
7202
+ if (plan.late && !plan.groups?.length) {
7013
7203
  nativeTargetUnitCount.set(plan.late.name, plan.sources.length)
7204
+ nativeTargetSources.set(plan.late.name, plan.lateSources)
7205
+ }
7206
+ }
7207
+ const nativeStageObjects = new Map<string, readonly string[]>()
7208
+ const recordStageObjects = (
7209
+ stageTarget: string,
7210
+ members: readonly string[],
7211
+ ): string => {
7212
+ const objects: string[] = []
7213
+ for (const member of members) {
7214
+ const sources = nativeTargetSources.get(member)
7215
+ if (!sources || sources.length === 0) return stageTarget
7216
+ for (const source of sources)
7217
+ objects.push(path.join(`${member}.build`, `${source}.o`))
7218
+ }
7219
+ nativeStageObjects.set(stageTarget, objects)
7220
+ return stageTarget
7014
7221
  }
7015
7222
  // bound each native product stage so llbuild commits build.db every few hundred
7016
7223
  // translation units instead of rolling back a whole multi-target native pass on timeout.
@@ -7022,7 +7229,7 @@ export function writeSwiftProject(
7022
7229
  0,
7023
7230
  )
7024
7231
  if (names.length === 1 || total <= MAX_NATIVE_STAGE_UNITS)
7025
- return [buildProduct(prefix, names)]
7232
+ return [recordStageObjects(buildProduct(prefix, names), names)]
7026
7233
  const chunks: string[][] = []
7027
7234
  let current: string[] = []
7028
7235
  let count = 0
@@ -7037,7 +7244,9 @@ export function writeSwiftProject(
7037
7244
  count += size
7038
7245
  }
7039
7246
  if (current.length > 0) chunks.push(current)
7040
- return chunks.map((members, index) => buildProduct(`${prefix}${index + 1}`, members))
7247
+ return chunks.map((members, index) =>
7248
+ recordStageObjects(buildProduct(`${prefix}${index + 1}`, members), members),
7249
+ )
7041
7250
  }
7042
7251
  const nativePrerequisiteStageTargets = chunkNativeStageTargets(
7043
7252
  'PeachHeaderNativePrereqs',
@@ -7048,7 +7257,7 @@ export function writeSwiftProject(
7048
7257
  remainingNativeBuildTargets,
7049
7258
  )
7050
7259
  files.set(manifestPath, manifest)
7051
- syncSwiftTree(layout.root, files)
7260
+ syncSwiftTree(layout.root, files, alreadySynced)
7052
7261
  // a header-only clang module compiles nothing, and swiftpm still needs its directory
7053
7262
  if (layout.multi)
7054
7263
  for (const target of targets)
@@ -7070,6 +7279,8 @@ export function writeSwiftProject(
7070
7279
  generatedOwners,
7071
7280
  targetToolset,
7072
7281
  headerCompiler,
7282
+ usesObjcPrebuilt,
7283
+ nativeStageObjects,
7073
7284
  }
7074
7285
  }
7075
7286
 
@@ -8527,22 +8738,24 @@ async function compileSwiftProjectOnce(
8527
8738
  work,
8528
8739
  unoptimized,
8529
8740
  )
8530
- const baseBuildEnv = {
8531
- ...(options.project?.env ?? process.env),
8532
- // shipped host plugins resolve against the selected compiler's runtime.
8533
- ...(process.platform === 'linux'
8534
- ? {
8535
- LD_LIBRARY_PATH: [
8536
- path.resolve(options.toolchainBin, '../lib/swift/linux'),
8537
- path.resolve(options.toolchainBin, '../lib/swift/host'),
8538
- process.env.LD_LIBRARY_PATH,
8539
- ]
8540
- .filter(Boolean)
8541
- .join(':'),
8542
- }
8543
- : {}),
8544
- PEACH_DEFER_WASM_LINK: '1',
8545
- }
8741
+ const baseBuildEnv = options.project?.env
8742
+ ? {
8743
+ ...options.project.env,
8744
+ // shipped host plugins resolve against the selected compiler's runtime.
8745
+ ...(process.platform === 'linux'
8746
+ ? {
8747
+ LD_LIBRARY_PATH: [
8748
+ path.resolve(options.toolchainBin, '../lib/swift/linux'),
8749
+ path.resolve(options.toolchainBin, '../lib/swift/host'),
8750
+ process.env.LD_LIBRARY_PATH,
8751
+ ]
8752
+ .filter(Boolean)
8753
+ .join(':'),
8754
+ }
8755
+ : {}),
8756
+ PEACH_DEFER_WASM_LINK: '1',
8757
+ }
8758
+ : swiftCompilerBaseEnv(options.toolchainBin, process.env)
8546
8759
  // hold the exclusive framework slot lock only while staging and
8547
8760
  // building framework products; take a shared read hold before
8548
8761
  // releasing it so other builds on the same framework revision
@@ -8727,7 +8940,14 @@ async function compileSwiftProjectOnce(
8727
8940
  : {
8728
8941
  ...buildOptions,
8729
8942
  temporaryDirectory,
8730
- env: { ...buildOptions.env, ...compiler },
8943
+ env: {
8944
+ ...buildOptions.env,
8945
+ ...(preparation.usesObjcPrebuilt &&
8946
+ process.env.PEACH_HOME !== undefined
8947
+ ? { PEACH_HOME: process.env.PEACH_HOME }
8948
+ : {}),
8949
+ ...compiler,
8950
+ },
8731
8951
  }
8732
8952
  const unprepared = preparation.targetFailures.map(
8733
8953
  (failure) => `error: target ${failure}`,
@@ -8790,12 +9010,20 @@ async function compileSwiftProjectOnce(
8790
9010
  // the mirror finds a changed sdk header's readers in their
8791
9011
  // dependency files, which omit system headers by default
8792
9012
  ...(mirrorDistribution ? ['-Xswiftc', '-track-system-dependencies'] : []),
8793
- // the link strips debug info, so none is generated (as for the framework)
9013
+ // the link strips debug info, so none is generated (as for the framework).
9014
+ // keep -num-threads fixed across caller core caps so llbuild does not
9015
+ // rebuild every target when callers alternate --cores, and bound backend
9016
+ // fan-out under high -j.
8794
9017
  '-Xswiftc',
8795
9018
  '-gnone',
8796
9019
  ...(incrementalPreview
8797
9020
  ? []
8798
- : ['-Xswiftc', '-num-threads', '-Xswiftc', String(perFile ? 1 : jobs)]),
9021
+ : [
9022
+ '-Xswiftc',
9023
+ '-num-threads',
9024
+ '-Xswiftc',
9025
+ String(perFile ? 1 : Math.min(8, os.availableParallelism())),
9026
+ ]),
8799
9027
  ...swiftReproducibleBuildFlags([
8800
9028
  [path.dirname(options.toolchainBin), 'toolchain'],
8801
9029
  [compileFrameworkRoot, 'framework'],
@@ -9008,7 +9236,25 @@ async function compileSwiftProjectOnce(
9008
9236
  })),
9009
9237
  ]
9010
9238
  const checkpoints = path.join(root, '.build', 'peach-product-checkpoints')
9239
+ const buildDbExists = existsSync(path.join(root, '.build', 'build.db'))
9240
+ const releaseDir = path.dirname(linked)
9011
9241
  for (const { target, producers } of stages) {
9242
+ // pure native checkpoint stages exist only to commit build.db on cold
9243
+ // builds; when build.db and all stage objects are already warm, the
9244
+ // header stage and final full-graph build still validate every input.
9245
+ if (!options.project && producers.length === 0 && buildDbExists) {
9246
+ const expectedObjects = preparation.nativeStageObjects.get(target)
9247
+ if (
9248
+ expectedObjects &&
9249
+ expectedObjects.length > 0 &&
9250
+ expectedObjects.every((relative) =>
9251
+ statSync(path.join(releaseDir, relative), {
9252
+ throwIfNoEntry: false,
9253
+ })?.isFile(),
9254
+ )
9255
+ )
9256
+ continue
9257
+ }
9012
9258
  const receipt = path.join(
9013
9259
  checkpoints,
9014
9260
  createHash('sha256').update(target).digest('hex'),