peachsim 0.1.2605 → 0.1.2607

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 (147) hide show
  1. package/cli/commands/package.ts +71 -39
  2. package/cli/commands/perf-native.ts +259 -6
  3. package/cli/commands/shell-url.ts +1 -0
  4. package/dist-lib/agent-daemon-client.cjs +1 -1
  5. package/dist-lib/agent-events.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +2 -2
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +5 -5
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +3 -3
  16. package/dist-lib/bundle-channel.cjs +1520 -932
  17. package/dist-lib/capture-contract.cjs +1 -1
  18. package/dist-lib/capture-contract.mjs +3 -3
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +3 -3
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +2 -2
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +7 -7
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/config.mjs +5 -5
  27. package/dist-lib/detox/index.cjs +1 -1
  28. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  29. package/dist-lib/esm-chunks/{acorn-UNOYFUKI.mjs → acorn-KFWXYMX5.mjs} +3 -3
  30. package/dist-lib/esm-chunks/{chunk-WSRPZF7M.mjs → chunk-6JPUMAC2.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-M4G5YUO7.mjs → chunk-6NDABMDX.mjs} +3 -3
  32. package/dist-lib/esm-chunks/{chunk-GT54N3GG.mjs → chunk-7SKDPTZN.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-FXONOT2L.mjs → chunk-ACAXWH62.mjs} +1 -1
  34. package/dist-lib/esm-chunks/chunk-ARYRQJUB.mjs +326 -0
  35. package/dist-lib/esm-chunks/{chunk-WB2EBX5Q.mjs → chunk-BNAXRY5Q.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-AST6VA7D.mjs → chunk-CA64UUHF.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-B54SPDLA.mjs → chunk-DBW62F4N.mjs} +3 -2
  38. package/dist-lib/esm-chunks/{chunk-7K33ENH6.mjs → chunk-ESS2CG5G.mjs} +5 -5
  39. package/dist-lib/esm-chunks/{chunk-LFN7VAPB.mjs → chunk-IGSLOAPL.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-RJCM34J7.mjs → chunk-KIIALACX.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-YO756PYQ.mjs → chunk-LJZ373SO.mjs} +819 -681
  42. package/dist-lib/esm-chunks/{chunk-VRQPEROV.mjs → chunk-M4ORY3NH.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-3XUIDCBF.mjs → chunk-MBWWOGI5.mjs} +4 -4
  44. package/dist-lib/esm-chunks/{chunk-M3V4F5OV.mjs → chunk-O5BPZVLB.mjs} +5 -5
  45. package/dist-lib/esm-chunks/chunk-P5Q5QCTP.mjs +32 -0
  46. package/dist-lib/esm-chunks/{chunk-O55DZ2EL.mjs → chunk-QJUAWJDB.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-HHS4A7GI.mjs → chunk-RIDXKGBZ.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-LG76KUUO.mjs → chunk-TD2DBEKQ.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-AYHTHFG4.mjs → chunk-UTSB5CDG.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-UPUOCALX.mjs → chunk-WMWOBH7E.mjs} +1 -1
  51. package/dist-lib/esm-chunks/{chunk-6TE7WLSF.mjs → chunk-ZNGLVJYL.mjs} +1 -1
  52. package/dist-lib/esm-chunks/{metro-layout-parser-YRBZCLVD.mjs → metro-layout-parser-UY3B6VGU.mjs} +3 -3
  53. package/dist-lib/esm-chunks/{swift-package-prebuilt-S7KR6TKE.mjs → swift-package-prebuilt-HDHPWS44.mjs} +10 -10
  54. package/dist-lib/esm-chunks/{swift-sdk-app-module-3JNA7PCB.mjs → swift-sdk-app-module-U6G5RZV2.mjs} +14 -14
  55. package/dist-lib/esm-chunks/{swift-sdk-image-3P4IUP2A.mjs → swift-sdk-image-PVDA2MVM.mjs} +14 -14
  56. package/dist-lib/esm-chunks/{swift-sdk-image-producer-EA2RYBM4.mjs → swift-sdk-image-producer-YHPS3KNR.mjs} +4 -4
  57. package/dist-lib/expo-swift-bundle.cjs +1519 -931
  58. package/dist-lib/expo-swift-metadata.cjs +1 -1
  59. package/dist-lib/expo-swift-metadata.mjs +7 -7
  60. package/dist-lib/home-paths.cjs +1 -1
  61. package/dist-lib/host/bridge-host.cjs +1677 -947
  62. package/dist-lib/host/fetch-proxy-handler.cjs +44 -37
  63. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  64. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  65. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  66. package/dist-lib/host/websocket-proxy.cjs +1 -1
  67. package/dist-lib/index.cjs +1 -1
  68. package/dist-lib/kotlin-host.cjs +1 -1
  69. package/dist-lib/menu.cjs +1 -1
  70. package/dist-lib/menu.mjs +3 -3
  71. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  72. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  73. package/dist-lib/metro-production-bundle.cjs +1 -1
  74. package/dist-lib/metro-production-bundle.mjs +4 -4
  75. package/dist-lib/native-app-identity-project.cjs +540 -247
  76. package/dist-lib/native-app-identity-project.mjs +218 -1828
  77. package/dist-lib/native-app-identity.cjs +1 -1
  78. package/dist-lib/native-app-identity.mjs +6 -6
  79. package/dist-lib/native-firebase-metadata.cjs +1 -1
  80. package/dist-lib/native-firebase-metadata.mjs +3 -3
  81. package/dist-lib/pdfium-raster.cjs +1 -1
  82. package/dist-lib/pdfium-raster.mjs +2 -2
  83. package/dist-lib/plist.cjs +327 -15
  84. package/dist-lib/plist.mjs +13 -5
  85. package/dist-lib/profiles.cjs +1 -1
  86. package/dist-lib/public-brand.cjs +1 -1
  87. package/dist-lib/public-origins-lib-esm.json +82 -129
  88. package/dist-lib/public-origins-lib.json +69 -140
  89. package/dist-lib/react-native-host-modules.cjs +1 -1
  90. package/dist-lib/react-native-host-modules.mjs +2 -2
  91. package/dist-lib/reap-browser.cjs +1 -1
  92. package/dist-lib/scripts/dev-server-scanner.cjs +211 -3
  93. package/dist-lib/sdk.cjs +1 -1
  94. package/dist-lib/sdk.mjs +8 -8
  95. package/dist-lib/skills.cjs +1693 -963
  96. package/dist-lib/swift-compile.cjs +812 -673
  97. package/dist-lib/swift-compile.mjs +10 -10
  98. package/dist-lib/swift-package.cjs +1 -1
  99. package/dist-lib/swift-package.mjs +3 -3
  100. package/dist-lib/swift-submit.cjs +1 -1
  101. package/dist-lib/swift-submit.mjs +6 -6
  102. package/dist-lib/swift-svg-raster.cjs +1 -1
  103. package/dist-lib/swift-svg-raster.mjs +2 -2
  104. package/dist-lib/swift-toolchain.cjs +3 -2
  105. package/dist-lib/swift.cjs +1 -1
  106. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  108. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  109. package/dist-lib/vendor/acorn.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/stream-json.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase.cjs +1 -1
  117. package/dist-lib/vendor/terser.cjs +1 -1
  118. package/dist-lib/vendor/valibot.cjs +1 -1
  119. package/dist-lib/vendor/ws.cjs +1 -1
  120. package/dist-lib/vendor/zod.cjs +1 -1
  121. package/dist-lib/worklet-executable.cjs +1 -1
  122. package/dist-lib/worklet-executable.mjs +3 -3
  123. package/dist-types/packages/peach-engine/src/ios/apps/canvas-map-data.d.ts +38 -2
  124. package/dist-types/packages/peach-globals/src/canvasAgentContract.d.ts +8 -0
  125. package/dist-types/packages/peach-globals/src/index.d.ts +1 -1
  126. package/package.json +1 -6
  127. package/src/agent-prompt.ts +5 -1
  128. package/src/bazel-project.ts +1 -1
  129. package/src/expo-native-prebuilt.ts +1 -1
  130. package/src/expo-workspace-exclusion.ts +1 -1
  131. package/src/gitignore.ts +175 -0
  132. package/src/intent-definition/plist-reader.ts +22 -168
  133. package/src/one-native-controls-package.ts +143 -1
  134. package/src/oneNativeControlsContract.ts +1 -0
  135. package/src/plist-bytes.ts +144 -2
  136. package/src/plist.ts +359 -2
  137. package/src/swift-compile-budget.ts +28 -7
  138. package/src/swift-compile.ts +972 -809
  139. package/src/swift-guest-compile.ts +3 -0
  140. package/src/swift-toolchain.ts +4 -1
  141. package/src/xcode-project.ts +1 -1
  142. package/dist-lib/esm-chunks/chunk-OW4VRQKO.mjs +0 -10993
  143. package/dist-lib/esm-chunks/chunk-ZSHGFGW7.mjs +0 -65
  144. package/dist-lib/vendor/@xmldom/xmldom.cjs +0 -6481
  145. package/dist-lib/vendor/bplist-parser.cjs +0 -1589
  146. package/dist-lib/vendor/ignore.cjs +0 -455
  147. package/dist-lib/vendor/plist.cjs +0 -10978
@@ -208,6 +208,7 @@ export {
208
208
  // `stream` echoes the output as it arrives: all of it, or only matching lines.
209
209
  // a successful run then echoes the rest minus lines matching `quiet`, its
210
210
  // warnings; a failed run's output goes to the caller's one diagnostic.
211
+ // `timeout` bounds silence: each output chunk restarts it and calls `onOutput`.
211
212
  async function runCompiler(
212
213
  command: string,
213
214
  args: string[],
@@ -218,6 +219,7 @@ async function runCompiler(
218
219
  temporaryDirectory?: string
219
220
  /** applied over the confined scratch environment, for a child that cannot use the host's. */
220
221
  confined?: Record<string, string>
222
+ onOutput?: () => void
221
223
  },
222
224
  stream: boolean | RegExp = false,
223
225
  quiet?: RegExp,
@@ -253,8 +255,18 @@ async function runCompiler(
253
255
  // close and cancellation share the same awaited cleanup below.
254
256
  void stopping.catch(() => {})
255
257
  }
258
+ const restartTimeout = () => {
259
+ if (!options.timeout) return
260
+ clearTimeout(timeout)
261
+ timeout = setTimeout(() => {
262
+ failure = new Error(`Swift compiler was silent for ${options.timeout}ms`)
263
+ stop()
264
+ }, options.timeout)
265
+ }
256
266
  for (const name of ['stdout', 'stderr'] as const) {
257
267
  child[name].on('data', (bytes: Buffer) => {
268
+ restartTimeout()
269
+ options.onOutput?.()
258
270
  if (stream === true) process[name].write(bytes)
259
271
  else if (stream) {
260
272
  const lines = (partial[name] + bytes.toString()).split('\n')
@@ -302,11 +314,7 @@ async function runCompiler(
302
314
  resolve(Buffer.concat(chunks.stdout).toString())
303
315
  }
304
316
  })
305
- if (options.timeout)
306
- timeout = setTimeout(() => {
307
- failure = new Error('Swift compiler timed out')
308
- stop()
309
- }, options.timeout)
317
+ restartTimeout()
310
318
  if (signal?.aborted) stop()
311
319
  })
312
320
  } finally {
@@ -5015,7 +5023,6 @@ export function writeSwiftProject(
5015
5023
  (left, right) => right.path.length - left.path.length,
5016
5024
  )
5017
5025
  const targetsByDir = indexTargetsByDirectory(bySourcePath)
5018
- const targetByName = new Map(targets.map((target) => [target.name, target]))
5019
5026
  const nativeTargets = input.nativeTargets ?? []
5020
5027
  const nativeTargetByName = new Map(nativeTargets.map((target) => [target.name, target]))
5021
5028
  const nativeTargetIndex = new Map(
@@ -5099,10 +5106,6 @@ export function writeSwiftProject(
5099
5106
  checkedToolchain = swiftToolchain(pin.release, swiftModuleSdk(moduleRoot))
5100
5107
  return checkedToolchain
5101
5108
  }
5102
- const deploymentTarget = (name: string) =>
5103
- nativeTargetByName.get(name)?.deploymentTarget ??
5104
- targetByName.get(name)?.iosDeploymentTarget ??
5105
- null
5106
5109
  const targetStagedFiles = new Map<string, Map<string, string | Buffer | undefined>>()
5107
5110
  const stageTargetFile = (
5108
5111
  target: string,
@@ -6476,7 +6479,10 @@ export function writeSwiftProject(
6476
6479
  }
6477
6480
  for (const target of targets) {
6478
6481
  if (!target.executable && !reachesNative(target.name)) continue
6479
- const version = deploymentTarget(target.name)
6482
+ const version =
6483
+ nativeTargetByName.get(target.name)?.deploymentTarget ??
6484
+ target.iosDeploymentTarget ??
6485
+ null
6480
6486
  const minimum = iosDeploymentMinimum(version)
6481
6487
  if (minimum === undefined)
6482
6488
  throw new Error(
@@ -7874,10 +7880,12 @@ type FrameworkBuildArgs = {
7874
7880
  signal?: AbortSignal
7875
7881
  lease?: SwiftRootLease
7876
7882
  frameworkLease?: SwiftRootLease
7883
+ onOutput?: () => void
7877
7884
  }
7878
7885
  }
7879
7886
 
7880
7887
  const frameworkProductsReceiptSchema = v.object({
7888
+ root: v.string(),
7881
7889
  modules: v.string(),
7882
7890
  objects: v.array(v.string()),
7883
7891
  lazyObjects: v.array(v.string()),
@@ -7904,25 +7912,18 @@ function readFrameworkProductsReceipt(
7904
7912
  } catch {
7905
7913
  return null
7906
7914
  }
7907
- const archive = path.join(scratch, 'lib')
7908
- const archiveStamp = path.join(archive, '.receipt')
7909
- const archiveMatches =
7910
- existsSync(archiveStamp) && readFileSync(archiveStamp, 'utf8') === receiptKey
7915
+ const archiveRoot = path.join(scratch, 'products-lib', receiptKey)
7916
+ if (parsed.root !== archiveRoot) return null
7911
7917
  if (!existsSync(parsed.modules)) return null
7912
- for (const [object] of parsed.archived) if (!existsSync(object)) return null
7918
+ for (const [object, rel] of parsed.archived) {
7919
+ if (!existsSync(object) || !existsSync(path.join(archiveRoot, rel))) return null
7920
+ }
7913
7921
  for (const file of parsed.providers) if (!existsSync(file)) return null
7914
7922
  for (const file of parsed.moduleMaps) if (!existsSync(file)) return null
7915
- if (!archiveMatches) {
7916
- rmSync(archive, { recursive: true, force: true })
7917
- mkdirSync(archive, { recursive: true })
7918
- for (const [object, rel] of parsed.archived)
7919
- symlinkSync(object, path.join(scratch, rel))
7920
- writeFileSync(archiveStamp, receiptKey)
7921
- }
7922
7923
  for (const file of parsed.objects) if (!existsSync(file)) return null
7923
7924
  for (const file of parsed.lazyObjects) if (!existsSync(file)) return null
7924
7925
  return {
7925
- root: scratch,
7926
+ root: parsed.root,
7926
7927
  modules: parsed.modules,
7927
7928
  objects: parsed.objects,
7928
7929
  lazyObjects: parsed.lazyObjects,
@@ -7945,7 +7946,7 @@ async function buildFrameworkProducts(
7945
7946
  const receiptKey = createHash('sha256')
7946
7947
  .update(
7947
7948
  JSON.stringify([
7948
- 'framework-products/v1',
7949
+ 'framework-products/v2',
7949
7950
  args.frameworkKey,
7950
7951
  unoptimized,
7951
7952
  args.sdk,
@@ -8132,33 +8133,47 @@ async function buildFrameworkProducts(
8132
8133
  // the framework objects link as a distribution's do: under lib/ with the names
8133
8134
  // build-distribution.ts gives them, Objective-C roots whole and the rest as an
8134
8135
  // archive region the pruner trims (swift-wasm-prune.ts reads <root>/lib).
8136
+ // each receipt owns an immutable archive root so simultaneous apps with
8137
+ // different linked product sets never delete or relink a reader's lib/.
8135
8138
  // Darwin stays whole: a distribution leaves it to the sdk's image.
8136
- const archive = path.join(scratch, 'lib')
8137
- rmSync(archive, { recursive: true, force: true })
8138
- mkdirSync(archive)
8139
+ const archiveBase = path.join(scratch, 'products-lib')
8140
+ mkdirSync(archiveBase, { recursive: true })
8141
+ const archiveRoot = path.join(archiveBase, receiptKey)
8142
+ const stagedArchiveRoot = `${archiveRoot}.tmp-${process.pid}-${randomUUID()}`
8143
+ const stagedArchive = path.join(stagedArchiveRoot, 'lib')
8144
+ mkdirSync(stagedArchive, { recursive: true })
8139
8145
  const archived = new Map<string, string>()
8140
- for (const object of objects) {
8141
- const target = linked.owners.get(object)
8142
- const dir = path.join(release, `${target}.build`)
8143
- if (!target || target === 'Darwin' || !object.startsWith(dir + path.sep)) continue
8144
- const name = `${target}-${path
8145
- .relative(dir, object)
8146
- .replaceAll(path.sep, '-')
8147
- .replace(/\.swift\.o$/, '.o')}`
8148
- symlinkSync(object, path.join(archive, name))
8149
- archived.set(object, `lib/${name}`)
8150
- }
8151
- const roots = swiftObjcRootObjects(`${scratch}\n${args.frameworkKey}`, scratch, [
8152
- ...archived.values(),
8153
- ])
8146
+ try {
8147
+ for (const object of objects) {
8148
+ const target = linked.owners.get(object)
8149
+ const dir = path.join(release, `${target}.build`)
8150
+ if (!target || target === 'Darwin' || !object.startsWith(dir + path.sep)) continue
8151
+ const name = `${target}-${path
8152
+ .relative(dir, object)
8153
+ .replaceAll(path.sep, '-')
8154
+ .replace(/\.swift\.o$/, '.o')}`
8155
+ symlinkSync(object, path.join(stagedArchive, name))
8156
+ archived.set(object, `lib/${name}`)
8157
+ }
8158
+ rmSync(archiveRoot, { recursive: true, force: true })
8159
+ renameSync(stagedArchiveRoot, archiveRoot)
8160
+ } catch (error) {
8161
+ rmSync(stagedArchiveRoot, { recursive: true, force: true })
8162
+ throw error
8163
+ }
8164
+ const roots = swiftObjcRootObjects(
8165
+ `${archiveRoot}\n${args.frameworkKey}`,
8166
+ archiveRoot,
8167
+ [...archived.values()],
8168
+ )
8154
8169
  const linkedObjects = objects.map((object) => {
8155
8170
  const name = archived.get(object)
8156
8171
  return name
8157
- ? { path: path.join(scratch, name), lazy: !roots.has(name) }
8172
+ ? { path: path.join(archiveRoot, name), lazy: !roots.has(name) }
8158
8173
  : { path: object, lazy: false }
8159
8174
  })
8160
8175
  const result: SwiftFrameworkProducts = {
8161
- root: scratch,
8176
+ root: archiveRoot,
8162
8177
  modules: path.join(release, 'Modules'),
8163
8178
  objects: linkedObjects.filter((object) => !object.lazy).map((object) => object.path),
8164
8179
  lazyObjects: linkedObjects
@@ -8170,7 +8185,6 @@ async function buildFrameworkProducts(
8170
8185
  moduleMaps: linked.moduleMaps,
8171
8186
  objcHeaders: linked.objcHeaders,
8172
8187
  }
8173
- writeFileSync(path.join(archive, '.receipt'), receiptKey)
8174
8188
  const receiptsDir = path.join(scratch, 'products-ready')
8175
8189
  mkdirSync(receiptsDir, { recursive: true })
8176
8190
  const receiptFile = path.join(receiptsDir, `${receiptKey}.json`)
@@ -8178,6 +8192,7 @@ async function buildFrameworkProducts(
8178
8192
  writeFileSync(
8179
8193
  partialReceipt,
8180
8194
  JSON.stringify({
8195
+ root: result.root,
8181
8196
  modules: result.modules,
8182
8197
  objects: result.objects,
8183
8198
  lazyObjects: result.lazyObjects,
@@ -8209,6 +8224,10 @@ const SWIFT_FRAMEWORK_SLOTS = 8
8209
8224
  const SWIFT_FRAMEWORK_UNOPTIMIZED_SLOTS = 4
8210
8225
  const SWIFT_FRAMEWORK_SLOT_KEY = '.peach-framework-key'
8211
8226
  const SWIFT_FRAMEWORK_SLOT_ORIGIN = '.peach-framework-origin'
8227
+ const SWIFT_FRAMEWORK_SLOT_RELEASE = '.peach-framework-release'
8228
+
8229
+ const SWIFT_BUILD_ROOT_SLOTS = 4
8230
+ const SWIFT_BUILD_ROOT_SHAPE = '.peach-build-shape'
8212
8231
 
8213
8232
  function swiftFrameworksDir(unoptimized = false): string {
8214
8233
  return path.join(
@@ -8230,8 +8249,13 @@ function swiftFrameworkSlotKey(slot: string): string | null {
8230
8249
  return swiftFrameworkSlotRecord(slot, SWIFT_FRAMEWORK_SLOT_KEY)
8231
8250
  }
8232
8251
 
8252
+ function swiftFrameworkSlotRelease(slot: string): string | null {
8253
+ return swiftFrameworkSlotRecord(slot, SWIFT_FRAMEWORK_SLOT_RELEASE)
8254
+ }
8255
+
8233
8256
  async function withSwiftFrameworkSlot<T>(
8234
8257
  frameworkKey: string,
8258
+ release: string,
8235
8259
  moduleRoot: string,
8236
8260
  signal: AbortSignal | undefined,
8237
8261
  work: (slot: string, lease: SwiftRootLease) => Promise<T>,
@@ -8263,12 +8287,18 @@ async function withSwiftFrameworkSlot<T>(
8263
8287
  readFileSync(path.join(moduleRoot, file)),
8264
8288
  ]),
8265
8289
  )
8266
- // a new builder workspace has no origin match; choose by source bytes so it
8267
- // inherits the nearest revision's products instead of an empty or old tree.
8290
+ // swiftc's swift-version hash invalidates every framework target when a slot
8291
+ // switches compiler release. keep each compiler release in its own slot:
8292
+ // tier 0 reuses a warm slot from the same release (nearest source revision),
8293
+ // tier 1 takes an empty slot, and tier 2 evicts another release only LRU when
8294
+ // all slots are full.
8268
8295
  const ranked = slots
8269
- .map((slot) => {
8296
+ .map((slot, index) => {
8297
+ const slotKey = swiftFrameworkSlotKey(slot)
8298
+ if (slotKey === null) return { slot, index, tier: 1, changes: Infinity }
8299
+ if (swiftFrameworkSlotRelease(slot) !== release)
8300
+ return { slot, index, tier: 2, changes: Infinity }
8270
8301
  let changes = 0
8271
- if (swiftFrameworkSlotKey(slot) === null) return { slot, changes: Infinity }
8272
8302
  const source = path.join(slot, 'source', 'packages', path.basename(moduleRoot))
8273
8303
  for (const [file, contents] of inputs) {
8274
8304
  try {
@@ -8283,22 +8313,27 @@ async function withSwiftFrameworkSlot<T>(
8283
8313
  changes++
8284
8314
  }
8285
8315
  }
8286
- return { slot, changes }
8316
+ return { slot, index, tier: 0, changes }
8287
8317
  })
8288
- .sort(
8289
- (left, right) =>
8290
- left.changes - right.changes ||
8291
- Number(own(right.slot)) - Number(own(left.slot)) ||
8292
- (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0),
8293
- )
8294
- for (const { slot, changes } of ranked) {
8318
+ .sort((left, right) => {
8319
+ if (left.tier !== right.tier) return left.tier - right.tier
8320
+ if (left.tier === 0)
8321
+ return (
8322
+ left.changes - right.changes ||
8323
+ Number(own(right.slot)) - Number(own(left.slot)) ||
8324
+ (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0)
8325
+ )
8326
+ if (left.tier === 1) return left.index - right.index
8327
+ return (built.get(left.slot) ?? 0) - (built.get(right.slot) ?? 0)
8328
+ })
8329
+ for (const { slot, tier, changes } of ranked) {
8295
8330
  if (await hasLiveSwiftRootReaders(slot, signal)) continue
8296
8331
  const result = await withSwiftRootLock(
8297
8332
  slot,
8298
8333
  async (lease) => {
8299
8334
  if (await hasLiveSwiftRootReaders(slot, signal)) return undefined
8300
8335
  console.error(
8301
- `[swift-framework-cache] ${path.basename(slot)} changedInputs=${changes} totalInputs=${inputs.size}`,
8336
+ `[swift-framework-cache] ${path.basename(slot)} release=${release} tier=${tier} changedInputs=${changes} totalInputs=${inputs.size}`,
8302
8337
  )
8303
8338
  return { value: await run(slot)(lease) }
8304
8339
  },
@@ -8311,6 +8346,56 @@ async function withSwiftFrameworkSlot<T>(
8311
8346
  return withSwiftRootLock(nearest, run(nearest), signal)
8312
8347
  }
8313
8348
 
8349
+ // normalized shared build roots (such as OneNativeControls) serve concurrent
8350
+ // callers with different inputs or target shapes. callers hold the per-hash
8351
+ // sharedRoot lock before entering here so identical concurrent builds never
8352
+ // race onto two slots, while distinct hashes claim idle matching or empty
8353
+ // slots without blocking or thrashing each other's incremental objects.
8354
+ async function withSwiftBuildRootSlot<T>(
8355
+ baseRoot: string,
8356
+ buildShape: string,
8357
+ signal: AbortSignal | undefined,
8358
+ work: (slotRoot: string, lease: SwiftRootLease, waitedMs: number) => Promise<T>,
8359
+ ): Promise<T> {
8360
+ const slots = Array.from({ length: SWIFT_BUILD_ROOT_SLOTS }, (_, index) => {
8361
+ const slot = index === 0 ? baseRoot : `${baseRoot}-s${index}`
8362
+ mkdirSync(slot, { recursive: true })
8363
+ return slot
8364
+ })
8365
+ const runInSlot = (slot: string, waitStart: number) => (lease: SwiftRootLease) => {
8366
+ const waitedMs = Date.now() - waitStart
8367
+ const now = new Date()
8368
+ utimesSync(slot, now, now)
8369
+ return work(slot, lease, waitedMs)
8370
+ }
8371
+ const built = new Map(slots.map((slot) => [slot, statSync(slot).mtimeMs]))
8372
+ const ranked = slots
8373
+ .map((slot, index) => {
8374
+ const shape = swiftFrameworkSlotRecord(slot, SWIFT_BUILD_ROOT_SHAPE)
8375
+ const tier = shape === buildShape ? 0 : shape === null ? 1 : 2
8376
+ return { slot, index, tier }
8377
+ })
8378
+ .sort((left, right) => {
8379
+ if (left.tier !== right.tier) return left.tier - right.tier
8380
+ if (left.tier === 0)
8381
+ return (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0)
8382
+ if (left.tier === 1) return left.index - right.index
8383
+ return (built.get(left.slot) ?? 0) - (built.get(right.slot) ?? 0)
8384
+ })
8385
+ for (const { slot } of ranked) {
8386
+ const result = await withSwiftRootLock(
8387
+ slot,
8388
+ async (lease) => ({ value: await runInSlot(slot, Date.now())(lease) }),
8389
+ signal,
8390
+ false,
8391
+ )
8392
+ if (result) return result.value
8393
+ }
8394
+ const nearest = ranked[0]!.slot
8395
+ const waitStart = Date.now()
8396
+ return withSwiftRootLock(nearest, runInSlot(nearest, waitStart), signal)
8397
+ }
8398
+
8314
8399
  // copies the files of `source` that differ into `target` and removes the rest of
8315
8400
  // `target`. a file whose size and mtime match, or whose bytes match, is left
8316
8401
  // alone so llbuild sees it unchanged; a changed file arrives as a new inode.
@@ -8382,8 +8467,10 @@ function stageFrameworkSource(
8382
8467
  if (hadKey !== frameworkKey) {
8383
8468
  // an interrupted restage must not look like a finished one
8384
8469
  rmSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), { force: true })
8470
+ rmSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_RELEASE), { force: true })
8385
8471
  rmSync(path.join(slot, 'products-ready'), { recursive: true, force: true })
8386
- rmSync(path.join(slot, 'lib', '.receipt'), { force: true })
8472
+ rmSync(path.join(slot, 'products-lib'), { recursive: true, force: true })
8473
+ rmSync(path.join(slot, 'lib'), { recursive: true, force: true })
8387
8474
  const moduleRestructured = mirrorTree(moduleRoot, stagedModule, '.build')
8388
8475
  const sdkRestructured = mirrorTree(
8389
8476
  swiftSharedSdkRoot(moduleRoot, false),
@@ -8415,8 +8502,11 @@ function stageFrameworkSource(
8415
8502
  rmSync(modules, { recursive: true, force: true })
8416
8503
  symlinkSync(target, modules)
8417
8504
  }
8505
+ writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_RELEASE), release)
8418
8506
  writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), frameworkKey)
8419
8507
  writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_ORIGIN), moduleRoot)
8508
+ } else if (swiftFrameworkSlotRelease(slot) !== release) {
8509
+ writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_RELEASE), release)
8420
8510
  }
8421
8511
  return stagedModule
8422
8512
  }
@@ -8705,62 +8795,194 @@ async function compileSwiftProjectOnce(
8705
8795
  }
8706
8796
  // the root's sources, manifest and executable are shared by every process
8707
8797
  // using it, so one process writes, builds and reads them at a time.
8798
+ const baseRoot = root
8799
+ const canPoolBuildRoot =
8800
+ !options.intermediates &&
8801
+ !options.project &&
8802
+ !options.linkOnly &&
8803
+ path.basename(path.dirname(baseRoot)) === 'swift-builds'
8804
+ const buildShape = canPoolBuildRoot
8805
+ ? createHash('sha256')
8806
+ .update(
8807
+ JSON.stringify([
8808
+ frameworkKey,
8809
+ Boolean(sdkImage),
8810
+ compileTargets(input)
8811
+ .map((target) => target.name)
8812
+ .sort(),
8813
+ input.oneModule === true,
8814
+ input.optimize === true,
8815
+ input.unoptimized === true,
8816
+ Object.keys(input.files).sort(),
8817
+ ]),
8818
+ )
8819
+ .digest('hex')
8820
+ .slice(0, 16)
8821
+ : ''
8708
8822
  return withSwiftCompileBudget(options.timeoutMs, options.signal, async (budget) => {
8709
- return withSwiftRootLock(
8710
- root,
8711
- async (lease) => {
8712
- // a process that held the root while this one waited may have built
8713
- // this exact address.
8714
- if (!options.intermediates) {
8715
- const built = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
8716
- if (built) {
8717
- report('reusing verified disk artifact')
8718
- return retain(root, built)
8719
- }
8823
+ const stage = (message: string) => {
8824
+ budget.progress()
8825
+ report(message)
8826
+ }
8827
+ const runLocked = (
8828
+ work: (
8829
+ slotRoot: string,
8830
+ lease: SwiftRootLease,
8831
+ waitedMs: number,
8832
+ ) => Promise<SwiftCompileArtifact | void>,
8833
+ ) => {
8834
+ if (canPoolBuildRoot) {
8835
+ mkdirSync(sharedRoot, { recursive: true })
8836
+ return withSwiftRootLock(
8837
+ sharedRoot,
8838
+ async () => {
8839
+ // a concurrent caller with the exact same hash may have finished
8840
+ // while we waited on sharedRoot; return before touching any slot.
8841
+ const built = readCompiledArtifact(
8842
+ path.join(sharedRoot, 'artifact'),
8843
+ hash,
8844
+ )
8845
+ if (built) {
8846
+ stage('reusing verified disk artifact')
8847
+ return retain(baseRoot, built)
8848
+ }
8849
+ return withSwiftBuildRootSlot(baseRoot, buildShape, budget.signal, work)
8850
+ },
8851
+ budget.signal,
8852
+ )
8853
+ }
8854
+ const waitStart = Date.now()
8855
+ return withSwiftRootLock(
8856
+ baseRoot,
8857
+ (lease) => work(baseRoot, lease, Date.now() - waitStart),
8858
+ budget.signal,
8859
+ )
8860
+ }
8861
+ return runLocked(async (slotRoot, lease, waitedMs) => {
8862
+ const root = slotRoot
8863
+ const layout: SwiftProjectLayout = {
8864
+ root,
8865
+ sources: path.join(root, 'Sources', 'App'),
8866
+ multi: compileTargets(input).length > 0,
8867
+ }
8868
+ // a process that held the root while this one waited may have built
8869
+ // this exact address.
8870
+ if (!options.intermediates) {
8871
+ const built = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
8872
+ if (built) {
8873
+ stage('reusing verified disk artifact')
8874
+ return retain(baseRoot, built)
8720
8875
  }
8721
- const swift = path.join(options.toolchainBin, 'swift')
8722
- if (!existsSync(swift)) {
8723
- throw new Error(
8724
- `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`,
8725
- )
8876
+ }
8877
+ if (waitedMs >= 1_000)
8878
+ report(`acquired build root ${path.basename(root)} after ${waitedMs}ms`)
8879
+ if (canPoolBuildRoot) {
8880
+ refreshSwiftCacheHold(root)
8881
+ writeFileSync(path.join(root, SWIFT_BUILD_ROOT_SHAPE), buildShape)
8882
+ }
8883
+ const swift = path.join(options.toolchainBin, 'swift')
8884
+ if (!existsSync(swift)) {
8885
+ throw new Error(
8886
+ `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`,
8887
+ )
8888
+ }
8889
+ // a distribution's immutable modules and host plugins need no source build.
8890
+ const unoptimized = input.unoptimized === true
8891
+ const withFrameworkLock = <T>(
8892
+ work: (slot: string | null, frameworkLease?: SwiftRootLease) => Promise<T>,
8893
+ ) =>
8894
+ distribution
8895
+ ? work(null)
8896
+ : withSwiftFrameworkSlot(
8897
+ frameworkKey,
8898
+ options.release,
8899
+ moduleRoot,
8900
+ budget.signal,
8901
+ work,
8902
+ unoptimized,
8903
+ )
8904
+ const baseBuildEnv = options.project?.env
8905
+ ? {
8906
+ ...options.project.env,
8907
+ // shipped host plugins resolve against the selected compiler's runtime.
8908
+ ...(process.platform === 'linux'
8909
+ ? {
8910
+ LD_LIBRARY_PATH: [
8911
+ path.resolve(options.toolchainBin, '../lib/swift/linux'),
8912
+ path.resolve(options.toolchainBin, '../lib/swift/host'),
8913
+ process.env.LD_LIBRARY_PATH,
8914
+ ]
8915
+ .filter(Boolean)
8916
+ .join(':'),
8917
+ }
8918
+ : {}),
8919
+ PEACH_DEFER_WASM_LINK: '1',
8920
+ }
8921
+ : swiftCompilerBaseEnv(options.toolchainBin, process.env)
8922
+ // hold the exclusive framework slot lock only while staging and
8923
+ // building framework products; take a shared read hold before
8924
+ // releasing it so other builds on the same framework revision
8925
+ // compile and link their apps concurrently.
8926
+ const {
8927
+ frameworkRoot,
8928
+ compileFrameworkRoot,
8929
+ macroPlugins,
8930
+ sdk,
8931
+ icu,
8932
+ prebuilt,
8933
+ readHold,
8934
+ } = await withFrameworkLock(async (slot, frameworkLease) => {
8935
+ budget.startCompile()
8936
+ if (slot && swiftFrameworkSlotKey(slot) !== frameworkKey)
8937
+ await waitForNoSwiftRootReaders(slot, budget.signal)
8938
+ // project users own their build roots; resolve their sdk outside them.
8939
+ const frameworkRoot = mirrorDistribution
8940
+ ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
8941
+ : distribution
8942
+ ? moduleRoot
8943
+ : stageFrameworkSource(moduleRoot, slot, frameworkKey, options.release)
8944
+ if (!swiftModuleDigest(frameworkRoot).equals(moduleDigest))
8945
+ throw new Error('Swift staged project source differs from the caller')
8946
+ stage('preparing compiler plugins')
8947
+ const macroPlugins = await ensureMacroPlugins(
8948
+ frameworkRoot,
8949
+ options.toolchainBin,
8950
+ options.release,
8951
+ budget.signal,
8952
+ frameworkLease,
8953
+ )
8954
+ const compileFrameworkRoot = distribution
8955
+ ? swiftDistributionCompileView(frameworkRoot, distribution)
8956
+ : frameworkRoot
8957
+ // memoized per toolchain, so only a process's first build waits on it,
8958
+ // and that one reads and gzips it while swift builds
8959
+ const sdk = swiftModuleSdk(frameworkRoot).wasmSdkId
8960
+ const icu = options.linkOnly ? null : swiftIcuAsset(options.toolchainBin, sdk)
8961
+ let prebuilt: SwiftFrameworkProducts | undefined
8962
+ if (!distribution) {
8963
+ stage('compiling framework products')
8964
+ prebuilt = await buildFrameworkProducts(slot!, {
8965
+ moduleRoot: frameworkRoot,
8966
+ frameworkKey,
8967
+ input,
8968
+ swift,
8969
+ sdk,
8970
+ toolchainBin: options.toolchainBin,
8971
+ plugins: macroPlugins,
8972
+ buildOptions: {
8973
+ env: baseBuildEnv,
8974
+ maxBuffer: 64 * 1024 * 1024,
8975
+ signal: budget.signal,
8976
+ onOutput: budget.progress,
8977
+ lease,
8978
+ frameworkLease,
8979
+ },
8980
+ })
8726
8981
  }
8727
- // a distribution's immutable modules and host plugins need no source build.
8728
- const unoptimized = input.unoptimized === true
8729
- const withFrameworkLock = <T>(
8730
- work: (slot: string | null, frameworkLease?: SwiftRootLease) => Promise<T>,
8731
- ) =>
8732
- distribution
8733
- ? work(null)
8734
- : withSwiftFrameworkSlot(
8735
- frameworkKey,
8736
- moduleRoot,
8737
- budget.signal,
8738
- work,
8739
- unoptimized,
8740
- )
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)
8759
- // hold the exclusive framework slot lock only while staging and
8760
- // building framework products; take a shared read hold before
8761
- // releasing it so other builds on the same framework revision
8762
- // compile and link their apps concurrently.
8763
- const {
8982
+ const readHold: SwiftRootReadHold | undefined = slot
8983
+ ? acquireSwiftRootReadHold(slot)
8984
+ : undefined
8985
+ return {
8764
8986
  frameworkRoot,
8765
8987
  compileFrameworkRoot,
8766
8988
  macroPlugins,
@@ -8768,735 +8990,676 @@ async function compileSwiftProjectOnce(
8768
8990
  icu,
8769
8991
  prebuilt,
8770
8992
  readHold,
8771
- } = await withFrameworkLock(async (slot, frameworkLease) => {
8772
- budget.startCompile()
8773
- if (slot && swiftFrameworkSlotKey(slot) !== frameworkKey)
8774
- await waitForNoSwiftRootReaders(slot, budget.signal)
8775
- // project users own their build roots; resolve their sdk outside them.
8776
- const frameworkRoot = mirrorDistribution
8777
- ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
8778
- : distribution
8779
- ? moduleRoot
8780
- : stageFrameworkSource(moduleRoot, slot, frameworkKey, options.release)
8781
- if (!swiftModuleDigest(frameworkRoot).equals(moduleDigest))
8782
- throw new Error('Swift staged project source differs from the caller')
8783
- report('preparing compiler plugins')
8784
- const macroPlugins = await ensureMacroPlugins(
8785
- frameworkRoot,
8786
- options.toolchainBin,
8787
- options.release,
8788
- budget.signal,
8789
- frameworkLease,
8993
+ }
8994
+ })
8995
+ const buildOptions = {
8996
+ env: baseBuildEnv,
8997
+ maxBuffer: 64 * 1024 * 1024,
8998
+ signal: budget.signal,
8999
+ onOutput: budget.progress,
9000
+ lease,
9001
+ }
9002
+ try {
9003
+ if (options.project) removeProjectLinks(root)
9004
+ const packageHostMacros =
9005
+ process.platform === 'linux' ? input.packageHostMacros : undefined
9006
+ if (
9007
+ retireStaleSwiftLink(
9008
+ root,
9009
+ swiftLinkStamp({
9010
+ frameworkKey: `${options.release}\0${Boolean(distribution)}\0${swiftModuleSdk(frameworkRoot).wasmSdkId}`,
9011
+ packageHostMacros,
9012
+ }),
9013
+ swiftLinkStamp({
9014
+ // a distribution's objects reach only the deferred link, and
9015
+ // the root's mirror keeps its compile inputs at fixed paths
9016
+ frameworkKey: distribution
9017
+ ? `${options.release}\0${distribution.wasmSdkChecksum}`
9018
+ : frameworkKey,
9019
+ prebuilt,
9020
+ packageHostMacros,
9021
+ }),
9022
+ Boolean(options.linkOnly),
8790
9023
  )
8791
- const compileFrameworkRoot = distribution
8792
- ? swiftDistributionCompileView(frameworkRoot, distribution)
8793
- : frameworkRoot
8794
- // memoized per toolchain, so only a process's first build waits on it,
8795
- // and that one reads and gzips it while swift builds
8796
- const sdk = swiftModuleSdk(frameworkRoot).wasmSdkId
8797
- const icu = options.linkOnly
8798
- ? null
8799
- : swiftIcuAsset(options.toolchainBin, sdk)
8800
- let prebuilt: SwiftFrameworkProducts | undefined
8801
- if (!distribution) {
8802
- report('compiling framework products')
8803
- prebuilt = await buildFrameworkProducts(slot!, {
8804
- moduleRoot: frameworkRoot,
8805
- frameworkKey,
8806
- input,
8807
- swift,
8808
- sdk,
8809
- toolchainBin: options.toolchainBin,
8810
- plugins: macroPlugins,
8811
- buildOptions: {
8812
- env: baseBuildEnv,
8813
- maxBuffer: 64 * 1024 * 1024,
8814
- signal: budget.signal,
8815
- lease,
8816
- frameworkLease,
8817
- },
8818
- })
8819
- }
8820
- const readHold: SwiftRootReadHold | undefined = slot
8821
- ? acquireSwiftRootReadHold(slot)
8822
- : undefined
8823
- return {
8824
- frameworkRoot,
8825
- compileFrameworkRoot,
8826
- macroPlugins,
8827
- sdk,
8828
- icu,
8829
- prebuilt,
8830
- readHold,
8831
- }
8832
- })
8833
- const buildOptions = {
8834
- env: baseBuildEnv,
8835
- maxBuffer: 64 * 1024 * 1024,
8836
- signal: budget.signal,
8837
- lease,
9024
+ )
9025
+ stage('framework revision changed; rebuilding the app link')
9026
+ const nativeToolset = needsNativeToolset(input, prebuilt)
9027
+ const preparation = writeSwiftProject(
9028
+ layout,
9029
+ input,
9030
+ frameworkRoot,
9031
+ prebuilt,
9032
+ !options.project,
9033
+ options.project
9034
+ ? false
9035
+ : (options.objcPrebuiltStage ??
9036
+ (options.intermediates ? false : undefined)),
9037
+ )
9038
+ // the framework objects link as inputs, so the product name its
9039
+ // modules autolink has no archive to load
9040
+ const productFile = path.join(frameworkRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
9041
+ writeSwiftAutolinkLinker(
9042
+ root,
9043
+ options.toolchainBin,
9044
+ existsSync(productFile)
9045
+ ? [
9046
+ v.parse(
9047
+ swiftFrameworkProductSchema,
9048
+ JSON.parse(readFileSync(productFile, 'utf8')),
9049
+ ).product.name,
9050
+ ]
9051
+ : [],
9052
+ )
9053
+ // the native build system takes its C compiler from CC, never a toolset
9054
+ const compiler: Record<string, string> = preparation.targetToolset
9055
+ ? { CC: path.join(root, CLANG_TARGET_MODULE_WRAPPER) }
9056
+ : {}
9057
+ if (packageHostMacros?.length) {
9058
+ // swiftpm build-tool flags skip macro targets; forward the import
9059
+ // when swiftpm compiles a declared macro for the linux host.
9060
+ const swiftc = path.join(root, SWIFT_HOST_COMPILER_WRAPPER)
9061
+ writeBuildFile(
9062
+ swiftc,
9063
+ [
9064
+ '#!/bin/sh',
9065
+ 'target=',
9066
+ 'module=',
9067
+ 'compile=',
9068
+ 'previous=',
9069
+ 'for argument do',
9070
+ ' case "$previous" in -target) target=$argument ;; -module-name) module=$argument ;; esac',
9071
+ ' case "$argument" in -c|-emit-module|-scan-dependencies|-typecheck) compile=1 ;; esac',
9072
+ ' previous=$argument',
9073
+ 'done',
9074
+ 'case "$target/$compile" in',
9075
+ ' *-*-linux*/1)',
9076
+ ' case ",$PEACH_SWIFT_HOST_MACROS," in',
9077
+ ' *",$module,"*) set -- "$@" -Xfrontend -import-module -Xfrontend Foundation ;;',
9078
+ ' esac ;;',
9079
+ 'esac',
9080
+ 'exec "$PEACH_SWIFTC" "$@"',
9081
+ '',
9082
+ ].join('\n'),
9083
+ )
9084
+ chmodSync(swiftc, 0o755)
9085
+ compiler.SWIFT_EXEC = swiftc
9086
+ compiler.PEACH_SWIFT_HOST_MACROS = packageHostMacros.join(',')
9087
+ compiler.PEACH_SWIFTC = path.join(options.toolchainBin, 'swiftc')
8838
9088
  }
8839
- try {
8840
- if (options.project) removeProjectLinks(root)
8841
- const packageHostMacros =
8842
- process.platform === 'linux' ? input.packageHostMacros : undefined
8843
- if (
8844
- retireStaleSwiftLink(
8845
- root,
8846
- swiftLinkStamp({
8847
- frameworkKey: `${options.release}\0${Boolean(distribution)}\0${swiftModuleSdk(frameworkRoot).wasmSdkId}`,
8848
- packageHostMacros,
8849
- }),
8850
- swiftLinkStamp({
8851
- // a distribution's objects reach only the deferred link, and
8852
- // the root's mirror keeps its compile inputs at fixed paths
8853
- frameworkKey: distribution
8854
- ? `${options.release}\0${distribution.wasmSdkChecksum}`
8855
- : frameworkKey,
8856
- prebuilt,
8857
- packageHostMacros,
8858
- }),
8859
- Boolean(options.linkOnly),
8860
- )
9089
+ const projectProcess = options.project
9090
+ ? prepareSwiftProjectProcess(root, options.project)
9091
+ : undefined
9092
+ // swiftpm hashes TMPDIR into its plan. the root lock owns this scratch.
9093
+ const temporaryDirectory = projectProcess
9094
+ ? undefined
9095
+ : path.join(root, '.build', 'peach-compiler-tmp')
9096
+ const appOptions = projectProcess
9097
+ ? {
9098
+ ...buildOptions,
9099
+ uid: projectProcess.uid,
9100
+ gid: projectProcess.gid,
9101
+ confined: { ...projectProcess.env, ...compiler },
9102
+ }
9103
+ : {
9104
+ ...buildOptions,
9105
+ temporaryDirectory,
9106
+ env: {
9107
+ ...buildOptions.env,
9108
+ ...(preparation.usesObjcPrebuilt &&
9109
+ process.env.PEACH_HOME !== undefined
9110
+ ? { PEACH_HOME: process.env.PEACH_HOME }
9111
+ : {}),
9112
+ ...compiler,
9113
+ },
9114
+ }
9115
+ const unprepared = preparation.targetFailures.map(
9116
+ (failure) => `error: target ${failure}`,
9117
+ )
9118
+ // a forwarder header (`#include "../../x.hpp"`) reaches its target
9119
+ // through `..`, which clang keeps in __FILE__, while the header
9120
+ // alias overlay names the same file directly. mapping each
9121
+ // forwarder spelling to the directory it reaches makes a debug
9122
+ // assert expand alike in every module that includes the header.
9123
+ const forwarders = new Map<string, string>()
9124
+ for (const [file, text] of Object.entries(input.files)) {
9125
+ const parents = /^#include "((?:\.\.\/)+)[^"\n]+"\n$/.exec(text)?.[1]
9126
+ if (!parents) continue
9127
+ const directory = path.posix.dirname(file)
9128
+ forwarders.set(
9129
+ `${path.join(root, directory)}/${parents.slice(0, -1)}`,
9130
+ path.posix.join('build', directory, parents).replace(/\/$/, ''),
8861
9131
  )
8862
- report('framework revision changed; rebuilding the app link')
8863
- const nativeToolset = needsNativeToolset(input, prebuilt)
8864
- const preparation = writeSwiftProject(
8865
- layout,
8866
- input,
8867
- frameworkRoot,
8868
- prebuilt,
8869
- !options.project,
8870
- options.project
8871
- ? false
8872
- : (options.objcPrebuiltStage ??
8873
- (options.intermediates ? false : undefined)),
9132
+ }
9133
+ const jobs = swiftCompilerJobs()
9134
+ const incrementalPreview =
9135
+ sdkImage !== undefined &&
9136
+ !guestGraph &&
9137
+ !options.project &&
9138
+ !input.optimize &&
9139
+ !input.unoptimized
9140
+ const perFile = input.unoptimized || incrementalPreview
9141
+ const buildArgs = [
9142
+ 'build',
9143
+ ...(projectProcess?.cacheOptions ?? swiftPackageCacheOptions()),
9144
+ '--build-system',
9145
+ 'native',
9146
+ '-j',
9147
+ String(jobs),
9148
+ '--package-path',
9149
+ root,
9150
+ ...swiftCompileSdkOptions(frameworkRoot, options.toolchainBin),
9151
+ ...swiftObjCSelectorOptions(frameworkRoot),
9152
+ '--swift-sdk',
9153
+ sdk,
9154
+ ...(preparation.targetToolset
9155
+ ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
9156
+ : []),
9157
+ '-c',
9158
+ 'release',
9159
+ ...(input.unoptimized ? ['-Xswiftc', '-Onone'] : []),
9160
+ ...(perFile
9161
+ ? [
9162
+ '-Xswiftc',
9163
+ '-no-whole-module-optimization',
9164
+ '-Xswiftc',
9165
+ '-j',
9166
+ '-Xswiftc',
9167
+ String(jobs),
9168
+ ]
9169
+ : []),
9170
+ ...(incrementalPreview
9171
+ ? ['-Xswiftc', '-incremental', '-Xswiftc', '-enable-batch-mode']
9172
+ : []),
9173
+ // the mirror finds a changed sdk header's readers in their
9174
+ // dependency files, which omit system headers by default
9175
+ ...(mirrorDistribution ? ['-Xswiftc', '-track-system-dependencies'] : []),
9176
+ // the link strips debug info, so none is generated (as for the framework).
9177
+ // keep -num-threads fixed across caller core caps so llbuild does not
9178
+ // rebuild every target when callers alternate --cores, and bound backend
9179
+ // fan-out under high -j.
9180
+ '-Xswiftc',
9181
+ '-gnone',
9182
+ ...(incrementalPreview
9183
+ ? []
9184
+ : [
9185
+ '-Xswiftc',
9186
+ '-num-threads',
9187
+ '-Xswiftc',
9188
+ String(perFile ? 1 : Math.min(8, os.availableParallelism())),
9189
+ ]),
9190
+ ...swiftReproducibleBuildFlags([
9191
+ [path.dirname(options.toolchainBin), 'toolchain'],
9192
+ [compileFrameworkRoot, 'framework'],
9193
+ [root, 'build'],
9194
+ ...forwarders,
9195
+ ]).flatMap((flag, index, flags) => {
9196
+ if (!nativeToolset || !flag.startsWith('-ffile-prefix-map='))
9197
+ return [flag]
9198
+ const toolchainDir = path.dirname(options.toolchainBin)
9199
+ let mapped = flag
9200
+ for (const [dir, target] of [
9201
+ [root, '/peach/build'],
9202
+ [compileFrameworkRoot, '/peach/framework'],
9203
+ [realpathSync(compileFrameworkRoot), '/peach/framework'],
9204
+ [toolchainDir, '/peach/toolchain'],
9205
+ [realpathSync(toolchainDir), '/peach/toolchain'],
9206
+ ] as const) {
9207
+ mapped = mapped.replaceAll(dir, target)
9208
+ }
9209
+ const [, from, to] = /^-ffile-prefix-map=([^=]+)=(.+)$/.exec(mapped) ?? []
9210
+ const tool = flags[index - 1]!
9211
+ // clang applies the longest prefix once without chaining: keep the
9212
+ // physical map for direct compiles and add the mapped form for
9213
+ // subpaths already rewritten by modular depscan.
9214
+ return mapped !== flag && from !== to ? [flag, tool, mapped] : [flag]
9215
+ }),
9216
+ ...macroPlugins.libraries.flatMap((plugin) => [
9217
+ '-Xswiftc',
9218
+ '-load-plugin-library',
9219
+ '-Xswiftc',
9220
+ plugin,
9221
+ ]),
9222
+ ...macroPlugins.executables.flatMap((plugin) => [
9223
+ '-Xswiftc',
9224
+ '-load-plugin-executable',
9225
+ '-Xswiftc',
9226
+ `${plugin}#ExpoModulesMacros`,
9227
+ ]),
9228
+ ]
9229
+ const linked = builtArtifact(layout)
9230
+ // every link is deferred: a build stopped after the linker wrapper wrote
9231
+ // its 8-byte placeholder would otherwise leave swiftpm seeing a fresh,
9232
+ // empty executable and skipping the link on the next build.
9233
+ rmSync(path.join(root, '.peach-link.rsp'), { force: true })
9234
+ // archive producers reuse objects across compiler recipe changes,
9235
+ // so qualify each new entry with the current linker.
9236
+ if (options.linkOnly || (existsSync(linked) && statSync(linked).size <= 8))
9237
+ rmSync(linked, { force: true })
9238
+ stage('compiling and linking Swift modules')
9239
+ const frameworkInterfaces = new Map<
9240
+ string,
9241
+ { file: string; header: string; module: boolean } | null
9242
+ >()
9243
+ const sdkFrameworks = path.join(
9244
+ swiftSdkPaths(frameworkRoot, options.toolchainBin).darwin,
9245
+ 'System/Library/Frameworks',
9246
+ )
9247
+ const generatedInterface = (source: string) =>
9248
+ withoutImportedSdkEnumForwards(
9249
+ clangInterfaceHeader(readFileSync(source, 'utf8'), frameworkRoot),
9250
+ sdkObjCDeclarationOwners(sdkFrameworks),
8874
9251
  )
8875
- // the framework objects link as inputs, so the product name its
8876
- // modules autolink has no archive to load
8877
- const productFile = path.join(frameworkRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
8878
- writeSwiftAutolinkLinker(
8879
- root,
8880
- options.toolchainBin,
8881
- existsSync(productFile)
8882
- ? [
8883
- v.parse(
8884
- swiftFrameworkProductSchema,
8885
- JSON.parse(readFileSync(productFile, 'utf8')),
8886
- ).product.name,
8887
- ]
8888
- : [],
9252
+ const nativeDeclarations = new Map<string, Set<string>>()
9253
+ const nativeHeaders = Object.entries(input.files)
9254
+ .filter(([name]) => name.endsWith('.h') && !name.endsWith('-Swift.h'))
9255
+ .map(([, source]) => source)
9256
+ for (const [file, contents] of Object.entries(input.files)) {
9257
+ if (!file.endsWith('.modulemap')) continue
9258
+ const name = moduleMapName(contents)
9259
+ const umbrella = /\bumbrella\s+header\s+"([^"]+)"/.exec(contents)?.[1]
9260
+ if (!name || !umbrella) continue
9261
+ const header =
9262
+ input.files[path.posix.join(path.posix.dirname(file), umbrella)]
9263
+ if (header === undefined) continue
9264
+ const included = new Set(
9265
+ [
9266
+ ...header.matchAll(/^\s*#\s*(?:import|include)\s*[<"]([^">]+)[">]/gm),
9267
+ ].map((match) => path.posix.basename(match[1]!)),
8889
9268
  )
8890
- // the native build system takes its C compiler from CC, never a toolset
8891
- const compiler: Record<string, string> = preparation.targetToolset
8892
- ? { CC: path.join(root, CLANG_TARGET_MODULE_WRAPPER) }
8893
- : {}
8894
- if (packageHostMacros?.length) {
8895
- // swiftpm build-tool flags skip macro targets; forward the import
8896
- // when swiftpm compiles a declared macro for the linux host.
8897
- const swiftc = path.join(root, SWIFT_HOST_COMPILER_WRAPPER)
8898
- writeBuildFile(
8899
- swiftc,
8900
- [
8901
- '#!/bin/sh',
8902
- 'target=',
8903
- 'module=',
8904
- 'compile=',
8905
- 'previous=',
8906
- 'for argument do',
8907
- ' case "$previous" in -target) target=$argument ;; -module-name) module=$argument ;; esac',
8908
- ' case "$argument" in -c|-emit-module|-scan-dependencies|-typecheck) compile=1 ;; esac',
8909
- ' previous=$argument',
8910
- 'done',
8911
- 'case "$target/$compile" in',
8912
- ' *-*-linux*/1)',
8913
- ' case ",$PEACH_SWIFT_HOST_MACROS," in',
8914
- ' *",$module,"*) set -- "$@" -Xfrontend -import-module -Xfrontend Foundation ;;',
8915
- ' esac ;;',
8916
- 'esac',
8917
- 'exec "$PEACH_SWIFTC" "$@"',
8918
- '',
8919
- ].join('\n'),
8920
- )
8921
- chmodSync(swiftc, 0o755)
8922
- compiler.SWIFT_EXEC = swiftc
8923
- compiler.PEACH_SWIFT_HOST_MACROS = packageHostMacros.join(',')
8924
- compiler.PEACH_SWIFTC = path.join(options.toolchainBin, 'swiftc')
9269
+ const declarations = nativeDeclarations.get(name) ?? new Set<string>()
9270
+ for (const declaration of swiftInterfaceDeclarations(header))
9271
+ declarations.add(declaration)
9272
+ for (const [candidate, source] of Object.entries(input.files))
9273
+ if (included.has(path.posix.basename(candidate)))
9274
+ for (const declaration of swiftInterfaceDeclarations(source))
9275
+ declarations.add(declaration)
9276
+ nativeDeclarations.set(name, declarations)
9277
+ }
9278
+ const frameworkInterface = (
9279
+ name: string,
9280
+ ): { file: string; header: string; module: boolean } | null => {
9281
+ if (frameworkInterfaces.has(name)) return frameworkInterfaces.get(name)!
9282
+ const source = distribution
9283
+ ? path.join(frameworkRoot, 'modules', `${name}-Swift.h`)
9284
+ : prebuilt!.objcHeaders.get(name)
9285
+ if (!source || !existsSync(source)) {
9286
+ frameworkInterfaces.set(name, null)
9287
+ return null
8925
9288
  }
8926
- const projectProcess = options.project
8927
- ? prepareSwiftProjectProcess(root, options.project)
8928
- : undefined
8929
- // swiftpm hashes TMPDIR into its plan. the root lock owns this scratch.
8930
- const temporaryDirectory = projectProcess
8931
- ? undefined
8932
- : path.join(root, '.build', 'peach-compiler-tmp')
8933
- const appOptions = projectProcess
8934
- ? {
8935
- ...buildOptions,
8936
- uid: projectProcess.uid,
8937
- gid: projectProcess.gid,
8938
- confined: { ...projectProcess.env, ...compiler },
8939
- }
8940
- : {
8941
- ...buildOptions,
8942
- temporaryDirectory,
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
- },
8951
- }
8952
- const unprepared = preparation.targetFailures.map(
8953
- (failure) => `error: target ${failure}`,
9289
+ const headers = path.join(sdkFrameworks, `${name}.framework/Headers`)
9290
+ const declared = new Set<string>()
9291
+ if (existsSync(headers))
9292
+ for (const file of readdirSync(headers, {
9293
+ recursive: true,
9294
+ encoding: 'utf8',
9295
+ }))
9296
+ if (file.endsWith('.h'))
9297
+ for (const name of swiftInterfaceDeclarations(
9298
+ readFileSync(path.join(headers, file), 'utf8'),
9299
+ ))
9300
+ declared.add(name)
9301
+ for (const declaration of nativeDeclarations.get(name) ?? [])
9302
+ declared.add(declaration)
9303
+ const own = withoutSwiftDeclarations(
9304
+ generatedInterface(source),
9305
+ declared,
9306
+ nativeDeclarations.has(name)
9307
+ ? `@import ${name};`
9308
+ : `#import <${name}/${name}.h>`,
8954
9309
  )
8955
- // a forwarder header (`#include "../../x.hpp"`) reaches its target
8956
- // through `..`, which clang keeps in __FILE__, while the header
8957
- // alias overlay names the same file directly. mapping each
8958
- // forwarder spelling to the directory it reaches makes a debug
8959
- // assert expand alike in every module that includes the header.
8960
- const forwarders = new Map<string, string>()
8961
- for (const [file, text] of Object.entries(input.files)) {
8962
- const parents = /^#include "((?:\.\.\/)+)[^"\n]+"\n$/.exec(text)?.[1]
8963
- if (!parents) continue
8964
- const directory = path.posix.dirname(file)
8965
- forwarders.set(
8966
- `${path.join(root, directory)}/${parents.slice(0, -1)}`,
8967
- path.posix.join('build', directory, parents).replace(/\/$/, ''),
8968
- )
9310
+ // the swift module also implements classes another framework's headers
9311
+ // already define; clang takes those from the owning framework
9312
+ const owners = sdkObjCDeclarationOwners(sdkFrameworks)
9313
+ const foreign = new Map<string, string>()
9314
+ for (const declaration of [
9315
+ ...swiftInterfaceDeclarations(own),
9316
+ ...objcEnumerations(own),
9317
+ ...[...own.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
9318
+ (match) => match[1]!,
9319
+ ),
9320
+ ]) {
9321
+ const owner = owners.get(declaration)
9322
+ if (owner && owner !== name) foreign.set(declaration, owner)
8969
9323
  }
8970
- const jobs = swiftCompilerJobs()
8971
- const incrementalPreview =
8972
- sdkImage !== undefined &&
8973
- !guestGraph &&
8974
- !options.project &&
8975
- !input.optimize &&
8976
- !input.unoptimized
8977
- const perFile = input.unoptimized || incrementalPreview
8978
- const buildArgs = [
8979
- 'build',
8980
- ...(projectProcess?.cacheOptions ?? swiftPackageCacheOptions()),
8981
- '--build-system',
8982
- 'native',
8983
- '-j',
8984
- String(jobs),
8985
- '--package-path',
9324
+ const header = foreign.size
9325
+ ? withoutSwiftDeclarations(
9326
+ own,
9327
+ new Set(foreign.keys()),
9328
+ [...new Set(foreign.values())]
9329
+ .map((owner) => `#import <${owner}/${owner}.h>`)
9330
+ .join('\n'),
9331
+ )
9332
+ : own
9333
+ const value = {
9334
+ file: path.join(root, '.build/peach-framework-objc', `${name}-Swift.h`),
9335
+ header,
9336
+ module: existsSync(headers),
9337
+ }
9338
+ frameworkInterfaces.set(name, value)
9339
+ writeBuildFile(
9340
+ value.file,
9341
+ (existsSync(path.join(headers, `${name}.h`))
9342
+ ? `#import <${name}/${name}.h>\n`
9343
+ : '') + swiftHeaderWithSuperclassImports(header, frameworkInterface),
9344
+ )
9345
+ return value
9346
+ }
9347
+ const headerPaths = (producer: string) => {
9348
+ const stem = path.join(
8986
9349
  root,
8987
- ...swiftCompileSdkOptions(frameworkRoot, options.toolchainBin),
8988
- ...swiftObjCSelectorOptions(frameworkRoot),
8989
- '--swift-sdk',
8990
- sdk,
8991
- ...(preparation.targetToolset
8992
- ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
8993
- : []),
8994
- '-c',
8995
- 'release',
8996
- ...(input.unoptimized ? ['-Xswiftc', '-Onone'] : []),
8997
- ...(perFile
8998
- ? [
8999
- '-Xswiftc',
9000
- '-no-whole-module-optimization',
9001
- '-Xswiftc',
9002
- '-j',
9003
- '-Xswiftc',
9004
- String(jobs),
9005
- ]
9006
- : []),
9007
- ...(incrementalPreview
9008
- ? ['-Xswiftc', '-incremental', '-Xswiftc', '-enable-batch-mode']
9009
- : []),
9010
- // the mirror finds a changed sdk header's readers in their
9011
- // dependency files, which omit system headers by default
9012
- ...(mirrorDistribution ? ['-Xswiftc', '-track-system-dependencies'] : []),
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.
9017
- '-Xswiftc',
9018
- '-gnone',
9019
- ...(incrementalPreview
9020
- ? []
9021
- : [
9022
- '-Xswiftc',
9023
- '-num-threads',
9024
- '-Xswiftc',
9025
- String(perFile ? 1 : Math.min(8, os.availableParallelism())),
9026
- ]),
9027
- ...swiftReproducibleBuildFlags([
9028
- [path.dirname(options.toolchainBin), 'toolchain'],
9029
- [compileFrameworkRoot, 'framework'],
9030
- [root, 'build'],
9031
- ...forwarders,
9032
- ]).flatMap((flag, index, flags) => {
9033
- if (!nativeToolset || !flag.startsWith('-ffile-prefix-map='))
9034
- return [flag]
9035
- const toolchainDir = path.dirname(options.toolchainBin)
9036
- let mapped = flag
9037
- for (const [dir, target] of [
9038
- [root, '/peach/build'],
9039
- [compileFrameworkRoot, '/peach/framework'],
9040
- [realpathSync(compileFrameworkRoot), '/peach/framework'],
9041
- [toolchainDir, '/peach/toolchain'],
9042
- [realpathSync(toolchainDir), '/peach/toolchain'],
9043
- ] as const) {
9044
- mapped = mapped.replaceAll(dir, target)
9045
- }
9046
- const [, from, to] =
9047
- /^-ffile-prefix-map=([^=]+)=(.+)$/.exec(mapped) ?? []
9048
- const tool = flags[index - 1]!
9049
- // clang applies the longest prefix once without chaining: keep the
9050
- // physical map for direct compiles and add the mapped form for
9051
- // subpaths already rewritten by modular depscan.
9052
- return mapped !== flag && from !== to ? [flag, tool, mapped] : [flag]
9053
- }),
9054
- ...macroPlugins.libraries.flatMap((plugin) => [
9055
- '-Xswiftc',
9056
- '-load-plugin-library',
9057
- '-Xswiftc',
9058
- plugin,
9059
- ]),
9060
- ...macroPlugins.executables.flatMap((plugin) => [
9061
- '-Xswiftc',
9062
- '-load-plugin-executable',
9063
- '-Xswiftc',
9064
- `${plugin}#ExpoModulesMacros`,
9065
- ]),
9066
- ]
9067
- const linked = builtArtifact(layout)
9068
- // every link is deferred: a build stopped after the linker wrapper wrote
9069
- // its 8-byte placeholder would otherwise leave swiftpm seeing a fresh,
9070
- // empty executable and skipping the link on the next build.
9071
- rmSync(path.join(root, '.peach-link.rsp'), { force: true })
9072
- // archive producers reuse objects across compiler recipe changes,
9073
- // so qualify each new entry with the current linker.
9074
- if (options.linkOnly || (existsSync(linked) && statSync(linked).size <= 8))
9075
- rmSync(linked, { force: true })
9076
- report('compiling and linking Swift modules')
9077
- const frameworkInterfaces = new Map<
9078
- string,
9079
- { file: string; header: string; module: boolean } | null
9080
- >()
9081
- const sdkFrameworks = path.join(
9082
- swiftSdkPaths(frameworkRoot, options.toolchainBin).darwin,
9083
- 'System/Library/Frameworks',
9350
+ '.build',
9351
+ 'peach-cxx-headers',
9352
+ `${producer}-Swift`,
9084
9353
  )
9085
- const generatedInterface = (source: string) =>
9086
- withoutImportedSdkEnumForwards(
9087
- clangInterfaceHeader(readFileSync(source, 'utf8'), frameworkRoot),
9088
- sdkObjCDeclarationOwners(sdkFrameworks),
9089
- )
9090
- const nativeDeclarations = new Map<string, Set<string>>()
9091
- const nativeHeaders = Object.entries(input.files)
9092
- .filter(([name]) => name.endsWith('.h') && !name.endsWith('-Swift.h'))
9093
- .map(([, source]) => source)
9094
- for (const [file, contents] of Object.entries(input.files)) {
9095
- if (!file.endsWith('.modulemap')) continue
9096
- const name = moduleMapName(contents)
9097
- const umbrella = /\bumbrella\s+header\s+"([^"]+)"/.exec(contents)?.[1]
9098
- if (!name || !umbrella) continue
9099
- const header =
9100
- input.files[path.posix.join(path.posix.dirname(file), umbrella)]
9101
- if (header === undefined) continue
9102
- const included = new Set(
9103
- [
9104
- ...header.matchAll(/^\s*#\s*(?:import|include)\s*[<"]([^">]+)[">]/gm),
9105
- ].map((match) => path.posix.basename(match[1]!)),
9106
- )
9107
- const declarations = nativeDeclarations.get(name) ?? new Set<string>()
9108
- for (const declaration of swiftInterfaceDeclarations(header))
9109
- declarations.add(declaration)
9110
- for (const [candidate, source] of Object.entries(input.files))
9111
- if (included.has(path.posix.basename(candidate)))
9112
- for (const declaration of swiftInterfaceDeclarations(source))
9113
- declarations.add(declaration)
9114
- nativeDeclarations.set(name, declarations)
9115
- }
9116
- const frameworkInterface = (
9117
- name: string,
9118
- ): { file: string; header: string; module: boolean } | null => {
9119
- if (frameworkInterfaces.has(name)) return frameworkInterfaces.get(name)!
9120
- const source = distribution
9121
- ? path.join(frameworkRoot, 'modules', `${name}-Swift.h`)
9122
- : prebuilt!.objcHeaders.get(name)
9123
- if (!source || !existsSync(source)) {
9124
- frameworkInterfaces.set(name, null)
9125
- return null
9354
+ return { producer, original: `${stem}.original.h`, emitted: `${stem}.h` }
9355
+ }
9356
+ const publishHeader = ({
9357
+ producer,
9358
+ original,
9359
+ emitted,
9360
+ }: ReturnType<typeof headerPaths>) => {
9361
+ const generated = generatedInterface(original)
9362
+ writeBuildFile(
9363
+ emitted,
9364
+ withoutSwiftDeclarations(
9365
+ swiftHeaderWithSuperclassImports(generated, frameworkInterface),
9366
+ new Set([
9367
+ ...(preparation.nativeHeaderDeclarations[producer] ?? []),
9368
+ ...nativelyDeclaredFunctions(generated, nativeHeaders),
9369
+ ]),
9370
+ `#import <${producer}/${producer}.h>`,
9371
+ ),
9372
+ )
9373
+ }
9374
+ const recipe = inputHash
9375
+ .copy()
9376
+ .update(
9377
+ distribution ? swiftCompileSurfaceDigest(frameworkRoot) : moduleDigest,
9378
+ )
9379
+ .update(readFileSync(path.join(root, 'Package.swift')))
9380
+ .update(JSON.stringify(buildArgs))
9381
+ .digest('hex')
9382
+ const runApp = async (compiler?: Record<string, string>) => {
9383
+ const optionsWithCompiler = compiler
9384
+ ? { ...appOptions, env: { ...appOptions.env, ...compiler } }
9385
+ : appOptions
9386
+ // clang consumes the real emitted headers after swift finishes.
9387
+ // swiftpm's transitive swift module maps are not C declarations:
9388
+ // importing them would shadow SDK modules such as ObjectiveC.
9389
+ const stages = [
9390
+ ...(preparation.nativePrerequisiteTargets ?? []).map((target) => ({
9391
+ target,
9392
+ producers: [],
9393
+ })),
9394
+ ...preparation.headerBuilds,
9395
+ ...(preparation.nativeProductTargets ?? []).map((target) => ({
9396
+ target,
9397
+ producers: [],
9398
+ })),
9399
+ ]
9400
+ const checkpoints = path.join(root, '.build', 'peach-product-checkpoints')
9401
+ const buildDbExists = existsSync(path.join(root, '.build', 'build.db'))
9402
+ const releaseDir = path.dirname(linked)
9403
+ for (const { target, producers } of stages) {
9404
+ // pure native checkpoint stages exist only to commit build.db on cold
9405
+ // builds; when build.db and all stage objects are already warm, the
9406
+ // header stage and final full-graph build still validate every input.
9407
+ if (!options.project && producers.length === 0 && buildDbExists) {
9408
+ const expectedObjects = preparation.nativeStageObjects.get(target)
9409
+ if (
9410
+ expectedObjects &&
9411
+ expectedObjects.length > 0 &&
9412
+ expectedObjects.every((relative) =>
9413
+ statSync(path.join(releaseDir, relative), {
9414
+ throwIfNoEntry: false,
9415
+ })?.isFile(),
9416
+ )
9417
+ )
9418
+ continue
9126
9419
  }
9127
- const headers = path.join(sdkFrameworks, `${name}.framework/Headers`)
9128
- const declared = new Set<string>()
9129
- if (existsSync(headers))
9130
- for (const file of readdirSync(headers, {
9131
- recursive: true,
9132
- encoding: 'utf8',
9133
- }))
9134
- if (file.endsWith('.h'))
9135
- for (const name of swiftInterfaceDeclarations(
9136
- readFileSync(path.join(headers, file), 'utf8'),
9137
- ))
9138
- declared.add(name)
9139
- for (const declaration of nativeDeclarations.get(name) ?? [])
9140
- declared.add(declaration)
9141
- const own = withoutSwiftDeclarations(
9142
- generatedInterface(source),
9143
- declared,
9144
- nativeDeclarations.has(name)
9145
- ? `@import ${name};`
9146
- : `#import <${name}/${name}.h>`,
9420
+ const receipt = path.join(
9421
+ checkpoints,
9422
+ createHash('sha256').update(target).digest('hex'),
9147
9423
  )
9148
- // the swift module also implements classes another framework's headers
9149
- // already define; clang takes those from the owning framework
9150
- const owners = sdkObjCDeclarationOwners(sdkFrameworks)
9151
- const foreign = new Map<string, string>()
9152
- for (const declaration of [
9153
- ...swiftInterfaceDeclarations(own),
9154
- ...objcEnumerations(own),
9155
- ...[...own.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
9156
- (match) => match[1]!,
9157
- ),
9158
- ]) {
9159
- const owner = owners.get(declaration)
9160
- if (owner && owner !== name) foreign.set(declaration, owner)
9161
- }
9162
- const header = foreign.size
9163
- ? withoutSwiftDeclarations(
9164
- own,
9165
- new Set(foreign.keys()),
9166
- [...new Set(foreign.values())]
9167
- .map((owner) => `#import <${owner}/${owner}.h>`)
9168
- .join('\n'),
9424
+ const headers = producers.map(headerPaths)
9425
+ for (const header of headers)
9426
+ if (existsSync(header.original)) publishHeader(header)
9427
+ const fingerprint = (): string | undefined => {
9428
+ const digest = createHash('sha256').update(recipe)
9429
+ for (const { original, emitted } of headers) {
9430
+ if (!existsSync(original) || !existsSync(emitted)) return
9431
+ digest.update(
9432
+ createHash('sha256').update(readFileSync(emitted)).digest(),
9169
9433
  )
9170
- : own
9171
- const value = {
9172
- file: path.join(root, '.build/peach-framework-objc', `${name}-Swift.h`),
9173
- header,
9174
- module: existsSync(headers),
9434
+ }
9435
+ return digest.digest('hex')
9175
9436
  }
9176
- frameworkInterfaces.set(name, value)
9177
- writeBuildFile(
9178
- value.file,
9179
- (existsSync(path.join(headers, `${name}.h`))
9180
- ? `#import <${name}/${name}.h>\n`
9181
- : '') + swiftHeaderWithSuperclassImports(header, frameworkInterface),
9182
- )
9183
- return value
9184
- }
9185
- const headerPaths = (producer: string) => {
9186
- const stem = path.join(
9187
- root,
9188
- '.build',
9189
- 'peach-cxx-headers',
9190
- `${producer}-Swift`,
9191
- )
9192
- return { producer, original: `${stem}.original.h`, emitted: `${stem}.h` }
9193
- }
9194
- const publishHeader = ({
9195
- producer,
9196
- original,
9197
- emitted,
9198
- }: ReturnType<typeof headerPaths>) => {
9199
- const generated = generatedInterface(original)
9200
- writeBuildFile(
9201
- emitted,
9202
- withoutSwiftDeclarations(
9203
- swiftHeaderWithSuperclassImports(generated, frameworkInterface),
9204
- new Set([
9205
- ...(preparation.nativeHeaderDeclarations[producer] ?? []),
9206
- ...nativelyDeclaredFunctions(generated, nativeHeaders),
9207
- ]),
9208
- `#import <${producer}/${producer}.h>`,
9209
- ),
9210
- )
9211
- }
9212
- const recipe = inputHash
9213
- .copy()
9214
- .update(
9215
- distribution ? swiftCompileSurfaceDigest(frameworkRoot) : moduleDigest,
9437
+ if (
9438
+ !options.project &&
9439
+ existsSync(receipt) &&
9440
+ readFileSync(receipt, 'utf8') === fingerprint()
9216
9441
  )
9217
- .update(readFileSync(path.join(root, 'Package.swift')))
9218
- .update(JSON.stringify(buildArgs))
9219
- .digest('hex')
9220
- const runApp = async (compiler?: Record<string, string>) => {
9221
- const optionsWithCompiler = compiler
9222
- ? { ...appOptions, env: { ...appOptions.env, ...compiler } }
9223
- : appOptions
9224
- // clang consumes the real emitted headers after swift finishes.
9225
- // swiftpm's transitive swift module maps are not C declarations:
9226
- // importing them would shadow SDK modules such as ObjectiveC.
9227
- const stages = [
9228
- ...(preparation.nativePrerequisiteTargets ?? []).map((target) => ({
9229
- target,
9230
- producers: [],
9231
- })),
9232
- ...preparation.headerBuilds,
9233
- ...(preparation.nativeProductTargets ?? []).map((target) => ({
9234
- target,
9235
- producers: [],
9236
- })),
9237
- ]
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)
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
- )
9442
+ continue
9443
+ if (!options.project) rmSync(receipt, { force: true })
9444
+ // swiftpm doesn't track custom objc header paths as outputs.
9445
+ for (const header of headers) {
9446
+ if (!existsSync(header.original))
9447
+ rmSync(
9448
+ path.join(
9449
+ path.dirname(linked),
9450
+ 'Modules',
9451
+ `${swiftTargetModuleName(header.producer)}.swiftmodule`,
9452
+ ),
9453
+ { force: true },
9255
9454
  )
9256
- continue
9257
- }
9258
- const receipt = path.join(
9259
- checkpoints,
9260
- createHash('sha256').update(target).digest('hex'),
9261
- )
9262
- const headers = producers.map(headerPaths)
9263
- for (const header of headers)
9264
- if (existsSync(header.original)) publishHeader(header)
9265
- const fingerprint = (): string | undefined => {
9266
- const digest = createHash('sha256').update(recipe)
9267
- for (const { original, emitted } of headers) {
9268
- if (!existsSync(original) || !existsSync(emitted)) return
9269
- digest.update(
9270
- createHash('sha256').update(readFileSync(emitted)).digest(),
9271
- )
9272
- }
9273
- return digest.digest('hex')
9274
- }
9275
- if (
9276
- !options.project &&
9277
- existsSync(receipt) &&
9278
- readFileSync(receipt, 'utf8') === fingerprint()
9279
- )
9280
- continue
9281
- if (!options.project) rmSync(receipt, { force: true })
9282
- // swiftpm doesn't track custom objc header paths as outputs.
9283
- for (const header of headers) {
9284
- if (!existsSync(header.original))
9285
- rmSync(
9286
- path.join(
9287
- path.dirname(linked),
9288
- 'Modules',
9289
- `${swiftTargetModuleName(header.producer)}.swiftmodule`,
9290
- ),
9291
- { force: true },
9292
- )
9293
- }
9294
- await runCompiler(
9295
- swift,
9296
- [...buildArgs, '--target', target],
9297
- optionsWithCompiler,
9298
- /^(?:\[swift-prebuilt\]|\[\d+\/\d+\] )/,
9299
- SWIFTPM_NOISE,
9300
- )
9301
- if (!compiler) for (const header of headers) publishHeader(header)
9302
- if (!options.project) {
9303
- const checkpoint = fingerprint()
9304
- if (checkpoint === undefined)
9305
- throw new Error(`missing Swift headers after building ${target}`)
9306
- mkdirSync(checkpoints, { recursive: true })
9307
- writeFileSync(`${receipt}.partial`, checkpoint)
9308
- renameSync(`${receipt}.partial`, receipt)
9309
- }
9310
9455
  }
9311
- // always let swiftpm check the full graph, including missing outputs.
9312
9456
  await runCompiler(
9313
9457
  swift,
9314
- buildArgs,
9458
+ [...buildArgs, '--target', target],
9315
9459
  optionsWithCompiler,
9316
- SWIFTPM_PROGRESS,
9460
+ /^(?:\[swift-prebuilt\]|\[\d+\/\d+\] )/,
9317
9461
  SWIFTPM_NOISE,
9318
9462
  )
9463
+ if (!compiler) for (const header of headers) publishHeader(header)
9464
+ if (!options.project) {
9465
+ const checkpoint = fingerprint()
9466
+ if (checkpoint === undefined)
9467
+ throw new Error(`missing Swift headers after building ${target}`)
9468
+ mkdirSync(checkpoints, { recursive: true })
9469
+ writeFileSync(`${receipt}.partial`, checkpoint)
9470
+ renameSync(`${receipt}.partial`, receipt)
9471
+ }
9319
9472
  }
9320
- const compileApp = () =>
9321
- preparation.headerCompiler
9322
- ? withSwiftHeaderCompiler(
9323
- root,
9324
- options.toolchainBin,
9325
- recipe,
9326
- new Map(
9327
- preparation.headerBuilds[0]!.producers.map((producer) => {
9328
- const paths = headerPaths(producer)
9329
- return [
9330
- swiftTargetModuleName(producer),
9331
- {
9332
- header: paths.original,
9333
- publish: () => publishHeader(paths),
9334
- },
9335
- ]
9336
- }),
9337
- ),
9338
- runApp,
9339
- )
9340
- : runApp()
9341
- try {
9342
- if (temporaryDirectory) mkdirSync(temporaryDirectory, { recursive: true })
9343
- await compileApp()
9344
- } catch (error) {
9345
- const output = outputOf(error)
9346
- const moduleCache = path.join(
9347
- root,
9348
- '.build',
9349
- WASM_TRIPLE,
9350
- 'release',
9351
- 'ModuleCache',
9352
- )
9353
- if (
9354
- output.includes('was compiled with module cache path') &&
9355
- existsSync(moduleCache)
9356
- ) {
9357
- rmSync(moduleCache, { recursive: true, force: true })
9358
- try {
9359
- await compileApp()
9360
- } catch (retryError) {
9361
- throw new Error(
9362
- [
9363
- ...unprepared,
9364
- projectDiagnostic(outputOf(retryError), layout, input.files),
9365
- ].join('\n'),
9366
- { cause: retryError },
9367
- )
9368
- }
9369
- } else {
9370
- throw new Error(
9371
- [...unprepared, projectDiagnostic(output, layout, input.files)].join(
9372
- '\n',
9473
+ // always let swiftpm check the full graph, including missing outputs.
9474
+ await runCompiler(
9475
+ swift,
9476
+ buildArgs,
9477
+ optionsWithCompiler,
9478
+ SWIFTPM_PROGRESS,
9479
+ SWIFTPM_NOISE,
9480
+ )
9481
+ }
9482
+ const compileApp = () =>
9483
+ preparation.headerCompiler
9484
+ ? withSwiftHeaderCompiler(
9485
+ root,
9486
+ options.toolchainBin,
9487
+ recipe,
9488
+ new Map(
9489
+ preparation.headerBuilds[0]!.producers.map((producer) => {
9490
+ const paths = headerPaths(producer)
9491
+ return [
9492
+ swiftTargetModuleName(producer),
9493
+ {
9494
+ header: paths.original,
9495
+ publish: () => publishHeader(paths),
9496
+ },
9497
+ ]
9498
+ }),
9373
9499
  ),
9374
- { cause: error },
9500
+ runApp,
9501
+ )
9502
+ : runApp()
9503
+ try {
9504
+ if (temporaryDirectory) mkdirSync(temporaryDirectory, { recursive: true })
9505
+ await compileApp()
9506
+ } catch (error) {
9507
+ const output = outputOf(error)
9508
+ const moduleCache = path.join(
9509
+ root,
9510
+ '.build',
9511
+ WASM_TRIPLE,
9512
+ 'release',
9513
+ 'ModuleCache',
9514
+ )
9515
+ if (
9516
+ output.includes('was compiled with module cache path') &&
9517
+ existsSync(moduleCache)
9518
+ ) {
9519
+ rmSync(moduleCache, { recursive: true, force: true })
9520
+ try {
9521
+ await compileApp()
9522
+ } catch (retryError) {
9523
+ throw new Error(
9524
+ [
9525
+ ...unprepared,
9526
+ projectDiagnostic(outputOf(retryError), layout, input.files),
9527
+ ].join('\n'),
9528
+ { cause: retryError },
9375
9529
  )
9376
9530
  }
9377
- } finally {
9378
- if (temporaryDirectory)
9379
- rmSync(temporaryDirectory, { recursive: true, force: true })
9380
- // a manifest, macro or build tool can leave processes behind that
9381
- // outlive the compiler's own group; none runs once the host reads.
9382
- if (options.project) endSwiftProjectProcesses(options.project)
9383
- }
9384
- if (unprepared.length) throw new Error(unprepared.join('\n'))
9385
- if (!existsSync(linked)) {
9386
- const binDir = path.dirname(linked)
9387
- const found = existsSync(binDir)
9388
- ? readdirSync(binDir)
9389
- .filter((name) => name.endsWith('.wasm'))
9390
- .sort()
9391
- : []
9531
+ } else {
9392
9532
  throw new Error(
9393
- `swift-compile: the build produced no ${path.basename(linked)} (found: ${found.join(', ') || 'none'})`,
9533
+ [...unprepared, projectDiagnostic(output, layout, input.files)].join(
9534
+ '\n',
9535
+ ),
9536
+ { cause: error },
9394
9537
  )
9395
9538
  }
9396
- if (options.project) removeProjectLinks(root)
9397
- const resourceReferences = Object.values(input.resources ?? {}).map(
9398
- (value) => Buffer.from(value, 'base64'),
9539
+ } finally {
9540
+ if (temporaryDirectory)
9541
+ rmSync(temporaryDirectory, { recursive: true, force: true })
9542
+ // a manifest, macro or build tool can leave processes behind that
9543
+ // outlive the compiler's own group; none runs once the host reads.
9544
+ if (options.project) endSwiftProjectProcesses(options.project)
9545
+ }
9546
+ if (unprepared.length) throw new Error(unprepared.join('\n'))
9547
+ if (!existsSync(linked)) {
9548
+ const binDir = path.dirname(linked)
9549
+ const found = existsSync(binDir)
9550
+ ? readdirSync(binDir)
9551
+ .filter((name) => name.endsWith('.wasm'))
9552
+ .sort()
9553
+ : []
9554
+ throw new Error(
9555
+ `swift-compile: the build produced no ${path.basename(linked)} (found: ${found.join(', ') || 'none'})`,
9399
9556
  )
9400
- // the guest link prunes and links the response file itself.
9401
- if (!guestGraph)
9402
- pruneSwiftWasmLink(
9403
- root,
9404
- options.toolchainBin,
9405
- prebuilt?.root ?? frameworkRoot,
9406
- input.staticClangTargets,
9407
- options.project,
9408
- undefined,
9409
- resourceReferences,
9410
- )
9411
- if (options.linkOnly) {
9412
- if (statSync(linked).size <= 8)
9413
- throw new Error('swift-compile: deferred linker produced no executable')
9414
- report('project link verified')
9415
- return
9416
- }
9417
- const output = options.project
9418
- ? projectOutputFile(root, linked, options.project)
9419
- : linked
9420
- const optimized = `${output}.optimized`
9421
- if (sdkImage && options.project) rmSync(optimized, { force: true })
9422
- let sdkAsset: SwiftSdkModuleAsset | undefined
9423
- if (guestGraph) {
9424
- const binding = await compileGuestLink({
9425
- graph: guestGraph,
9426
- buildDirectory: root,
9427
- releaseDirectory: path.dirname(linked),
9428
- moduleRoot: frameworkRoot,
9429
- toolchainBin: options.toolchainBin,
9430
- swiftCompiler: preparation.headerCompiler
9431
- ? path.join(root, SWIFT_HEADER_COMPILER_WRAPPER)
9432
- : (compiler.SWIFT_EXEC ?? path.join(options.toolchainBin, 'swiftc')),
9433
- sysroot: swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9434
- sdk: swiftModuleSdk(frameworkRoot),
9435
- sdkImage,
9436
- compilerDigest: compilerSourceDigest,
9437
- project: options.project && {
9438
- ...options.project,
9439
- env: { ...options.project.env, ...projectProcess?.env },
9440
- },
9441
- staticClangTargets: input.staticClangTargets ?? [],
9442
- resourceReferences,
9443
- resourceBundles: input.resourceBundles ?? [],
9444
- generatedOwners: preparation.generatedOwners,
9445
- output,
9446
- optimized,
9447
- optimize: input.optimize === true,
9448
- jobs: swiftBuildJobs(),
9449
- })
9450
- if (sdkImage && binding)
9451
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9452
- } else if (sdkImage) {
9453
- const { buildSwiftAppModule } = await import('./swift-sdk-app-module')
9454
- const binding = await buildSwiftAppModule({
9455
- buildRoot: root,
9456
- toolchainBin: options.toolchainBin,
9457
- sdk: sdkImage,
9458
- output: optimized,
9459
- optimize: input.optimize === true,
9460
- project: options.project && {
9461
- ...options.project,
9462
- env: { ...options.project.env, ...projectProcess?.env },
9463
- sdkRoot: path.dirname(
9464
- swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9465
- ),
9466
- linked: output,
9467
- },
9468
- })
9469
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9470
- } else {
9471
- const bytes = readFileSync(output)
9472
- const ordered = orderObjCConstructors(bytes)
9473
- if (ordered !== bytes) writeFileSync(output, ordered)
9474
- await lowerWasm(output, optimized, { optimize: input.optimize === true })
9475
- }
9476
- if (!sdkImage)
9477
- await runCompiler(
9478
- path.join(options.toolchainBin, 'llvm-objcopy'),
9479
- ['--remove-section=.swift1_autolink_entries', optimized],
9480
- buildOptions,
9481
- )
9482
- const artifact = {
9483
- hash,
9484
- bytes: readFileSync(optimized),
9485
- icu: await icu!,
9486
- sdk: sdkAsset,
9487
- }
9488
- if (artifact.bytes.length <= 8)
9557
+ }
9558
+ if (options.project) removeProjectLinks(root)
9559
+ const resourceReferences = Object.values(input.resources ?? {}).map((value) =>
9560
+ Buffer.from(value, 'base64'),
9561
+ )
9562
+ // the guest link prunes and links the response file itself.
9563
+ if (!guestGraph)
9564
+ pruneSwiftWasmLink(
9565
+ root,
9566
+ options.toolchainBin,
9567
+ prebuilt?.root ?? frameworkRoot,
9568
+ input.staticClangTargets,
9569
+ options.project,
9570
+ undefined,
9571
+ resourceReferences,
9572
+ )
9573
+ if (options.linkOnly) {
9574
+ if (statSync(linked).size <= 8)
9489
9575
  throw new Error('swift-compile: deferred linker produced no executable')
9490
- if (!options.project) saveCompiledArtifact(root, artifact)
9491
- saveSharedArtifact(sharedRoot, artifact)
9492
- report('compiled artifact verified')
9493
- return retain(root, artifact)
9494
- } finally {
9495
- readHold?.release()
9576
+ stage('project link verified')
9577
+ return
9496
9578
  }
9497
- },
9498
- budget.signal,
9499
- )
9579
+ const output = options.project
9580
+ ? projectOutputFile(root, linked, options.project)
9581
+ : linked
9582
+ const optimized = `${output}.optimized`
9583
+ if (sdkImage && options.project) rmSync(optimized, { force: true })
9584
+ let sdkAsset: SwiftSdkModuleAsset | undefined
9585
+ stage('linking the app image')
9586
+ if (guestGraph) {
9587
+ const binding = await compileGuestLink({
9588
+ graph: guestGraph,
9589
+ buildDirectory: root,
9590
+ releaseDirectory: path.dirname(linked),
9591
+ moduleRoot: frameworkRoot,
9592
+ toolchainBin: options.toolchainBin,
9593
+ swiftCompiler: preparation.headerCompiler
9594
+ ? path.join(root, SWIFT_HEADER_COMPILER_WRAPPER)
9595
+ : (compiler.SWIFT_EXEC ?? path.join(options.toolchainBin, 'swiftc')),
9596
+ sysroot: swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9597
+ sdk: swiftModuleSdk(frameworkRoot),
9598
+ sdkImage,
9599
+ compilerDigest: compilerSourceDigest,
9600
+ project: options.project && {
9601
+ ...options.project,
9602
+ env: { ...options.project.env, ...projectProcess?.env },
9603
+ },
9604
+ staticClangTargets: input.staticClangTargets ?? [],
9605
+ resourceReferences,
9606
+ resourceBundles: input.resourceBundles ?? [],
9607
+ generatedOwners: preparation.generatedOwners,
9608
+ output,
9609
+ optimized,
9610
+ optimize: input.optimize === true,
9611
+ jobs: swiftBuildJobs(),
9612
+ onStage: stage,
9613
+ })
9614
+ if (sdkImage && binding)
9615
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9616
+ } else if (sdkImage) {
9617
+ const { buildSwiftAppModule } = await import('./swift-sdk-app-module')
9618
+ const binding = await buildSwiftAppModule({
9619
+ buildRoot: root,
9620
+ toolchainBin: options.toolchainBin,
9621
+ sdk: sdkImage,
9622
+ output: optimized,
9623
+ optimize: input.optimize === true,
9624
+ project: options.project && {
9625
+ ...options.project,
9626
+ env: { ...options.project.env, ...projectProcess?.env },
9627
+ sdkRoot: path.dirname(
9628
+ swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9629
+ ),
9630
+ linked: output,
9631
+ },
9632
+ })
9633
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9634
+ } else {
9635
+ const bytes = readFileSync(output)
9636
+ const ordered = orderObjCConstructors(bytes)
9637
+ if (ordered !== bytes) writeFileSync(output, ordered)
9638
+ stage('lowering the app image')
9639
+ await lowerWasm(output, optimized, { optimize: input.optimize === true })
9640
+ }
9641
+ if (!sdkImage)
9642
+ await runCompiler(
9643
+ path.join(options.toolchainBin, 'llvm-objcopy'),
9644
+ ['--remove-section=.swift1_autolink_entries', optimized],
9645
+ buildOptions,
9646
+ )
9647
+ const artifact = {
9648
+ hash,
9649
+ bytes: readFileSync(optimized),
9650
+ icu: await icu!,
9651
+ sdk: sdkAsset,
9652
+ }
9653
+ if (artifact.bytes.length <= 8)
9654
+ throw new Error('swift-compile: deferred linker produced no executable')
9655
+ if (!options.project) saveCompiledArtifact(root, artifact)
9656
+ saveSharedArtifact(sharedRoot, artifact)
9657
+ stage('compiled artifact verified')
9658
+ return retain(baseRoot, artifact)
9659
+ } finally {
9660
+ readHold?.release()
9661
+ }
9662
+ })
9500
9663
  })
9501
9664
  },
9502
9665
  options.signal,