peachsim 0.1.2935 → 0.1.2937

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 (345) hide show
  1. package/LICENSE +6 -8
  2. package/cli/account-gate.ts +20 -3
  3. package/cli/app-bundle-resources.ts +66 -19
  4. package/cli/catalog/meta.ts +2 -106
  5. package/cli/command-agent.ts +7 -0
  6. package/cli/command-registry.ts +0 -1
  7. package/cli/commands/control.ts +13 -5
  8. package/cli/commands/daemon.ts +4 -2
  9. package/cli/commands/device.ts +78 -8
  10. package/cli/commands/do-chain.ts +11 -8
  11. package/cli/commands/inspect/core.ts +4 -9
  12. package/cli/commands/inspect/settling.ts +1 -0
  13. package/cli/commands/logout.ts +6 -1
  14. package/cli/commands/map.ts +2 -6
  15. package/cli/commands/package.ts +112 -57
  16. package/cli/commands/shell-url.ts +0 -1
  17. package/cli/download-auth.ts +2 -0
  18. package/cli/drivers/playwright-provisioning.ts +10 -38
  19. package/cli/github-workflow-identity.ts +8 -0
  20. package/cli/internal-child-contract.ts +1 -0
  21. package/cli/internal-child.ts +5 -0
  22. package/cli/main.ts +2 -10
  23. package/cli/outbound-endpoints.ts +26 -0
  24. package/detox/index.ts +227 -131
  25. package/dist-lib/agent-daemon-client.cjs +1 -1
  26. package/dist-lib/agent-events.cjs +1 -1
  27. package/dist-lib/attached-projects.cjs +1 -1
  28. package/dist-lib/auth/shared-session.cjs +1 -1
  29. package/dist-lib/backend-origin.cjs +1 -1
  30. package/dist-lib/beta.cjs +1 -1
  31. package/dist-lib/beta.mjs +2 -2
  32. package/dist-lib/bridge-constants.cjs +1 -1
  33. package/dist-lib/bridge-contract-input.cjs +47 -3
  34. package/dist-lib/bridge-contract-input.mjs +6 -6
  35. package/dist-lib/bridge-contract.cjs +10 -1
  36. package/dist-lib/bridge-contract.mjs +3 -3
  37. package/dist-lib/bundle-channel.cjs +12779 -9515
  38. package/dist-lib/capture-contract.cjs +39 -17
  39. package/dist-lib/capture-contract.mjs +3 -3
  40. package/dist-lib/cloud-contract.cjs +1 -1
  41. package/dist-lib/cloud-contract.mjs +3 -3
  42. package/dist-lib/cloud-test-args.cjs +1 -1
  43. package/dist-lib/cloud-test-args.mjs +2 -2
  44. package/dist-lib/cloud.cjs +1 -1
  45. package/dist-lib/cloud.mjs +8 -8
  46. package/dist-lib/config.cjs +1 -1
  47. package/dist-lib/config.mjs +6 -6
  48. package/dist-lib/detox/index.cjs +200 -132
  49. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  50. package/dist-lib/esm-chunks/{acorn-Q5TRRYSO.mjs → acorn-IIBLEO25.mjs} +3 -3
  51. package/dist-lib/esm-chunks/{chunk-UDWBTBVG.mjs → chunk-4FTPQKPT.mjs} +10 -1
  52. package/dist-lib/esm-chunks/chunk-4WIDTRBB.mjs +10232 -0
  53. package/dist-lib/esm-chunks/{chunk-LCMFYMT7.mjs → chunk-5QZOQ3NZ.mjs} +1 -1
  54. package/dist-lib/esm-chunks/{chunk-BJ2OGUX7.mjs → chunk-CIY67HNL.mjs} +39 -17
  55. package/dist-lib/esm-chunks/{chunk-SKQTNQYE.mjs → chunk-CQFEMJ64.mjs} +1 -1
  56. package/dist-lib/esm-chunks/{chunk-AXWVXRHX.mjs → chunk-CWVMCW23.mjs} +1 -1
  57. package/dist-lib/esm-chunks/{chunk-MTALOHQR.mjs → chunk-F6DZ4DS2.mjs} +1 -1
  58. package/dist-lib/esm-chunks/{chunk-I4R7IZRD.mjs → chunk-HJMF6O7L.mjs} +74 -46
  59. package/dist-lib/esm-chunks/chunk-I6T4PXJF.mjs +154 -0
  60. package/dist-lib/esm-chunks/{chunk-XWAUZKIA.mjs → chunk-IJU3JMWM.mjs} +1 -1
  61. package/dist-lib/esm-chunks/{chunk-CXWUIOCH.mjs → chunk-KODEPXQC.mjs} +4 -4
  62. package/dist-lib/esm-chunks/{chunk-WJE5QHSD.mjs → chunk-LD4K2VBL.mjs} +155 -36
  63. package/dist-lib/esm-chunks/{chunk-2TSM64HI.mjs → chunk-LTE7YMEG.mjs} +1 -1
  64. package/dist-lib/esm-chunks/{chunk-3GGOXUJA.mjs → chunk-M3CSKAJE.mjs} +1 -1
  65. package/dist-lib/esm-chunks/{chunk-7G5UETIG.mjs → chunk-NA6DJPB6.mjs} +43 -1
  66. package/dist-lib/esm-chunks/{chunk-MSUHMNAI.mjs → chunk-NNAX24FS.mjs} +1 -1
  67. package/dist-lib/esm-chunks/{chunk-VDJA4LP4.mjs → chunk-PZPJJBAS.mjs} +1 -1
  68. package/dist-lib/esm-chunks/{chunk-UEEEJVQA.mjs → chunk-QXSTHMWN.mjs} +1 -1
  69. package/dist-lib/esm-chunks/{chunk-S2RJB5I7.mjs → chunk-RBPVK5YI.mjs} +1 -1
  70. package/dist-lib/esm-chunks/{chunk-VRAXNGYT.mjs → chunk-SCT5OFDV.mjs} +1 -1
  71. package/dist-lib/esm-chunks/{chunk-T3M73LGP.mjs → chunk-U3CJGYSP.mjs} +50 -6
  72. package/dist-lib/esm-chunks/{chunk-SLUGTGQQ.mjs → chunk-VXTOQ522.mjs} +12 -6
  73. package/dist-lib/esm-chunks/{chunk-EL44SZMV.mjs → chunk-WMSVGYTH.mjs} +1 -1
  74. package/dist-lib/esm-chunks/{chunk-FEDEPSEV.mjs → chunk-WRWINRWK.mjs} +1 -1
  75. package/dist-lib/esm-chunks/{chunk-BNO52N2S.mjs → chunk-YZF2USRD.mjs} +1905 -8760
  76. package/dist-lib/esm-chunks/{chunk-TQLKYMVP.mjs → chunk-ZNHR6C3L.mjs} +1 -1
  77. package/dist-lib/esm-chunks/{download-auth-registry-G75MIT55.mjs → download-auth-registry-AHS5MSIB.mjs} +4 -4
  78. package/dist-lib/esm-chunks/{metro-layout-parser-FXLUDTYT.mjs → metro-layout-parser-24ZYK5UP.mjs} +3 -3
  79. package/dist-lib/esm-chunks/{swift-package-prebuilt-524D4MA2.mjs → swift-package-prebuilt-L4YNXQRD.mjs} +15 -15
  80. package/dist-lib/esm-chunks/{swift-sdk-app-module-EX544YJY.mjs → swift-sdk-app-module-RM652JSW.mjs} +87 -71
  81. package/dist-lib/esm-chunks/{swift-sdk-image-LOTMWVM7.mjs → swift-sdk-image-5PQ44UJT.mjs} +15 -15
  82. package/dist-lib/esm-chunks/{swift-sdk-image-producer-UO6B3M4U.mjs → swift-sdk-image-producer-GD3SM6YI.mjs} +5 -5
  83. package/dist-lib/esm-chunks/swift-sdk-later-data-62QYJ2KH.mjs +590 -0
  84. package/dist-lib/expo-swift-bundle.cjs +21037 -17896
  85. package/dist-lib/expo-swift-metadata.cjs +8 -2
  86. package/dist-lib/expo-swift-metadata.mjs +9 -8
  87. package/dist-lib/home-paths.cjs +1 -1
  88. package/dist-lib/host/bridge-host.cjs +22481 -18741
  89. package/dist-lib/host/fetch-proxy-handler.cjs +21079 -17980
  90. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  91. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  92. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  93. package/dist-lib/host/websocket-proxy.cjs +1 -1
  94. package/dist-lib/index.cjs +68 -38
  95. package/dist-lib/kotlin-host.cjs +97 -21
  96. package/dist-lib/menu.cjs +1 -1
  97. package/dist-lib/menu.mjs +3 -3
  98. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  99. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  100. package/dist-lib/metro-production-bundle.cjs +23 -1
  101. package/dist-lib/metro-production-bundle.mjs +24 -4
  102. package/dist-lib/native-app-identity-project.cjs +3582 -571
  103. package/dist-lib/native-app-identity-project.mjs +1024 -398
  104. package/dist-lib/native-app-identity.cjs +1 -1
  105. package/dist-lib/native-app-identity.mjs +6 -6
  106. package/dist-lib/native-firebase-metadata.cjs +1 -1
  107. package/dist-lib/native-firebase-metadata.mjs +3 -3
  108. package/dist-lib/pdfium-raster.cjs +1 -1
  109. package/dist-lib/pdfium-raster.mjs +2 -2
  110. package/dist-lib/plist.cjs +1 -1
  111. package/dist-lib/plist.mjs +3 -3
  112. package/dist-lib/profiles.cjs +1 -1
  113. package/dist-lib/public-brand.cjs +1 -1
  114. package/dist-lib/public-origins-lib-esm.json +132 -116
  115. package/dist-lib/public-origins-lib.json +215 -173
  116. package/dist-lib/react-native-host-modules.cjs +1 -1
  117. package/dist-lib/react-native-host-modules.mjs +2 -2
  118. package/dist-lib/reap-browser.cjs +17 -1
  119. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  120. package/dist-lib/sdk.cjs +6 -7
  121. package/dist-lib/sdk.mjs +13 -14
  122. package/dist-lib/skills.cjs +23216 -19650
  123. package/dist-lib/swift-compile.cjs +4337 -2905
  124. package/dist-lib/swift-compile.mjs +15 -13
  125. package/dist-lib/swift-package.cjs +1 -1
  126. package/dist-lib/swift-package.mjs +3 -3
  127. package/dist-lib/swift-submit.cjs +1 -1
  128. package/dist-lib/swift-submit.mjs +6 -6
  129. package/dist-lib/swift-svg-raster.cjs +1 -1
  130. package/dist-lib/swift-svg-raster.mjs +2 -2
  131. package/dist-lib/swift-toolchain.cjs +19 -1
  132. package/dist-lib/swift.cjs +1 -1
  133. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  134. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  135. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  136. package/dist-lib/vendor/acorn.cjs +1 -1
  137. package/dist-lib/vendor/stream-json.cjs +1 -1
  138. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  139. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  140. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  141. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  142. package/dist-lib/vendor/sucrase.cjs +1 -1
  143. package/dist-lib/vendor/terser.cjs +1 -1
  144. package/dist-lib/vendor/valibot.cjs +1 -1
  145. package/dist-lib/vendor/ws.cjs +94 -32
  146. package/dist-lib/vendor/zod.cjs +1 -1
  147. package/dist-lib/worklet-executable.cjs +8 -5
  148. package/dist-lib/worklet-executable.mjs +9 -6
  149. package/dist-types/packages/peach-engine/src/canvaskit-artifact-urls.d.ts +2 -1
  150. package/dist-types/packages/peach-engine/src/capture/compositor-presentation-recording.d.ts +1 -0
  151. package/dist-types/packages/peach-engine/src/engine/generated/canvaskit-artifact-hashes.d.ts +26 -0
  152. package/dist-types/packages/peach-engine/src/engine/guest-scene-inspect.d.ts +1 -1
  153. package/dist-types/packages/peach-engine/src/engine/inspect-info.d.ts +1 -0
  154. package/dist-types/packages/peach-engine/src/engine/metalTypes.d.ts +32 -2
  155. package/dist-types/packages/peach-engine/src/engine/portalContract.d.ts +24 -0
  156. package/dist-types/packages/peach-engine/src/engine/remote-display-protocol.d.ts +12 -2
  157. package/dist-types/packages/peach-engine/src/guest/http-cookie-storage.d.ts +73 -0
  158. package/dist-types/packages/peach-engine/src/guest/native-evaluation-lease.d.ts +5 -0
  159. package/dist-types/packages/peach-engine/src/guest/nitro-jsi-host.d.ts +3 -1
  160. package/dist-types/packages/peach-engine/src/ios/apps/canvas-map-data.d.ts +225 -9
  161. package/dist-types/packages/peach-engine/src/ios/chrome-metrics.d.ts +4 -1
  162. package/dist-types/packages/peach-engine/src/ios/duo-vertical-bar-geometry.d.ts +0 -1
  163. package/dist-types/packages/peach-engine/src/native-preview-bundle.d.ts +1 -0
  164. package/dist-types/packages/peach-engine/src/remote-stream/canvas-display-compositor.d.ts +1 -0
  165. package/dist-types/packages/peach-engine/src/remote-stream/canvas-display-contract.d.ts +44 -10
  166. package/dist-types/packages/peach-engine/src/remote-stream/cloud-display.d.ts +4 -3
  167. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +2 -4
  168. package/dist-types/packages/peach-engine/src/render-worker/metro-bundle-metadata.d.ts +2 -0
  169. package/dist-types/packages/peach-engine/src/render-worker/native-widgetContract.d.ts +1 -1
  170. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +15 -27
  171. package/dist-types/packages/peach-engine/src/render-worker/reanimated-readiness.d.ts +2 -6
  172. package/dist-types/packages/peach-engine/src/render-worker/shell-protocol.d.ts +11 -3
  173. package/dist-types/packages/peach-engine/src/settings/devices.d.ts +3 -1
  174. package/dist-types/packages/peach-engine/src/settings/duo-fold.d.ts +1 -1
  175. package/dist-types/packages/peach-engine/src/webview-automation-host.d.ts +1 -1
  176. package/dist-types/packages/peach-globals/src/app-bundle-resources.d.ts +10 -0
  177. package/dist-types/packages/peach-globals/src/compositorBridgeContract.d.ts +1 -1
  178. package/dist-types/packages/peach-globals/src/hostStorageBridgeContract.d.ts +1 -0
  179. package/dist-types/packages/peach-globals/src/index.d.ts +2 -2
  180. package/dist-types/packages/peach-globals/src/lockstepCaptureBridgeContract.d.ts +9 -6
  181. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +11 -0
  182. package/dist-types/packages/peach-globals/src/oneWidgetContract.d.ts +28 -0
  183. package/package.json +2 -2
  184. package/runtime-companion.json +1 -1
  185. package/sdk/ios/System/Library/Frameworks/CoreHaptics.framework/Headers/CoreHaptics.h +251 -0
  186. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INImage.h +14 -0
  187. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INIntent.h +18 -0
  188. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INIntentIdentifiers.h +30 -0
  189. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INIntentResponse.h +12 -0
  190. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INInteraction.h +35 -0
  191. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INObjectCollection.h +0 -7
  192. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INObjectSection.h +0 -7
  193. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INOutgoingMessageType.h +7 -0
  194. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INPerson.h +36 -0
  195. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INPersonHandle.h +22 -0
  196. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INSendMessageIntent+UserNotifications.h +6 -0
  197. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INSendMessageIntent.h +33 -0
  198. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/INSpeakableString.h +24 -0
  199. package/sdk/ios/System/Library/Frameworks/Intents.framework/Headers/Intents.h +11 -7
  200. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMailComposeViewController.h +1 -1
  201. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMessageComposeViewController.h +1 -1
  202. package/sdk/ios/System/Library/Frameworks/Metal.framework/Headers/MTLRenderCommandEncoder.h +0 -8
  203. package/sdk/ios/System/Library/Frameworks/MetalTypes.framework/Headers/MetalTypes.h +8 -0
  204. package/sdk/ios/System/Library/Frameworks/Social.framework/Headers/SLServiceTypes.h +9 -0
  205. package/sdk/ios/System/Library/Frameworks/Social.framework/Headers/Social.h +1 -0
  206. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotification.h +1 -1
  207. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationAction.h +2 -2
  208. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationAttachment.h +1 -1
  209. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationCategory.h +1 -1
  210. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationContent.h +2 -2
  211. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationRequest.h +1 -1
  212. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationResponse.h +2 -2
  213. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationSound.h +1 -1
  214. package/sdk/ios/System/Library/Frameworks/UserNotifications.framework/Headers/UNNotificationTrigger.h +5 -5
  215. package/sdk/ios/usr/lib/swift/UIKit.swiftmodule/arm64-apple-ios-simulator.swiftinterface +4 -0
  216. package/sdk/ios/wasm/include/unistd.h +1 -0
  217. package/src/acorn-program.ts +3 -0
  218. package/src/audio-codec-archives.ts +141 -0
  219. package/src/bridge-contract-input.ts +61 -1
  220. package/src/bridge-contract.ts +45 -4
  221. package/src/bundle-channel.mjs +44 -30
  222. package/src/capture-contract.ts +57 -39
  223. package/src/conformance-comparison-contract.ts +2 -0
  224. package/src/expo-discovery-cache.ts +0 -2
  225. package/src/expo-macro-host.ts +8 -3
  226. package/src/expo-native-compiler-digest.ts +0 -1
  227. package/src/expo-native-prebuilt.ts +1 -1
  228. package/src/expo-native-workspace.ts +83 -45
  229. package/src/expo-pod-prebuilt.ts +1 -0
  230. package/src/expo-swift-host.ts +158 -77
  231. package/src/expo-swift-legacy-runtime-source.ts +12 -1
  232. package/src/expo-swift-view-source.ts +51 -20
  233. package/src/expo-workspace-exclusion.ts +7 -1
  234. package/src/expoSwiftContract.ts +10 -1
  235. package/src/ffmpeg-source-build.ts +123 -59
  236. package/src/genrule-archives.ts +7 -2
  237. package/src/genrule-library-builds.ts +101 -18
  238. package/src/host/bridge-host.ts +10 -1
  239. package/src/installed-native-libraries.ts +147 -23
  240. package/src/installed-package-versions.ts +30 -0
  241. package/src/ios-rn-bundle-request.ts +3 -1
  242. package/src/ios-rn-bundle.ts +38 -27
  243. package/src/ios-rn-compile.ts +23 -6
  244. package/src/ios-rn-startup.ts +2 -1
  245. package/src/java-module-abi.ts +4 -3
  246. package/src/kotlin-host.ts +4 -4
  247. package/src/kotlin-library-sources.ts +8 -5
  248. package/src/metro-production-bundle.ts +24 -0
  249. package/src/native-firebase-config.ts +2 -0
  250. package/src/native-framework-compiler.ts +5 -0
  251. package/src/native-package-slice-build.ts +3 -0
  252. package/src/native-package-slice.ts +15 -10
  253. package/src/native-preparation.ts +4 -1
  254. package/src/native-static-libraries.ts +107 -33
  255. package/src/nativeRuntimePackageIndex.ts +1 -4
  256. package/src/nitro-adapter.lock.json +286 -286
  257. package/src/nitro-app-providers.ts +20 -8
  258. package/src/nitro-compile.ts +131 -37
  259. package/src/nitro-dependencies.ts +42 -8
  260. package/src/nitro-source.ts +40 -36
  261. package/src/nitro-superset.lock.json +4 -4
  262. package/src/nitroAdapterContract.ts +32 -7
  263. package/src/nitroContract.ts +21 -37
  264. package/src/one-direct-host-source.ts +247 -140
  265. package/src/one-fabric.ts +129 -0
  266. package/src/one-native-controls-package.ts +95 -21
  267. package/src/one-native-controls-release.ts +147 -14
  268. package/src/one-native-source.ts +4 -1
  269. package/src/one-nitro-inputs.ts +1 -1
  270. package/src/one-nitro-source.ts +45 -1
  271. package/src/one-sdk/source.ts +10 -41
  272. package/src/one-widget-metadata.ts +2 -2
  273. package/src/one-widget-package.ts +1 -1
  274. package/src/oneSdkContract.ts +3 -0
  275. package/src/playwright-browser-paths.ts +30 -0
  276. package/src/pods-install.ts +6 -2
  277. package/src/pods-post-install.ts +2 -2
  278. package/src/pods-project.ts +10 -0
  279. package/src/podspec-ruby-stdlib.ts +73 -0
  280. package/src/podspec-ruby.ts +1 -1
  281. package/src/podspec-sources.ts +31 -13
  282. package/src/process-group.ts +135 -5
  283. package/src/published-swift-sdk.ts +25 -1
  284. package/src/react-native-bridge-modules.ts +35 -3
  285. package/src/react-native-core-build.ts +14 -2
  286. package/src/react-native-core.ts +12 -2
  287. package/src/rive-runtime-dependencies.ts +178 -40
  288. package/src/serverDiscoveryContract.ts +1 -1
  289. package/src/storageSnapshotContract.ts +1 -1
  290. package/src/swift-app-data-store.ts +35 -0
  291. package/src/swift-compile.ts +403 -121
  292. package/src/swift-compiler-digest.ts +4 -0
  293. package/src/swift-darwin-records.ts +6 -0
  294. package/src/swift-distribution-mirror.ts +10 -1
  295. package/src/swift-distribution.lock.json +19 -18
  296. package/src/swift-distribution.ts +17 -1
  297. package/src/swift-entry-module.ts +1 -0
  298. package/src/swift-guest-compile.ts +8 -1
  299. package/src/swift-host.ts +79 -23
  300. package/src/swift-installed-targets.ts +51 -20
  301. package/src/swift-objc-standin.ts +60 -8
  302. package/src/swift-packages.ts +104 -24
  303. package/src/swift-project-user.ts +2 -1
  304. package/src/swift-reproducible.ts +99 -1
  305. package/src/swift-root-lock.ts +52 -46
  306. package/src/swift-sdk-app-module.ts +65 -13
  307. package/src/swift-sdk-image-producer.ts +2 -1
  308. package/src/swift-sdk-image.ts +23 -8
  309. package/src/swift-sdk-later-data.ts +294 -44
  310. package/src/swift-sdk-surface.ts +233 -55
  311. package/src/swift-shared-sdk.ts +7 -0
  312. package/src/swift-standin-builtin-behavior.ts +18 -0
  313. package/src/swift-standin-emit.ts +242 -54
  314. package/src/swift-standins.ts +184 -38
  315. package/src/swift-startup-split.ts +19 -9
  316. package/src/swift-toolchain.ts +18 -0
  317. package/src/swift-wasm-prune.ts +179 -9
  318. package/src/swift-xcframework.ts +16 -0
  319. package/src/swiftContract.ts +4 -1
  320. package/src/swiftSdkLinkContract.ts +2 -0
  321. package/src/swiftTargetContract.ts +1 -0
  322. package/src/turbo-bundle.ts +6 -3
  323. package/src/turbo-codegen-intake.ts +106 -16
  324. package/src/turbo-compile.ts +89 -68
  325. package/src/turbo-fabric-app.ts +287 -23
  326. package/src/turbo-provider-host.ts +122 -31
  327. package/src/turbo-runtime.lock.json +26 -26
  328. package/src/turbo-source.ts +374 -157
  329. package/src/vite-plugin.ts +48 -112
  330. package/src/wasm-binary-sections.ts +40 -0
  331. package/src/wasm-code-immediates.ts +35 -5
  332. package/src/widget-extension-bundle.ts +15 -1
  333. package/src/worklet-executable.ts +2 -1
  334. package/src/worklet-kernel.ts +5 -3
  335. package/src/worklets-babel.ts +2 -1
  336. package/src/xcode-project.ts +151 -53
  337. package/src/xcode-scheme-actions.ts +104 -0
  338. package/cli/commands/canvas.ts +0 -1204
  339. package/dist-lib/esm-chunks/chunk-B5QD2KEV.mjs +0 -2787
  340. package/dist-lib/vendor/magic-string.cjs +0 -1693
  341. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-cookies.d.ts +0 -127
  342. package/src/appBundleResourcesContract.ts +0 -51
  343. package/src/canvas-groups.ts +0 -28
  344. package/src/canvas-map-layout.ts +0 -161
  345. package/src/oneWidgetContract.ts +0 -134
@@ -1,2787 +0,0 @@
1
- /*! peach v0.1.2935 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
- import {
3
- SWIFT_CACHE_HOLD_MARKER,
4
- SWIFT_WASM_TRIPLE,
5
- refreshSwiftCacheHold,
6
- swiftCacheDir,
7
- swiftCompiler,
8
- swiftEnvironment,
9
- swiftSdkOptions,
10
- swiftSourceSdk,
11
- swiftToolchain,
12
- terminateProcessGroup,
13
- wasmThreadFlags,
14
- windowAdmission
15
- } from "./chunk-WJE5QHSD.mjs";
16
- import {
17
- isSwiftResourcePath
18
- } from "./chunk-7G5UETIG.mjs";
19
- import {
20
- SWIFT_IMPORT,
21
- swiftManifestDeclarations,
22
- swiftTargetModuleName
23
- } from "./chunk-XWAUZKIA.mjs";
24
- import {
25
- isRecord
26
- } from "./chunk-VDJA4LP4.mjs";
27
- import {
28
- __publicField
29
- } from "./chunk-2TSM64HI.mjs";
30
-
31
- // src/write-build-file.ts
32
- import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
33
- import path from "node:path";
34
- function writeBuildFile(file, contents2) {
35
- const stat = statSync(file, { throwIfNoEntry: false });
36
- if (stat?.isFile()) {
37
- if (typeof contents2 === "string") {
38
- if (readFileSync(file, "utf8") === contents2) return;
39
- } else if (stat.size === contents2.length && readFileSync(file).equals(contents2)) {
40
- return;
41
- }
42
- }
43
- mkdirSync(path.dirname(file), { recursive: true });
44
- writeFileSync(file, contents2);
45
- }
46
-
47
- // src/swift-objc-standin.ts
48
- import { execFileSync, spawnSync as spawnSync2 } from "node:child_process";
49
- import { createHash as createHash2 } from "node:crypto";
50
- import fs2 from "node:fs";
51
- import path6 from "node:path";
52
-
53
- // src/case-insensitive-header-overlay.ts
54
- import { createHash } from "node:crypto";
55
- import fs from "node:fs";
56
- import path2 from "node:path";
57
- var HEADER = /\.(h|hh|hpp|hxx|inc|inl|def|modulemap|apinotes|tcc)$/i;
58
- var volumeCaseSensitivity = /* @__PURE__ */ new Map();
59
- function needsCaseOverlay(directory) {
60
- if (process.platform !== "darwin") return true;
61
- const device = fs.statSync(directory).dev;
62
- const known = volumeCaseSensitivity.get(device);
63
- if (known !== void 0) return known;
64
- let probed = false;
65
- for (const name of fs.readdirSync(directory)) {
66
- const alternate = name.replace(
67
- /[a-zA-Z]/,
68
- (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
69
- );
70
- if (alternate === name) continue;
71
- const original = fs.lstatSync(path2.join(directory, name), { throwIfNoEntry: false });
72
- if (!original) continue;
73
- const changed = fs.lstatSync(path2.join(directory, alternate), {
74
- throwIfNoEntry: false
75
- });
76
- if (!changed || original.ino !== changed.ino || original.dev !== changed.dev) {
77
- volumeCaseSensitivity.set(device, true);
78
- return true;
79
- }
80
- probed = true;
81
- }
82
- if (probed) volumeCaseSensitivity.set(device, false);
83
- return !probed;
84
- }
85
- function scan(directory, listed) {
86
- const node = { files: /* @__PURE__ */ new Map(), directories: /* @__PURE__ */ new Map() };
87
- const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
88
- for (const entry of entries) {
89
- const full = path2.join(directory, entry.name);
90
- const stat = entry.isSymbolicLink() ? fs.statSync(full, { throwIfNoEntry: false }) : entry;
91
- if (!stat) continue;
92
- if (stat.isDirectory()) {
93
- const child = scan(full, listed);
94
- if (child.files.size > 0 || child.directories.size > 0)
95
- node.directories.set(entry.name, child);
96
- } else if (HEADER.test(entry.name) && (!listed || listed(full)))
97
- node.files.set(entry.name, full);
98
- }
99
- return node;
100
- }
101
- function contents(node) {
102
- return [
103
- ...[...node.directories].map(([name, child]) => ({
104
- name,
105
- type: "directory",
106
- contents: contents(child)
107
- })),
108
- ...[...node.files].map(([name, file]) => ({
109
- name,
110
- type: "file",
111
- "external-contents": file
112
- }))
113
- ];
114
- }
115
- var scans = /* @__PURE__ */ new Map();
116
- var listedScans = /* @__PURE__ */ new WeakMap();
117
- function clearCaseInsensitiveHeaderOverlayCache(rootPrefix) {
118
- const prefix = `${rootPrefix}${path2.sep}`;
119
- for (const key of scans.keys())
120
- if (key === rootPrefix || key.startsWith(prefix)) scans.delete(key);
121
- }
122
- function caseInsensitiveHeaderOverlay(directory, roots, listed, fixedName) {
123
- let known = scans;
124
- if (listed) {
125
- known = listedScans.get(listed) ?? /* @__PURE__ */ new Map();
126
- listedScans.set(listed, known);
127
- }
128
- const existing = [...new Set(roots)].filter(
129
- (root) => fs.existsSync(root) && needsCaseOverlay(root)
130
- );
131
- if (existing.length === 0) return null;
132
- const unique = existing.filter(
133
- (root) => !existing.some((other) => other !== root && root.startsWith(`${other}/`))
134
- ).sort();
135
- const roots_ = unique.map((root) => {
136
- let node = known.get(root);
137
- if (!node) known.set(root, node = scan(root, listed));
138
- return { name: root, type: "directory", contents: contents(node) };
139
- });
140
- const text = JSON.stringify({ "case-sensitive": "false", roots: roots_, version: 0 });
141
- const file = path2.join(
142
- directory,
143
- fixedName ?? `case-insensitive-${createHash("sha256").update(text).digest("hex").slice(0, 16)}.yaml`
144
- );
145
- writeBuildFile(file, text);
146
- return file;
147
- }
148
-
149
- // src/swift-objc-platform.ts
150
- import { spawnSync } from "node:child_process";
151
- import path3 from "node:path";
152
- var platforms = /* @__PURE__ */ new Map();
153
- function swiftObjCPlatformFlags(toolchainBin, minimum) {
154
- const key = `${toolchainBin}:${minimum}`;
155
- const cached = platforms.get(key);
156
- if (cached) return cached;
157
- const version = [
158
- Math.floor(minimum / 1e4),
159
- Math.floor(minimum % 1e4 / 100),
160
- minimum % 100
161
- ].join(".");
162
- const result = spawnSync(
163
- path3.join(toolchainBin, "clang"),
164
- [
165
- "-target",
166
- `arm64-apple-ios${version}-simulator`,
167
- "-dM",
168
- "-E",
169
- "-x",
170
- "objective-c",
171
- "-"
172
- ],
173
- {
174
- input: "",
175
- encoding: "utf8",
176
- env: swiftEnvironment(),
177
- timeout: 3e4,
178
- maxBuffer: 1024 * 1024
179
- }
180
- );
181
- if (result.error || result.status !== 0)
182
- throw new Error(
183
- `could not read iOS compiler platform predefines: ${result.error?.message ?? result.stderr}`
184
- );
185
- const flags = [
186
- ...result.stdout.matchAll(
187
- /^#define (TARGET_OS_\w+|TARGET_IPHONE_SIMULATOR|__APPLE\w*__|__MACH__|__ENVIRONMENT_\w+|__nonnull|__nullable|__null_unspecified) (.*)$/gm
188
- )
189
- ].map(([, name, value]) => `-D${name}=${value}`);
190
- if (!flags.includes("-D__APPLE__=1") || !flags.includes("-D__MACH__=1"))
191
- throw new Error("iOS compiler platform predefines lack Apple and Mach identity");
192
- platforms.set(key, flags);
193
- return flags;
194
- }
195
-
196
- // src/swift-objc-sdk.ts
197
- import path5 from "node:path";
198
- import { gunzipSync } from "node:zlib";
199
-
200
- // src/swift-objc-sdk-tree.ts
201
- import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
202
- import path4 from "node:path";
203
-
204
- // src/swift-objc-sdk.ts
205
- var IOS_SDK_TARGET = "arm64-apple-ios16.0-simulator";
206
-
207
- // src/swift-standin-emit.ts
208
- var TYPE_KINDS = new Set(
209
- "swift.class swift.struct swift.enum swift.protocol swift.typealias".split(" ")
210
- );
211
- var MEMBER_KINDS = new Set(
212
- "swift.method swift.type.method swift.func.op swift.init swift.property swift.type.property swift.subscript swift.type.subscript".split(
213
- " "
214
- )
215
- );
216
- var KEYWORDS = new Set(
217
- "Type Protocol Self default init self class func var let in is as repeat internal public private operator extension subscript static struct protocol enum case where return throw throws import true false nil".split(
218
- " "
219
- )
220
- );
221
-
222
- // src/swift-objc-standin.ts
223
- var NATIVE_GRAPH_SDK_VERSION = "27.1";
224
- var WASI_EMULATION = [
225
- "_WASI_EMULATED_SIGNAL",
226
- "_WASI_EMULATED_MMAN",
227
- "_WASI_EMULATED_PROCESS_CLOCKS"
228
- ];
229
- var WASI_EMULATION_FLAGS = WASI_EMULATION.map((name) => `-D${name}`);
230
- var NATIVE_GRAPH_INPUTS = {
231
- sdk: NATIVE_GRAPH_SDK_VERSION,
232
- settings: "e68503e5e534e9194af5efe8c636ca8b824e2d8237c5f38ec84aa4d155bc8418",
233
- build: "ff785237ba22f1d8f347a5c4f4c68400a387c6d935ef3a443545a72faef57e70",
234
- compiler: "Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)",
235
- target: IOS_SDK_TARGET
236
- };
237
- var NATIVE_GRAPH_ID = createHash2("sha256").update(JSON.stringify(NATIVE_GRAPH_INPUTS)).digest("hex");
238
- var C_PRIMITIVE_TYPES = new Set(
239
- "void bool _Bool char short int long float double".split(" ")
240
- );
241
- var SWIFT_SDK_HEADER_CASE_OVERLAY = "sdk-header-case.yaml";
242
- function objcSdkIntakeFlags(headers, toolchainBin, minimum, overlayDirectory) {
243
- const caseOverlay = caseInsensitiveHeaderOverlay(
244
- overlayDirectory ?? path6.join(swiftCacheDir(), "swift-header-case"),
245
- [
246
- path6.join(headers, "System/Library/Frameworks"),
247
- path6.join(headers, "wasm/include"),
248
- path6.join(headers, "wasm/intrinsics"),
249
- path6.join(headers, "usr/include")
250
- ],
251
- void 0,
252
- overlayDirectory ? SWIFT_SDK_HEADER_CASE_OVERLAY : void 0
253
- );
254
- return [
255
- ...swiftObjCPlatformFlags(toolchainBin, minimum),
256
- ...caseOverlay ? ["-ivfsoverlay", caseOverlay] : [],
257
- // AvailabilityInternal.h derives these through __is_target_os(ios), which
258
- // is false for wasm64. the maximum is the sdk the headers come from, as
259
- // xcode defines it, so `#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0`
260
- // sources see the members the sdk declares instead of a 17.0 default.
261
- `-D__IPHONE_OS_VERSION_MIN_REQUIRED=${minimum}`,
262
- `-D__IPHONE_OS_VERSION_MAX_ALLOWED=__IPHONE_${NATIVE_GRAPH_SDK_VERSION.replace(".", "_")}`,
263
- // the installed libc's default feature set otherwise defines
264
- // _XOPEN_SOURCE, which darwin's sys/cdefs.h turns into a strict posix
265
- // level; iOS compiles at darwin's full level with neither defined.
266
- "-D_BSD_SOURCE",
267
- // the installed icu archive exports its swift_-prefixed names, which the
268
- // unicode headers rename to only off darwin.
269
- "-DU_DISABLE_RENAMING=0",
270
- // clang enables blocks in every language for darwin targets, and the sdk
271
- // headers declare block types unguarded.
272
- "-fblocks",
273
- ...WASI_EMULATION_FLAGS,
274
- "-iframework",
275
- path6.join(headers, "System/Library/Frameworks"),
276
- "-isystem",
277
- path6.join(headers, "wasm/include"),
278
- // compiler intrinsics an arm64 unit includes, ahead of clang's arm-only ones.
279
- "-isystem",
280
- path6.join(headers, "wasm/intrinsics"),
281
- // libxml2 headers sit one level deeper, as in the iOS sdk: a unit
282
- // includes <libxml/parser.h> through usr/include/libxml2, never the parent.
283
- "-I",
284
- path6.join(headers, "usr/include/libxml2"),
285
- "-idirafter",
286
- path6.join(headers, "usr/include")
287
- ];
288
- }
289
- var appPlatformFlags = /* @__PURE__ */ new Map();
290
- function objcAppIntakeFlags(headers, toolchainBin, minimum, overlayDirectory) {
291
- let flags = appPlatformFlags.get(headers);
292
- if (!flags) {
293
- const include = path6.resolve(headers, "../include");
294
- const targetHeaders = [
295
- path6.join(include, "wasm64-wasip1-threads/wasi/version.h"),
296
- path6.join(include, "c++/v1/__config")
297
- ];
298
- flags = targetHeaders.every(
299
- (file) => fs2.existsSync(file) && fs2.readFileSync(file, "utf8").includes("__is_target_os(wasi)")
300
- ) ? ["-U__wasi__"] : [];
301
- appPlatformFlags.set(headers, flags);
302
- }
303
- return [
304
- ...objcSdkIntakeFlags(headers, toolchainBin, minimum, overlayDirectory),
305
- ...flags
306
- ];
307
- }
308
- function iosDeploymentMinimum(version) {
309
- const parts = /^(\d{1,2})(?:\.(\d{1,2}))?(?:\.(\d{1,2}))?$/.exec(version ?? "");
310
- if (!parts) return void 0;
311
- return Number(parts[1]) * 1e4 + Number(parts[2] ?? 0) * 100 + Number(parts[3] ?? 0);
312
- }
313
-
314
- // src/swift-distribution-contract.ts
315
- var SWIFT_DISTRIBUTION_MANIFEST = "distribution.json";
316
- var SWIFT_DISTRIBUTION_OBJC_SELECTORS = "objc-selectors.json";
317
- var SWIFT_DISTRIBUTION_HOSTS = [
318
- "darwin-arm64",
319
- "linux-x64",
320
- "linux-arm64"
321
- ];
322
- var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
323
- function parseSwiftDistributionManifest(value) {
324
- if (!isRecord(value) || typeof value.id !== "string" || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || !isStrings(value.modules) || !isStrings(value.objects) || !isStrings(value.link) || !isRecord(value.files) || !Object.values(value.files).every((sha) => typeof sha === "string") || typeof value.host !== "string" || !isStrings(value.plugins)) {
325
- throw new Error(`invalid Swift distribution ${SWIFT_DISTRIBUTION_MANIFEST}`);
326
- }
327
- const host = SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === value.host);
328
- if (!host) throw new Error(`Swift distribution names an unknown host ${value.host}`);
329
- const uikitCommitAbi = typeof value.uikitCommitAbi === "string" && /^[a-f0-9]{16}$/.test(value.uikitCommitAbi) ? value.uikitCommitAbi : void 0;
330
- const sourceId = typeof value.sourceId === "string" && /^[a-f0-9]{16}$/.test(value.sourceId) ? value.sourceId : void 0;
331
- return {
332
- id: value.id,
333
- ...sourceId ? { sourceId } : {},
334
- release: value.release,
335
- ...uikitCommitAbi ? { uikitCommitAbi } : {},
336
- wasmSdkId: value.wasmSdkId,
337
- wasmSdkUrl: value.wasmSdkUrl,
338
- wasmSdkChecksum: value.wasmSdkChecksum,
339
- modules: value.modules,
340
- objects: value.objects,
341
- link: value.link,
342
- files: Object.fromEntries(
343
- Object.entries(value.files).map(([file, sha]) => [file, String(sha)])
344
- ),
345
- host,
346
- plugins: value.plugins
347
- };
348
- }
349
- function parseSwiftDistributionLock(value) {
350
- if (!isRecord(value) || typeof value.id !== "string" || !/^[a-f0-9]{16}$/.test(value.id) || value.archive !== void 0 && value.archive !== "tar.gz" && value.archive !== "tar.zst" || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || typeof value.source !== "string" || !isStrings(value.targets) || !isRecord(value.systemEnvironment) || !Object.values(value.systemEnvironment).every(isStrings) || !isRecord(value.hosts)) {
351
- throw new Error("invalid Swift distribution lock");
352
- }
353
- const hosts = value.hosts;
354
- const publication = (runtime) => {
355
- if (runtime === void 0) return void 0;
356
- if (!isRecord(runtime) || typeof runtime.source !== "string" || !/^[a-f0-9]{64}$/.test(runtime.source) || typeof runtime.url !== "string" || !/^https:\/\/[a-z0-9.-]+(?::\d+)?\/compile\/asset\/[a-f0-9]{64}$/.test(
357
- runtime.url
358
- ) || runtime.dataPlan !== void 0 && (typeof runtime.dataPlan !== "string" || !/^[a-f0-9]{64}$/.test(runtime.dataPlan)) || runtime.recipe !== void 0 && (typeof runtime.recipe !== "string" || !/^[a-f0-9]{16}$/.test(runtime.recipe)))
359
- throw new Error("invalid shared SDK runtime publication in Swift distribution lock");
360
- return {
361
- source: runtime.source,
362
- url: runtime.url,
363
- ...runtime.dataPlan && { dataPlan: runtime.dataPlan },
364
- ...runtime.recipe && { recipe: runtime.recipe }
365
- };
366
- };
367
- const sdkRuntime = publication(value.sdkRuntime);
368
- const sdkGuestRuntime = publication(value.sdkGuestRuntime);
369
- const entry = (host) => {
370
- const item = hosts[host];
371
- if (!isRecord(item) || typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256) || typeof item.size !== "number") {
372
- throw new Error(`invalid Swift distribution lock entry for ${host}`);
373
- }
374
- return { sha256: item.sha256, size: item.size };
375
- };
376
- return {
377
- id: value.id,
378
- release: value.release,
379
- archive: value.archive ?? "tar.gz",
380
- wasmSdkId: value.wasmSdkId,
381
- wasmSdkUrl: value.wasmSdkUrl,
382
- wasmSdkChecksum: value.wasmSdkChecksum,
383
- source: value.source,
384
- targets: value.targets,
385
- systemEnvironment: Object.fromEntries(
386
- Object.entries(value.systemEnvironment).map(([key, values]) => {
387
- if (!isStrings(values))
388
- throw new Error(`invalid Swift system environment values for ${key}`);
389
- return [key, values];
390
- })
391
- ),
392
- hosts: {
393
- "darwin-arm64": entry("darwin-arm64"),
394
- "linux-x64": entry("linux-x64"),
395
- "linux-arm64": entry("linux-arm64")
396
- },
397
- ...sdkRuntime ? { sdkRuntime } : {},
398
- ...sdkGuestRuntime ? { sdkGuestRuntime } : {}
399
- };
400
- }
401
-
402
- // src/swift-lexical.ts
403
- var SWIFT_SCAN_KEYWORDS = {
404
- c: "class",
405
- e: "extension",
406
- o: "override",
407
- i: "import",
408
- f: "func",
409
- U: "UIApplicationMain",
410
- F: "Foundation",
411
- C: "CoreFoundation",
412
- O: "ObjectiveC",
413
- _: "_LocationEssentials"
414
- };
415
- function swiftCodeScan(source) {
416
- const starts = /* @__PURE__ */ new Set();
417
- const tokens = [];
418
- const stack = [{ kind: "code", parens: 0 }];
419
- const hashesAt = (at) => {
420
- let end = at;
421
- while (source[end] === "#") end++;
422
- return end - at;
423
- };
424
- const closes = (at, hashes) => source.startsWith("#".repeat(hashes), at);
425
- let i = 0;
426
- while (i < source.length) {
427
- const top = stack[stack.length - 1];
428
- if ((i === 0 || source[i - 1] === "\n") && top.kind === "code" && stack.length === 1)
429
- starts.add(i);
430
- const char = source[i];
431
- if (top.kind === "block") {
432
- if (source.startsWith("/*", i)) {
433
- top.depth++;
434
- i += 2;
435
- } else if (source.startsWith("*/", i)) {
436
- if (--top.depth === 0) stack.pop();
437
- i += 2;
438
- } else i++;
439
- continue;
440
- }
441
- if (top.kind === "string") {
442
- if (char === "\\" && closes(i + 1, top.hashes)) {
443
- const after = i + 1 + top.hashes;
444
- if (source[after] === "(") {
445
- stack.push({ kind: "code", parens: 0 });
446
- i = after + 1;
447
- } else i = after + 1;
448
- continue;
449
- }
450
- const quote = top.multiline ? '"""' : '"';
451
- if (source.startsWith(quote, i) && closes(i + quote.length, top.hashes)) {
452
- stack.pop();
453
- i += quote.length + top.hashes;
454
- } else i++;
455
- continue;
456
- }
457
- if (top.kind === "regex") {
458
- if (char === "/" && closes(i + 1, top.hashes)) {
459
- stack.pop();
460
- i += 1 + top.hashes;
461
- } else i++;
462
- continue;
463
- }
464
- if (source.startsWith("//", i)) {
465
- const end = source.indexOf("\n", i);
466
- i = end === -1 ? source.length : end;
467
- } else if (source.startsWith("/*", i)) {
468
- stack.push({ kind: "block", depth: 1 });
469
- i += 2;
470
- } else if (char === '"' || char === "#") {
471
- const hashes = hashesAt(i);
472
- const at = i + hashes;
473
- if (source.startsWith('"""', at)) {
474
- stack.push({ kind: "string", hashes, multiline: true });
475
- i = at + 3;
476
- } else if (source[at] === '"') {
477
- stack.push({ kind: "string", hashes, multiline: false });
478
- i = at + 1;
479
- } else if (hashes > 0 && source[at] === "/") {
480
- stack.push({ kind: "regex", hashes });
481
- i = at + 1;
482
- } else {
483
- if (hashes > 0) tokens.push(at - 1);
484
- i = Math.max(at, i + 1);
485
- }
486
- } else if (char === "{" || char === "}") {
487
- tokens.push(i);
488
- i++;
489
- } else if (char === "(") {
490
- top.parens++;
491
- i++;
492
- } else if (char === ")") {
493
- if (top.parens === 0 && stack.length > 1) stack.pop();
494
- else top.parens--;
495
- i++;
496
- } else {
497
- const keyword = SWIFT_SCAN_KEYWORDS[char];
498
- if (keyword && source.startsWith(keyword, i) && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + keyword.length] ?? "")) {
499
- tokens.push(i);
500
- i += keyword.length;
501
- } else {
502
- if (char === "@") tokens.push(i);
503
- i++;
504
- }
505
- }
506
- }
507
- return { lineStarts: starts, tokens };
508
- }
509
- function mapSwiftConditionalLines(source, lineStarts, map) {
510
- let offset = 0;
511
- return source.split("\n").map((line) => {
512
- const start = offset;
513
- offset += line.length + 1;
514
- return lineStarts.has(start) && /^[ \t]*#(?:if|elseif)\b/.test(line) ? map(line) : line;
515
- }).join("\n");
516
- }
517
-
518
- // src/wasm-binary-sections.ts
519
- function encodeWasmNumber(value) {
520
- const bytes = [];
521
- for (let rest = value; ; ) {
522
- const byte = rest % 128;
523
- rest = Math.floor(rest / 128);
524
- if (rest === 0) return [...bytes, byte];
525
- bytes.push(byte | 128);
526
- }
527
- }
528
- function encodeWasmSigned(value) {
529
- const out = [];
530
- for (; ; ) {
531
- const byte = Number(value & 127n);
532
- value >>= 7n;
533
- if (value === 0n && !(byte & 64) || value === -1n && byte & 64) {
534
- out.push(byte);
535
- return out;
536
- }
537
- out.push(byte | 128);
538
- }
539
- }
540
- function encodeWasmName(name) {
541
- const bytes = new TextEncoder().encode(name);
542
- return [...encodeWasmNumber(bytes.length), ...bytes];
543
- }
544
- function readULEB(bytes, offset, end = bytes.length) {
545
- if (offset < end) {
546
- const first = bytes[offset];
547
- if (first < 128) return [first, offset + 1];
548
- }
549
- let value = 0;
550
- for (let shift = 0; ; shift += 7) {
551
- if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
552
- const byte = bytes[offset++];
553
- value += (byte & 127) * 2 ** shift;
554
- if (!(byte & 128)) return [value, offset];
555
- }
556
- }
557
- function readSLEB(bytes, offset, end = bytes.length) {
558
- let value = 0n;
559
- let shift = 0n;
560
- let byte = 0;
561
- do {
562
- if (offset >= end || shift > 70n) throw new Error("invalid wasm integer");
563
- byte = bytes[offset++];
564
- value |= BigInt(byte & 127) << shift;
565
- shift += 7n;
566
- } while (byte & 128);
567
- if (byte & 64) value -= 1n << shift;
568
- return [value, offset];
569
- }
570
- function skipLEB(bytes, offset) {
571
- while ((bytes[offset++] & 128) !== 0) {
572
- }
573
- return offset;
574
- }
575
- function readWasmSection(bytes, start, end) {
576
- let at = start;
577
- const number = () => {
578
- const [value, next] = readULEB(bytes, at, end);
579
- at = next;
580
- return value;
581
- };
582
- return {
583
- number,
584
- byte: () => {
585
- if (at >= end) throw new Error("truncated wasm section");
586
- return bytes[at++];
587
- },
588
- name: () => {
589
- const length = number();
590
- at += length;
591
- if (at > end) throw new Error("truncated wasm name");
592
- return Buffer.from(bytes.buffer, bytes.byteOffset + at - length, length).toString();
593
- },
594
- skip: (length) => {
595
- at += length;
596
- if (at > end) throw new Error("truncated wasm section");
597
- },
598
- position: () => at,
599
- done: () => at === end
600
- };
601
- }
602
- function wasmSections(bytes) {
603
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
604
- throw new Error("not a wasm module");
605
- const found = [];
606
- for (let at = 8; at < bytes.length; ) {
607
- const header = readWasmSection(bytes, at, bytes.length);
608
- const id = header.byte();
609
- const size = header.number();
610
- const start = header.position();
611
- if (start + size > bytes.length) throw new Error("truncated wasm section");
612
- found.push({ id, offset: at, start, end: start + size });
613
- at = start + size;
614
- }
615
- return found;
616
- }
617
-
618
- // src/swift-shared-sdk.ts
619
- import { execFileSync as execFileSync2 } from "node:child_process";
620
- import { createHash as createHash3 } from "node:crypto";
621
- import fs3, { readdirSync as readdirSync2, readFileSync as readFileSync3 } from "node:fs";
622
- import path7 from "node:path";
623
- var SWIFT_DISTRIBUTION_MIRROR_RECORD = ".peach-mirror.json";
624
- var distributionHeaderRoots = /* @__PURE__ */ new Map();
625
- function swiftSharedSdkSourceRoot(moduleRoot, distribution) {
626
- return path7.resolve(moduleRoot, distribution ? "sdk/ios" : "../peachsim/sdk/ios");
627
- }
628
- function swiftSharedSdkRoot(moduleRoot, distribution) {
629
- const root = swiftSharedSdkSourceRoot(moduleRoot, distribution);
630
- if (!distribution || fs3.existsSync(path7.join(moduleRoot, SWIFT_DISTRIBUTION_MIRROR_RECORD)))
631
- return root;
632
- let headers = distributionHeaderRoots.get(root);
633
- if (!headers || !fs3.existsSync(headers)) {
634
- const files = readdirSync2(root, { recursive: true, withFileTypes: true }).filter((entry) => entry.isFile()).map((entry) => path7.relative(root, path7.join(entry.parentPath, entry.name))).sort();
635
- const hash = createHash3("sha256");
636
- for (const file of files) {
637
- const bytes = readFileSync3(path7.join(root, file));
638
- hash.update(JSON.stringify([file, bytes.length])).update(bytes);
639
- }
640
- headers = path7.join(
641
- swiftCacheDir(),
642
- "swift-sdk-views",
643
- `headers-${hash.digest("hex")}`
644
- );
645
- if (!fs3.existsSync(headers)) {
646
- fs3.mkdirSync(path7.dirname(headers), { recursive: true });
647
- const staging = fs3.mkdtempSync(`${headers}-`);
648
- fs3.chmodSync(staging, 493);
649
- fs3.cpSync(root, staging, { recursive: true, preserveTimestamps: true });
650
- try {
651
- fs3.renameSync(staging, headers);
652
- } catch (error) {
653
- fs3.rmSync(staging, { recursive: true, force: true });
654
- if (!fs3.existsSync(headers)) throw error;
655
- }
656
- }
657
- distributionHeaderRoots.set(root, headers);
658
- }
659
- const now = /* @__PURE__ */ new Date();
660
- fs3.utimesSync(headers, now, now);
661
- refreshSwiftCacheHold(headers);
662
- return headers;
663
- }
664
- function swiftSharedSdkFlags(moduleRoot, distribution) {
665
- const root = swiftSharedSdkRoot(moduleRoot, distribution);
666
- return [
667
- ...wasmThreadFlags,
668
- "-isystem",
669
- path7.join(root, "wasm/storage-include"),
670
- "-idirafter",
671
- path7.join(root, "usr/include")
672
- ];
673
- }
674
- var WEAKEN_FOUNDATION_SYMS = /* @__PURE__ */ new Set([
675
- "$s10Foundation6BundleC22preferredLocalizations4from14forPreferencesSaySSGAG_AGSgtFZ",
676
- "$s10Foundation6BundleC22preferredLocalizations4fromSaySSGAF_tFZ",
677
- "$s10Foundation6BundleC22preferredLocalizationsSaySSGvg",
678
- "$s10Foundation16NSSortDescriptorC3key9ascendingACSSSg_SbtcfC",
679
- "$s10Foundation16NSSortDescriptorC3key9ascendingACSSSg_Sbtcfc",
680
- "$s10Foundation16NSSortDescriptorC3keySSSgvg",
681
- "$s10Foundation16NSSortDescriptorC7keyPath9ascendingACs03KeyE0Cyxq_G_SbtcSLR_r0_lufC",
682
- "$s10Foundation16NSSortDescriptorC7keyPath9ascendingACs03KeyE0Cyxq_G_SbtcSLR_r0_lufc"
683
- ]);
684
- function weakenFoundationSymbolsInWasmObj(buf) {
685
- let pos = 8;
686
- while (pos < buf.length) {
687
- const id = buf[pos++];
688
- const [sz, p] = readULEB(buf, pos);
689
- const end = p + sz;
690
- if (id === 0) {
691
- const [nLen, np] = readULEB(buf, p);
692
- const name = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
693
- const cp = np + nLen;
694
- if (name === "linking") {
695
- let [, lp] = readULEB(buf, cp);
696
- while (lp < end) {
697
- const subId = buf[lp++];
698
- const [subLen, sp] = readULEB(buf, lp);
699
- const subEnd = sp + subLen;
700
- if (subId === 8) {
701
- let [cnt, cur] = readULEB(buf, sp);
702
- for (let i = 0; i < cnt; i++) {
703
- const kind = buf[cur++];
704
- const flOffset = cur;
705
- const [fl, c2] = readULEB(buf, cur);
706
- cur = c2;
707
- const isUndef = (fl & 16) !== 0;
708
- const isExplicitName = (fl & 64) !== 0;
709
- if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
710
- const [, c3] = readULEB(buf, cur);
711
- cur = c3;
712
- if (!isUndef || isExplicitName) {
713
- const [sLen, c4] = readULEB(buf, cur);
714
- const sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
715
- if (!isUndef && kind === 0 && WEAKEN_FOUNDATION_SYMS.has(sName)) {
716
- buf[flOffset] = buf[flOffset] & ~3 | 1;
717
- }
718
- cur = c4 + sLen;
719
- }
720
- } else if (kind === 1) {
721
- const [sLen, c3] = readULEB(buf, cur);
722
- cur = c3 + sLen;
723
- if (!isUndef) {
724
- const [, c4] = readULEB(buf, cur);
725
- const [, c5] = readULEB(buf, c4);
726
- const [, c6] = readULEB(buf, c5);
727
- cur = c6;
728
- }
729
- } else if (kind === 3) {
730
- const [, c3] = readULEB(buf, cur);
731
- cur = c3;
732
- }
733
- }
734
- }
735
- lp = subEnd;
736
- }
737
- }
738
- }
739
- pos = end;
740
- }
741
- }
742
- function weakenFoundationOverridesInArchive(arBuf) {
743
- let gnuNames = null;
744
- let pos = 8;
745
- while (pos + 60 <= arBuf.length) {
746
- const rawName = Buffer.from(arBuf.subarray(pos, pos + 16)).toString("ascii");
747
- const size = Number.parseInt(
748
- Buffer.from(arBuf.subarray(pos + 48, pos + 58)).toString("ascii").trim(),
749
- 10
750
- );
751
- pos += 60;
752
- if (Number.isNaN(size) || pos + size > arBuf.length) break;
753
- let bodyStart = pos;
754
- const bodyEnd = pos + size;
755
- let name = rawName.trim();
756
- if (rawName.startsWith("#1/")) {
757
- const nLen = Number.parseInt(rawName.slice(3).trim(), 10);
758
- name = Buffer.from(arBuf.subarray(bodyStart, bodyStart + nLen)).toString("utf8").replace(/\0+$/, "");
759
- bodyStart += nLen;
760
- } else if (rawName.startsWith("//")) {
761
- gnuNames = arBuf.subarray(bodyStart, bodyEnd);
762
- pos = bodyEnd + (size & 1);
763
- continue;
764
- } else if (rawName.startsWith("/") && gnuNames) {
765
- const offStr = rawName.slice(1).trim();
766
- if (offStr.length > 0 && /^\d+$/.test(offStr)) {
767
- const off = Number.parseInt(offStr, 10);
768
- let end = off;
769
- while (end < gnuNames.length && gnuNames[end] !== 10 && gnuNames[end] !== 47) {
770
- end++;
771
- }
772
- name = Buffer.from(gnuNames.subarray(off, end)).toString("utf8");
773
- } else {
774
- pos = bodyEnd + (size & 1);
775
- continue;
776
- }
777
- } else if (name.endsWith("/")) {
778
- name = name.slice(0, -1);
779
- }
780
- if (name.endsWith("Bundle.o") || name.endsWith("NSSortDescriptor.o")) {
781
- weakenFoundationSymbolsInWasmObj(arBuf.subarray(bodyStart, bodyEnd));
782
- }
783
- pos = bodyEnd + (size & 1);
784
- }
785
- }
786
- function mirrorTree(real, mirror, overrides) {
787
- fs3.mkdirSync(mirror);
788
- for (const entry of fs3.readdirSync(real, { withFileTypes: true })) {
789
- const from = path7.join(real, entry.name);
790
- const to = path7.join(mirror, entry.name);
791
- const override = overrides.get(from);
792
- if (override) fs3.symlinkSync(override, to);
793
- else if (fs3.statSync(from).isDirectory()) mirrorTree(from, to, overrides);
794
- else fs3.symlinkSync(from, to);
795
- }
796
- }
797
- function stageOverlaySlot(realRoot, stagingRoot, relPath) {
798
- const segments = relPath.split(path7.sep);
799
- let real = realRoot;
800
- let mirror = stagingRoot;
801
- for (let i = 0; i < segments.length; i++) {
802
- const segment = segments[i];
803
- for (const entry of readdirSync2(real)) {
804
- if (entry === segment || i === 0 && entry === SWIFT_CACHE_HOLD_MARKER) continue;
805
- if (mirror === stagingRoot && entry === "configuration") continue;
806
- const dest = path7.join(mirror, entry);
807
- if (!fs3.lstatSync(dest, { throwIfNoEntry: false })) {
808
- fs3.symlinkSync(path7.join(real, entry), dest);
809
- }
810
- }
811
- real = path7.join(real, segment);
812
- mirror = path7.join(mirror, segment);
813
- if (i < segments.length - 1) {
814
- if (fs3.lstatSync(mirror, { throwIfNoEntry: false })?.isSymbolicLink()) {
815
- fs3.unlinkSync(mirror);
816
- }
817
- fs3.mkdirSync(mirror, { recursive: true });
818
- }
819
- }
820
- if (fs3.lstatSync(mirror, { throwIfNoEntry: false })?.isSymbolicLink()) {
821
- fs3.unlinkSync(mirror);
822
- }
823
- return mirror;
824
- }
825
- var sdkViews = /* @__PURE__ */ new Map();
826
- function swiftSharedSdkViewOptions(moduleRoot, distribution, toolchainBin, sdk) {
827
- const sdkRoot = swiftSharedSdkRoot(moduleRoot, distribution);
828
- const frameworks = path7.join(sdkRoot, "System/Library/Frameworks");
829
- const overlay = path7.join(sdkRoot, "wasm");
830
- const overlayFiles = ["include", "storage-include"].flatMap(
831
- (directory) => readdirSync2(path7.join(overlay, directory), {
832
- recursive: true,
833
- withFileTypes: true
834
- })
835
- ).filter((entry) => entry.isFile()).map((entry) => path7.join(entry.parentPath, entry.name)).sort();
836
- const hasDarwinTcp = overlayFiles.includes(path7.join(overlay, "include/netinet/tcp.h"));
837
- const hasDarwinTermios = fs3.existsSync(path7.join(sdkRoot, "usr/include/termios.h"));
838
- const stdint = path7.join(overlay, "include/stdint.h");
839
- const key = JSON.stringify([
840
- // bump the recipe when the transformation changes; bundling changes function text.
841
- "v40",
842
- [...WEAKEN_FOUNDATION_SYMS],
843
- toolchainBin,
844
- sdk,
845
- frameworks,
846
- overlayFiles,
847
- swiftSdkOptions(),
848
- ...hasDarwinTcp ? ["darwin-tcp-module"] : [],
849
- ...hasDarwinTermios ? ["darwin-termios"] : [],
850
- // the view copies this overlay, so its bytes name the view
851
- overlayFiles.includes(stdint) ? fs3.readFileSync(stdint, "utf8") : null
852
- ]);
853
- const cached = sdkViews.get(key);
854
- if (cached && fs3.existsSync(cached.manifest))
855
- return touchSdkView(cached.options, cached.bundle);
856
- const configuration = execFileSync2(
857
- path7.join(toolchainBin, "swift"),
858
- [
859
- "sdk",
860
- "configure",
861
- ...swiftSdkOptions(),
862
- "--show-configuration",
863
- sdk,
864
- SWIFT_WASM_TRIPLE
865
- ],
866
- { encoding: "utf8", env: swiftEnvironment(), stdio: ["ignore", "pipe", "pipe"] }
867
- );
868
- const sysroot = /^sdkRootPath: (.+)$/m.exec(configuration)?.[1]?.trim();
869
- if (!sysroot || !path7.isAbsolute(sysroot))
870
- throw new Error(`swift sdk ${sdk} reports no absolute sdkRootPath`);
871
- let bundle = sysroot;
872
- while (!bundle.endsWith(".artifactbundle")) {
873
- if (path7.dirname(bundle) === bundle)
874
- throw new Error(`swift sdk ${sdk} is outside an artifact bundle`);
875
- bundle = path7.dirname(bundle);
876
- }
877
- const foundationArchive = path7.join(
878
- path7.dirname(sysroot),
879
- "swift.xctoolchain/usr/lib/swift_static/wasi/libFoundation.a"
880
- );
881
- const foundationBytes = fs3.existsSync(foundationArchive) ? new Uint8Array(fs3.readFileSync(foundationArchive)) : void 0;
882
- const view = path7.join(
883
- swiftCacheDir(),
884
- "swift-sdk-views",
885
- createHash3("sha256").update(key).update(foundationBytes ?? "").digest("hex").slice(0, 16)
886
- );
887
- const manifest = path7.join(view, path7.basename(bundle), "info.json");
888
- const intact = () => !fs3.lstatSync(path7.join(view, SWIFT_CACHE_HOLD_MARKER), {
889
- throwIfNoEntry: false
890
- })?.isSymbolicLink() && fs3.existsSync(manifest) && fs3.readdirSync(
891
- path7.join(
892
- view,
893
- path7.relative(path7.dirname(bundle), sysroot),
894
- "darwin/usr/include"
895
- ),
896
- { withFileTypes: true }
897
- ).every(
898
- (entry) => !entry.isSymbolicLink() || fs3.existsSync(path7.join(entry.parentPath, entry.name))
899
- );
900
- if (!intact()) {
901
- fs3.rmSync(view, { recursive: true, force: true });
902
- fs3.mkdirSync(path7.dirname(view), { recursive: true });
903
- const staging = fs3.mkdtempSync(`${view}-`);
904
- fs3.chmodSync(staging, 493);
905
- const realRoot = path7.dirname(bundle);
906
- const overrides = new Map([
907
- [path7.join(sysroot, "darwin/System/Library/Frameworks"), frameworks],
908
- ...[
909
- "MacTypes.h",
910
- "objc/NSObject.h",
911
- "ObjectiveC.apinotes",
912
- "net/if.h",
913
- "netinet/tcp.h",
914
- "paths.h",
915
- "sys/paths.h",
916
- "sys/filio.h",
917
- "sys/sockio.h",
918
- "sys/time.h",
919
- "sys/proc.h",
920
- "sys/_types/_itimerval.h",
921
- "termios.h",
922
- "sys/termios.h",
923
- "sys/ttycom.h",
924
- "sys/ttydefaults.h",
925
- "notify.h",
926
- "notify.modulemap",
927
- "module.modulemap",
928
- "darwin.modulemap",
929
- "MachO.modulemap",
930
- "mach/clock_reply.h",
931
- "mach-o/arm/reloc.h",
932
- "mach-o/arm64/reloc.h",
933
- "mach-o/dyld.h",
934
- "mach-o/dyld_images.h",
935
- "mach-o/fixup-chains.h",
936
- "mach-o/ldsyms.h",
937
- "mach-o/nlist.h",
938
- "mach-o/ranlib.h",
939
- "mach-o/reloc.h",
940
- "mach-o/swap.h",
941
- "mach-o/x86_64/reloc.h"
942
- ].filter((header) => fs3.existsSync(path7.join(sdkRoot, "usr/include", header))).map((header) => [
943
- path7.join(sysroot, "darwin/usr/include", header),
944
- path7.join(sdkRoot, "usr/include", header)
945
- ])
946
- ]);
947
- for (const file of overlayFiles)
948
- overrides.set(path7.join(sysroot, "darwin/wasm", path7.relative(overlay, file)), file);
949
- mirrorTree(
950
- sysroot,
951
- stageOverlaySlot(realRoot, staging, path7.relative(realRoot, sysroot)),
952
- overrides
953
- );
954
- for (const [file, shared] of overrides) {
955
- const destination = path7.join(staging, path7.relative(realRoot, file));
956
- if (fs3.lstatSync(destination, { throwIfNoEntry: false })) continue;
957
- fs3.mkdirSync(path7.dirname(destination), { recursive: true });
958
- fs3.symlinkSync(shared, destination);
959
- }
960
- const wasmInclude = path7.join(path7.relative(realRoot, sysroot), "darwin/wasm/include");
961
- const moduleMap = path7.join(staging, wasmInclude, "module.modulemap");
962
- const original = fs3.readFileSync(moduleMap, "utf8");
963
- let updated = original;
964
- if (hasDarwinTcp) {
965
- updated = updated.replace(
966
- '"../../../include/wasm64-wasip1/netinet/tcp.h"',
967
- '"netinet/tcp.h"'
968
- );
969
- }
970
- const wasiModule = updated.indexOf("\nmodule SwiftWASILibc [system] {");
971
- if (wasiModule !== -1) {
972
- let foundation = updated.slice(0, wasiModule);
973
- let libc = updated.slice(wasiModule);
974
- for (const [layer, name] of [
975
- [1, "_arm_arch_h"],
976
- [1, "_machine__endian_h"],
977
- [1, "_sys__types__os_inline_h"],
978
- [2, "_libkern__OSByteOrder_h"],
979
- [2, "_libkern_OSByteOrder_h"],
980
- [2, "_libkern_arm_OSByteOrder_h"],
981
- [2, "_machine_endian_h"],
982
- [2, "_sys__endian_h"]
983
- ]) {
984
- const member = new RegExp(`^ module ${name} \\{\\n[^}]+^ \\}\\n`, "m");
985
- const block = libc.match(member)?.[0];
986
- if (!block) continue;
987
- libc = libc.replace(member, "");
988
- foundation = foundation.replace(
989
- `module _DarwinFoundation${layer} [system] {
990
- module Darwin {
991
- `,
992
- (declaration) => declaration + block
993
- );
994
- }
995
- updated = foundation + libc;
996
- }
997
- if (overlayFiles.includes(stdint)) {
998
- fs3.writeFileSync(
999
- stageOverlaySlot(realRoot, staging, path7.join(wasmInclude, "stdint.h")),
1000
- fs3.readFileSync(stdint, "utf8").replace(/^#pragma once\n/, "")
1001
- );
1002
- }
1003
- if (fs3.existsSync(path7.join(staging, wasmInclude, "stdint.h")) && !/^\s*header "(?:\.\.\/include\/)?stdint\.h"$/m.test(updated)) {
1004
- updated = updated.replace(
1005
- "module _DarwinFoundation2 [system] {\n module Darwin {\n",
1006
- '$& module _stdint_h {\n header "stdint.h"\n export *\n }\n'
1007
- );
1008
- }
1009
- if (updated !== original) {
1010
- fs3.unlinkSync(moduleMap);
1011
- fs3.writeFileSync(moduleMap, updated);
1012
- }
1013
- if (foundationBytes) {
1014
- const foundationSlot = stageOverlaySlot(
1015
- realRoot,
1016
- staging,
1017
- path7.relative(realRoot, foundationArchive)
1018
- );
1019
- weakenFoundationOverridesInArchive(foundationBytes);
1020
- fs3.writeFileSync(foundationSlot, foundationBytes);
1021
- }
1022
- try {
1023
- fs3.renameSync(staging, view);
1024
- } catch (error) {
1025
- fs3.rmSync(staging, { recursive: true, force: true });
1026
- if (!intact()) throw error;
1027
- }
1028
- }
1029
- const options = ["--swift-sdks-path", view];
1030
- sdkViews.set(key, { options, manifest, bundle });
1031
- return touchSdkView(options, bundle);
1032
- }
1033
- function touchSdkView(options, bundle) {
1034
- const now = /* @__PURE__ */ new Date();
1035
- fs3.utimesSync(options[1], now, now);
1036
- fs3.utimesSync(bundle, now, now);
1037
- refreshSwiftCacheHold(options[1]);
1038
- return options;
1039
- }
1040
- function swiftSharedSdkInputFiles(moduleRoot) {
1041
- const root = swiftSharedSdkRoot(moduleRoot, false);
1042
- return readdirSync2(root, { recursive: true, withFileTypes: true }).filter((entry) => entry.isFile()).map((entry) => path7.relative(moduleRoot, path7.join(entry.parentPath, entry.name))).sort();
1043
- }
1044
-
1045
- // src/swift-sdk-surface.ts
1046
- import { AsyncLocalStorage } from "node:async_hooks";
1047
- import { execFileSync as execFileSync3, spawnSync as spawnSync3 } from "node:child_process";
1048
- import { createHash as createHash4, randomUUID } from "node:crypto";
1049
- import {
1050
- chmodSync,
1051
- copyFileSync,
1052
- existsSync,
1053
- mkdirSync as mkdirSync2,
1054
- mkdtempSync,
1055
- readFileSync as readFileSync4,
1056
- readdirSync as readdirSync3,
1057
- realpathSync,
1058
- renameSync,
1059
- rmSync,
1060
- statSync as statSync2,
1061
- utimesSync,
1062
- writeFileSync as writeFileSync2
1063
- } from "node:fs";
1064
- import os from "node:os";
1065
- import path8 from "node:path";
1066
-
1067
- // ../peach-globals/build/swift-source-mask.ts
1068
- function maskSwiftCode(source) {
1069
- const chars = source.split("");
1070
- const blank = (from, to) => {
1071
- for (let i = Math.max(0, from); i < Math.min(to, chars.length); i++)
1072
- if (chars[i] !== "\n") chars[i] = " ";
1073
- };
1074
- const hashesAt = (at) => {
1075
- let end = at;
1076
- while (source[end] === "#") end++;
1077
- return end - at;
1078
- };
1079
- const scanString = (quote, hashes) => {
1080
- const multiline = source.startsWith('"""', quote);
1081
- let i = quote + (multiline ? 3 : 1);
1082
- const keep = [];
1083
- const quoteEnd = (at) => {
1084
- const mark = multiline ? '"""' : '"';
1085
- return source.startsWith(mark, at) && source.startsWith("#".repeat(hashes), at + mark.length);
1086
- };
1087
- while (i < chars.length) {
1088
- if (source[i] === "\\" && source.startsWith("#".repeat(hashes), i + 1)) {
1089
- const escaped = i + 1 + hashes;
1090
- if (source[escaped] === "(") {
1091
- const codeStart = escaped + 1;
1092
- const codeEnd = scanCode(codeStart, true);
1093
- keep.push([codeStart, codeEnd]);
1094
- i = codeEnd + 1;
1095
- } else {
1096
- i = escaped + 1;
1097
- }
1098
- continue;
1099
- }
1100
- if (quoteEnd(i)) {
1101
- const close = i + (multiline ? 3 : 1) + hashes;
1102
- let cursor = quote - hashes;
1103
- const ranges = [...keep, [close, close]];
1104
- for (const [from, to] of ranges)
1105
- if (from > cursor) {
1106
- blank(cursor, from);
1107
- cursor = to;
1108
- } else cursor = Math.max(cursor, to);
1109
- return close;
1110
- }
1111
- i++;
1112
- }
1113
- blank(quote - hashes, chars.length);
1114
- return chars.length;
1115
- };
1116
- const scanCode = (i, nested) => {
1117
- let parens = 0;
1118
- while (i < chars.length) {
1119
- const char = source[i];
1120
- if (char === "/" && source[i + 1] === "/") {
1121
- const end = source.indexOf("\n", i);
1122
- blank(i, end === -1 ? chars.length : end);
1123
- i = end === -1 ? chars.length : end;
1124
- continue;
1125
- }
1126
- if (char === "/" && source[i + 1] === "*") {
1127
- let j = i + 2;
1128
- let depth = 1;
1129
- while (j < chars.length && depth > 0) {
1130
- if (source.startsWith("/*", j)) {
1131
- depth++;
1132
- j += 2;
1133
- } else if (source.startsWith("*/", j)) {
1134
- depth--;
1135
- j += 2;
1136
- } else j++;
1137
- }
1138
- blank(i, j);
1139
- i = j;
1140
- continue;
1141
- }
1142
- if (char === "#") {
1143
- const hashes = hashesAt(i);
1144
- const at = i + hashes;
1145
- if (source[at] === '"') {
1146
- i = scanString(at, hashes);
1147
- continue;
1148
- }
1149
- if (hashes > 0 && source[at] === "/") {
1150
- const mark = "#".repeat(hashes);
1151
- let j = at + 1;
1152
- while (j < chars.length && !(source[j] === "/" && source.startsWith(mark, j + 1)))
1153
- j++;
1154
- blank(i, Math.min(chars.length, j + 1 + hashes));
1155
- i = Math.min(chars.length, j + 1 + hashes);
1156
- continue;
1157
- }
1158
- i++;
1159
- continue;
1160
- }
1161
- if (char === '"') {
1162
- i = scanString(i, 0);
1163
- continue;
1164
- }
1165
- if (char === "(") parens++;
1166
- else if (char === ")") {
1167
- if (nested && parens === 0) return i;
1168
- parens--;
1169
- }
1170
- i++;
1171
- }
1172
- return i;
1173
- };
1174
- scanCode(0, false);
1175
- return chars.join("");
1176
- }
1177
-
1178
- // src/swift-sdk-surface.ts
1179
- function swiftSdkReplacedModules(product, sourceModules) {
1180
- const replaced = new Set(sourceModules);
1181
- if (replaced.size === 0) return replaced;
1182
- for (let changed = true; changed; ) {
1183
- changed = false;
1184
- for (const target of product.targets) {
1185
- const name = swiftTargetModuleName(target.name);
1186
- if (!replaced.has(name) && target.dependencies.some(
1187
- (dependency) => replaced.has(swiftTargetModuleName(dependency))
1188
- )) {
1189
- replaced.add(name);
1190
- changed = true;
1191
- }
1192
- }
1193
- }
1194
- return replaced;
1195
- }
1196
- function swiftBuildJobs() {
1197
- const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES);
1198
- const parallelism = Math.max(1, os.availableParallelism());
1199
- if (!Number.isInteger(admittedCores) || admittedCores <= 0)
1200
- return Math.min(4, Math.max(1, Math.floor(parallelism / 2)));
1201
- const cores = Math.min(admittedCores, parallelism);
1202
- if (process.platform === "darwin") return cores;
1203
- const memory = process.env.TM_EXEC_ADMITTED === "1" && process.env.LINUX_BUILD_SCOPE ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX) : NaN;
1204
- const effectiveMemory = Number.isSafeInteger(memory) && memory > 0 ? memory : os.totalmem();
1205
- const memoryJobs = Math.max(1, Math.floor(effectiveMemory / (2 * 1024 ** 3)));
1206
- return Math.min(cores, memoryJobs);
1207
- }
1208
- function swiftDistributionAt(root) {
1209
- const file = path8.join(root, SWIFT_DISTRIBUTION_MANIFEST);
1210
- const stat = statSync2(file, { bigint: true, throwIfNoEntry: false });
1211
- if (!stat) return null;
1212
- const identity = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}`;
1213
- const cached = distributionManifests.get(file);
1214
- if (cached?.identity === identity) return cached.manifest;
1215
- const manifest = parseSwiftDistributionManifest(JSON.parse(readFileSync4(file, "utf8")));
1216
- distributionManifests.set(file, { identity, manifest });
1217
- return manifest;
1218
- }
1219
- var distributionManifests = /* @__PURE__ */ new Map();
1220
- var distributionCompileViews = /* @__PURE__ */ new WeakMap();
1221
- function swiftDistributionCompileView(moduleRoot, distribution) {
1222
- let view = distributionCompileViews.get(distribution);
1223
- if (!view || !existsSync(view)) {
1224
- const inputs = Object.entries(distribution.files).filter(
1225
- ([file]) => file.startsWith("host/") || file === SWIFT_DISTRIBUTION_OBJC_SELECTORS
1226
- ).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
1227
- const digest = createHash4("sha256").update(JSON.stringify(inputs)).digest("hex");
1228
- view = path8.join(swiftCacheDir(), "swift-sdk-views", `compile-${digest}`);
1229
- if (!existsSync(view)) {
1230
- mkdirSync2(path8.dirname(view), { recursive: true });
1231
- const staging = mkdtempSync(`${view}-`);
1232
- try {
1233
- chmodSync(staging, 493);
1234
- for (const [file] of inputs) {
1235
- if (!isSwiftResourcePath(file))
1236
- throw new Error(`invalid Swift distribution compile path ${file}`);
1237
- const destination = path8.join(staging, file);
1238
- mkdirSync2(path8.dirname(destination), { recursive: true });
1239
- copyFileSync(path8.join(moduleRoot, file), destination);
1240
- }
1241
- try {
1242
- renameSync(staging, view);
1243
- } catch (error) {
1244
- if (!existsSync(view)) throw error;
1245
- }
1246
- } finally {
1247
- rmSync(staging, { recursive: true, force: true });
1248
- }
1249
- }
1250
- distributionCompileViews.set(distribution, view);
1251
- }
1252
- const now = /* @__PURE__ */ new Date();
1253
- utimesSync(view, now, now);
1254
- refreshSwiftCacheHold(view);
1255
- return view;
1256
- }
1257
- var REACH_STAGED_FRAMEWORKS = /* @__PURE__ */ new Set(["React"]);
1258
- function swiftModuleInterface(moduleRoot, name) {
1259
- if (REACH_STAGED_FRAMEWORKS.has(name)) return null;
1260
- if (swiftDistributionAt(moduleRoot)) {
1261
- const file = path8.join(moduleRoot, "modules", `${name}-Swift.h`);
1262
- if (!existsSync(file)) return null;
1263
- const header = clangInterfaceHeader(readFileSync4(file, "utf8"), moduleRoot);
1264
- return { declared: swiftInterfaceDeclarations(header), header };
1265
- }
1266
- const sources = path8.join(moduleRoot, "Sources", name);
1267
- const built = path8.join(moduleRoot, ".build/host", `${name}-Swift.h`);
1268
- if (!existsSync(sources) || !existsSync(built)) return null;
1269
- const declared = /* @__PURE__ */ new Set();
1270
- for (const file of readdirSync3(sources, { recursive: true, encoding: "utf8" }))
1271
- if (file.endsWith(".swift"))
1272
- for (const [, objc, subclass] of readFileSync4(
1273
- path8.join(sources, file),
1274
- "utf8"
1275
- ).matchAll(
1276
- /@objc\((\w+)\)\s+(?:\w+\s+)*?(?:protocol|class)\s|^(?:public|open)\s+(?:final\s+)?class\s+(\w+)\s*:\s*NSObject\b/gm
1277
- ))
1278
- declared.add(objc ?? subclass);
1279
- if (declared.size === 0) return null;
1280
- return {
1281
- declared,
1282
- header: clangInterfaceHeader(readFileSync4(built, "utf8"), moduleRoot)
1283
- };
1284
- }
1285
- function clangInterfaceHeader(header, moduleRoot) {
1286
- const distribution = swiftDistributionAt(moduleRoot) !== null;
1287
- const frameworks = path8.join(
1288
- swiftSharedSdkSourceRoot(moduleRoot, distribution),
1289
- "System/Library/Frameworks"
1290
- );
1291
- let references;
1292
- const imported = new Set(
1293
- [...header.matchAll(/^@import (\w+);$/gm)].map((match) => match[1])
1294
- );
1295
- return header.replace(/^@import (?:UIKitCore|UIKitText);$/gm, "@import UIKit;").replace(
1296
- /^@import ((\w+?)(?:Enums|Constants));$/gm,
1297
- (_, module, framework) => {
1298
- const imports = [`@import ${framework};`];
1299
- imported.add(framework);
1300
- const directory = distribution ? path8.join(moduleRoot, "modules", module) : path8.join(moduleRoot, "Sources", module, "include");
1301
- if (!existsSync(directory)) return imports[0];
1302
- if (!references) {
1303
- references = new Set(header.match(/\b[A-Z]\w*\b/g));
1304
- for (const name of objcEnumerations(header)) references.delete(name);
1305
- }
1306
- const owners = sdkObjCDeclarationOwners(frameworks);
1307
- for (const name of clangDeclarationEnums(directory)) {
1308
- const owner = references.has(name) ? owners.get(name) : void 0;
1309
- if (!owner || imported.has(owner)) continue;
1310
- imported.add(owner);
1311
- imports.push(`@import ${owner};`);
1312
- }
1313
- return imports.join("\n");
1314
- }
1315
- ).replace(
1316
- /^@import (?:CoreFoundation(?:_Private)?|FoundationNetworking|PeachFoundation);$/gm,
1317
- "@import Foundation;"
1318
- ).replace(/\b_TtC10Foundation\d+(NS\w+)\b/g, "$1").replace(/\b__attribute__\(\(objc_subclassing_restricted\)\)\s*/g, "");
1319
- }
1320
- var objcEnumerations = (header) => [
1321
- ...header.matchAll(
1322
- /^\s*typedef\s+(?:NS|CF|SWIFT)_\w*(?:ENUM|OPTIONS)\w*\s*\(\s*\w+\s*,\s*(\w+)\b/gm
1323
- )
1324
- ].map((match) => match[1]);
1325
- var clangDeclarationEnumCache = /* @__PURE__ */ new Map();
1326
- function clangDeclarationEnums(directory) {
1327
- const cached = clangDeclarationEnumCache.get(directory);
1328
- if (cached) return cached;
1329
- const enums = readdirSync3(directory).filter((file) => file.endsWith(".h")).flatMap((file) => objcEnumerations(readFileSync4(path8.join(directory, file), "utf8")));
1330
- clangDeclarationEnumCache.set(directory, enums);
1331
- return enums;
1332
- }
1333
- var objcEnumForward = /^[ \t]*SWIFT_ENUM_FWD_DECL\s*\(\s*\w+\s*,\s*(\w+)\b/;
1334
- function withoutImportedSdkEnumForwards(header, owners) {
1335
- const imports = new Set([...header.matchAll(/^@import (\w+);$/gm)].map((m) => m[1]));
1336
- return header.split("\n").filter((line) => {
1337
- const name = objcEnumForward.exec(line)?.[1];
1338
- const owner = name && owners.get(name);
1339
- return !owner || !imports.has(owner);
1340
- }).join("\n");
1341
- }
1342
- function nativelyDeclaredFunctions(generated, headers) {
1343
- const candidates = [
1344
- ...new Set(
1345
- [...generated.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
1346
- (match) => match[1]
1347
- )
1348
- )
1349
- ];
1350
- if (candidates.length === 0) return [];
1351
- const declaration = new RegExp(`^[^\\n#/*]*?\\b(${candidates.join("|")})\\s*\\(`, "gm");
1352
- const found = /* @__PURE__ */ new Set();
1353
- for (const header of headers)
1354
- for (const match of header.matchAll(declaration)) found.add(match[1]);
1355
- return [...found];
1356
- }
1357
- function sdkObjCDeclarations(header) {
1358
- return [
1359
- ...swiftInterfaceDeclarations(header),
1360
- ...objcEnumerations(header),
1361
- ...[...header.matchAll(/^[A-Z_]*_(?:EXTERN|EXPORT)\b[^;(\n]*?\b(\w+)\s*\(/gm)].map(
1362
- (match) => match[1]
1363
- )
1364
- ];
1365
- }
1366
- function sdkHeaderVisibleToSwift(header) {
1367
- const conditions = header.replace(
1368
- /^\s*#\s*if(n?)def[ \t]+(\w+)/gm,
1369
- (_, negated, name) => `#if ${negated ? "!" : ""}defined(${name})`
1370
- ).replace(/^\s*#\s*elif\b/gm, "#elseif").replace(/\bdefined\s*\(\s*(?:__OBJC__|__swift__)\s*\)/g, "true").replace(/\b__swift__\b/g, "true");
1371
- return Array.from(
1372
- swiftConditionalLines(conditions),
1373
- ({ line, active }) => active === false ? "" : line
1374
- ).join("\n");
1375
- }
1376
- var sdkDeclarationOwners = /* @__PURE__ */ new Map();
1377
- function sdkObjCDeclarationOwners(frameworks, fromSwift = false) {
1378
- const known = sdkDeclarationOwners.get(frameworks);
1379
- const projection = fromSwift ? "swift" : "objc";
1380
- if (known) return known[projection];
1381
- const owners = { objc: /* @__PURE__ */ new Map(), swift: /* @__PURE__ */ new Map() };
1382
- for (const framework of readdirSync3(frameworks))
1383
- if (framework.endsWith(".framework")) {
1384
- const owner = framework.slice(0, -".framework".length);
1385
- const headers = path8.join(frameworks, framework, "Headers");
1386
- if (existsSync(headers)) {
1387
- for (const file of readdirSync3(headers, { recursive: true, encoding: "utf8" }))
1388
- if (file.endsWith(".h")) {
1389
- const header = readFileSync4(path8.join(headers, file), "utf8");
1390
- const names = sdkObjCDeclarations(header);
1391
- for (const name of names) owners.objc.set(name, owner);
1392
- const visible = header.includes("__swift__") ? sdkObjCDeclarations(sdkHeaderVisibleToSwift(header)) : names;
1393
- for (const name of visible) owners.swift.set(name, owner);
1394
- }
1395
- }
1396
- }
1397
- sdkDeclarationOwners.set(frameworks, owners);
1398
- return owners[projection];
1399
- }
1400
- function swiftHeaderWithSuperclassImports(header, interfaceFor) {
1401
- const superclasses = new Set(
1402
- [...header.matchAll(/@interface\s+\w+\s*:\s*(\w+)/g)].map((match) => match[1])
1403
- );
1404
- return header.replace(/^@import (\w+);$/gm, (statement, name) => {
1405
- const dependency = interfaceFor(name);
1406
- if (dependency && !dependency.module)
1407
- return `#import ${JSON.stringify(dependency.file)}`;
1408
- if (!dependency || ![...swiftInterfaceDeclarations(dependency.header)].some(
1409
- (name2) => superclasses.has(name2)
1410
- ))
1411
- return statement;
1412
- return `${statement}
1413
- #import ${JSON.stringify(dependency.file)}`;
1414
- });
1415
- }
1416
- var swiftInterfaceDeclarations = (header) => /* @__PURE__ */ new Set([
1417
- ...[
1418
- ...header.matchAll(
1419
- /^[ \t]*(?:[A-Z_]\w*(?:\([^()\n]*\))?[ \t]+)*@protocol\s+(\w+)\b(?![^\n]*;\s*$)/gm
1420
- )
1421
- ].map((m) => m[1]),
1422
- ...[
1423
- ...header.matchAll(
1424
- /^[ \t]*(?:[A-Z_]\w*(?:\([^()\n]*\))?[ \t]+)*@interface\s+(\w+)\s*(?=[:<{]|$)/gm
1425
- )
1426
- ].map((m) => m[1])
1427
- ]);
1428
- function withoutSwiftDeclarations(text, declared, interfaceImport) {
1429
- const out = [];
1430
- let skipping;
1431
- let imported = false;
1432
- let regionStart = -1;
1433
- for (const line of text.split("\n")) {
1434
- if (skipping) {
1435
- if (skipping === "objc" ? /^@end\b/.test(line) : /^\s*};/.test(line))
1436
- skipping = void 0;
1437
- continue;
1438
- }
1439
- if (regionStart < 0 && /^NS_ASSUME_NONNULL_BEGIN\b/.test(line))
1440
- regionStart = out.length;
1441
- const name = /^\s*(?:[A-Z_]\w*(?:\([^()\n]*\))?\s+)*@(?:protocol|interface)\s+(\w+)\s*(?=[:<{]|$)/.exec(
1442
- line
1443
- )?.[1];
1444
- const external = /^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(.*\)[^;\n]*;\s*$/.exec(
1445
- line
1446
- )?.[1];
1447
- if (external && declared.has(external)) continue;
1448
- const enumeration = /^\s*typedef\s+(?:NS_ENUM|NS_OPTIONS|SWIFT_ENUM(?:_NAMED)?)\s*\(\s*\w+\s*,\s*(\w+)\b/.exec(
1449
- line
1450
- )?.[1];
1451
- const enumForward = objcEnumForward.exec(line)?.[1];
1452
- const declaration = name ?? enumeration ?? enumForward;
1453
- if (declaration && declared.has(declaration)) {
1454
- skipping = name ? "objc" : enumeration && !line.includes("};") ? "enum" : void 0;
1455
- while (/^(?:SWIFT_[A-Z_]+|(?:NS|CF)_SWIFT_NAME)(?:\(.*\))?\s*$/.test(out.at(-1) ?? ""))
1456
- out.pop();
1457
- if (!imported)
1458
- out.splice(regionStart < 0 ? out.length : regionStart, 0, interfaceImport);
1459
- imported = true;
1460
- continue;
1461
- }
1462
- out.push(line);
1463
- }
1464
- return out.join("\n");
1465
- }
1466
- function swiftModuleSdk(root) {
1467
- const pin = swiftDistributionAt(root) ?? swiftSourceSdk(root);
1468
- return {
1469
- wasmSdkId: pin.wasmSdkId,
1470
- wasmSdkUrl: pin.wasmSdkUrl,
1471
- wasmSdkChecksum: pin.wasmSdkChecksum
1472
- };
1473
- }
1474
- function swiftCompileSdkOptions(moduleRoot, toolchainBin) {
1475
- return swiftSharedSdkViewOptions(
1476
- moduleRoot,
1477
- swiftDistributionAt(moduleRoot) !== null,
1478
- toolchainBin,
1479
- swiftModuleSdk(moduleRoot).wasmSdkId
1480
- );
1481
- }
1482
- var guestEngineTrees = [
1483
- "../peach-engine/core-abi/closure",
1484
- "../peach-engine/native",
1485
- "../peach-engine/skia"
1486
- ];
1487
- var guestEngineBuildFiles = [
1488
- "../peach-engine/core-abi/style/fields.ts",
1489
- "../peach-engine/scripts/canvaskit-build-contract.ts",
1490
- "../peach-engine/scripts/canvaskit-build-utils.ts",
1491
- "../peach-engine/scripts/canvaskit-manifest.ts",
1492
- "../peach-engine/scripts/canvaskit-text-data.ts",
1493
- "../peachsim/src/swift-guest-image-ledger.ts",
1494
- "../peachsim/src/swift-wasm-archive.ts",
1495
- "../peachsim/src/swift-wasm-prune.ts",
1496
- "../../scripts/build/peach-guest-engine.ts"
1497
- ];
1498
- function swiftModuleInputFiles(root, surface = "module") {
1499
- if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST];
1500
- const files = surface === "engine" ? ["toolchain.json", "../../bun.lock"] : [
1501
- ...swiftSharedSdkInputFiles(root),
1502
- "../peachsim/src/admitted-mac-build.ts",
1503
- "../peachsim/src/swift-shared-sdk.ts",
1504
- "../peachsim/src/wasm-binary-sections.ts",
1505
- "../peachsim/src/swift-runtime-products.ts",
1506
- "../peachsim/src/swiftRuntimeProductContract.ts",
1507
- "../peachsim/src/swiftTargetContract.ts",
1508
- "../peachsim/src/swift-darwin-records.ts",
1509
- "../peachsim/src/swift-uniform-type-constants.ts",
1510
- "../../scripts/generate/swift-sdk-module/darwin-mach.json",
1511
- "../../scripts/generate/swift-sdk-module/darwin-socketvar.json",
1512
- "../../scripts/ops/swift-distribution-publish.ts",
1513
- "../../src/helpers/mapLimit.ts",
1514
- "Package.swift",
1515
- "scripts/contrast-app-Package.swift",
1516
- "scripts/build-distribution.ts",
1517
- "scripts/build-javascriptcore.ts",
1518
- "scripts/runtime-product.ts",
1519
- "scripts/runtime-product-scopes.ts",
1520
- "scripts/distribution-runtime-products.ts",
1521
- "scripts/build-helpers.ts",
1522
- "scripts/build-cache.ts",
1523
- "scripts/build-cache-launcher.ts",
1524
- "scripts/distribution-clang.ts",
1525
- "runtime/UniformTypeIdentifiersConstants.m",
1526
- "Sources/libxml2/include/module.modulemap",
1527
- "Sources/libxml2/COPYING",
1528
- "scripts/build-distribution-plugins.sh",
1529
- "scripts/build-distribution-plugins-docker.sh",
1530
- "scripts/build-preview-plugin.sh",
1531
- "toolchain.json"
1532
- ];
1533
- const walk = (dir, allFiles = false) => {
1534
- for (const entry of readdirSync3(path8.join(root, dir), {
1535
- withFileTypes: true
1536
- })) {
1537
- const relative = `${dir}/${entry.name}`;
1538
- if (entry.isDirectory()) walk(relative, allFiles);
1539
- else if (allFiles || /\.(swift|swiftinterface|swiftoverlay|c|cpp|h|inc|m|mm|modulemap|apinotes|json)$/.test(
1540
- entry.name
1541
- ))
1542
- files.push(relative);
1543
- }
1544
- };
1545
- if (surface !== "engine") {
1546
- walk("Sources");
1547
- walk("runtime/JavaScriptCore");
1548
- walk("cross-import-overlays");
1549
- walk("ios-simulator-stdlib");
1550
- }
1551
- if (surface === "framework") {
1552
- files.push("../peach-engine/native/core/input/control_tracking.h");
1553
- } else {
1554
- files.push(...guestEngineBuildFiles);
1555
- for (const tree of guestEngineTrees) walk(tree, true);
1556
- }
1557
- return files.sort();
1558
- }
1559
- function swiftMacroPlugins(moduleRoot) {
1560
- const distribution = swiftDistributionAt(moduleRoot);
1561
- if (distribution) {
1562
- const view = swiftDistributionCompileView(moduleRoot, distribution);
1563
- return {
1564
- libraries: distribution.plugins.filter((plugin) => path8.basename(plugin) !== "ExpoModulesMacros").map((plugin) => path8.join(view, plugin)),
1565
- executables: distribution.plugins.filter((plugin) => path8.basename(plugin) === "ExpoModulesMacros").map((plugin) => path8.join(view, plugin)),
1566
- stale: false
1567
- };
1568
- }
1569
- const release = JSON.parse(
1570
- readFileSync4(path8.join(moduleRoot, "toolchain.json"), "utf8")
1571
- ).release;
1572
- const key = createHash4("sha256").update(release).update(`${process.platform}-${process.arch}`).update(readFileSync4(path8.join(moduleRoot, "scripts/build-preview-plugin.sh")));
1573
- for (const source of [
1574
- "RnxPreviewMacros",
1575
- "FoundationMacros",
1576
- "TipKitMacros",
1577
- "SwiftMacroSupport"
1578
- ]) {
1579
- const sourceDir = path8.join(moduleRoot, "Sources", source);
1580
- for (const file of readdirSync3(sourceDir, { withFileTypes: true }).sort(
1581
- (a, b) => a.name.localeCompare(b.name)
1582
- )) {
1583
- if (file.isFile())
1584
- key.update(`${source}/${file.name}\0`).update(readFileSync4(path8.join(sourceDir, file.name)));
1585
- }
1586
- }
1587
- const dir = path8.join(swiftCacheDir(), "swift-distribution-plugins", key.digest("hex"));
1588
- const stamp = path8.join(dir, "compiler-release");
1589
- const ext = process.platform === "darwin" ? "dylib" : "so";
1590
- const libraries = ["RnxPreviewMacros", "FoundationMacros", "TipKitMacros"].map(
1591
- (name) => path8.join(dir, `lib${name}.${ext}`)
1592
- );
1593
- const executables = [path8.join(dir, "ExpoModulesMacros")];
1594
- return {
1595
- libraries,
1596
- executables,
1597
- stale: [...libraries, ...executables, stamp].some((file) => !existsSync(file)) || readFileSync4(stamp, "utf8").trim() !== release
1598
- };
1599
- }
1600
- var linkedModuleDigests = /* @__PURE__ */ new Map();
1601
- var moduleDigestScopes = new AsyncLocalStorage();
1602
- function withSwiftModuleDigestScope(fn) {
1603
- if (moduleDigestScopes.getStore()) return fn();
1604
- return moduleDigestScopes.run(/* @__PURE__ */ new Map(), fn);
1605
- }
1606
- function clearSwiftModuleDigestScope(root) {
1607
- const scope = moduleDigestScopes.getStore();
1608
- if (!scope) return;
1609
- if (root === void 0) scope.clear();
1610
- else
1611
- for (const surface of ["module", "framework", "engine"])
1612
- scope.delete(surface + "\0" + path8.resolve(root));
1613
- }
1614
- function clearLinkedModuleDigests(root) {
1615
- clearSwiftModuleDigestScope(root);
1616
- if (root === void 0) linkedModuleDigests.clear();
1617
- else
1618
- for (const surface of ["module", "framework", "engine"])
1619
- linkedModuleDigests.delete(surface + "\0" + path8.resolve(root));
1620
- }
1621
- function gitCleanModuleInputsKey(root, files) {
1622
- if (swiftDistributionAt(root)) return null;
1623
- const top = spawnSync3("git", ["-C", root, "rev-parse", "--show-toplevel"], {
1624
- encoding: "utf8",
1625
- stdio: ["ignore", "pipe", "ignore"]
1626
- });
1627
- if (top.status !== 0) return null;
1628
- const repoTop = top.stdout.trim();
1629
- if (!repoTop) return null;
1630
- const realTop = realpathSync(repoTop);
1631
- const realRoot = realpathSync(root);
1632
- const collapsedDirs = [
1633
- path8.join(realRoot, "Sources"),
1634
- path8.join(realRoot, "cross-import-overlays"),
1635
- path8.join(realRoot, "ios-simulator-stdlib"),
1636
- realpathSync(path8.resolve(realRoot, "../peachsim/sdk/ios"))
1637
- ];
1638
- const scoped = /* @__PURE__ */ new Set();
1639
- for (const dir of collapsedDirs) {
1640
- const rel = path8.relative(realTop, dir).split(path8.sep).join("/");
1641
- if (!rel || rel.startsWith("../")) return null;
1642
- scoped.add(rel);
1643
- }
1644
- for (const file of files) {
1645
- const full = path8.resolve(realRoot, file);
1646
- if (collapsedDirs.some((dir) => full.startsWith(dir + path8.sep))) continue;
1647
- const rel = path8.relative(realTop, full).split(path8.sep).join("/");
1648
- if (!rel || rel.startsWith("../")) return null;
1649
- scoped.add(rel);
1650
- }
1651
- const paths = [...scoped].sort();
1652
- const status = spawnSync3(
1653
- "git",
1654
- [
1655
- "-C",
1656
- realTop,
1657
- "status",
1658
- "--porcelain",
1659
- "--untracked-files=all",
1660
- "--ignored=matching",
1661
- "--",
1662
- ...paths
1663
- ],
1664
- {
1665
- encoding: "utf8",
1666
- stdio: ["ignore", "pipe", "ignore"],
1667
- maxBuffer: 16 * 1024 * 1024
1668
- }
1669
- );
1670
- if (status.status !== 0 || status.stdout.trim().length > 0) return null;
1671
- const oids = spawnSync3(
1672
- "git",
1673
- ["-C", realTop, "rev-parse", ...paths.map((entry) => `HEAD:${entry}`)],
1674
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
1675
- );
1676
- if (oids.status !== 0) return null;
1677
- const keyHash = createHash4("sha256");
1678
- keyHash.update("git-module-digest/v1\n");
1679
- keyHash.update(oids.stdout);
1680
- keyHash.update("\n");
1681
- for (const file of files) keyHash.update(file).update("\n");
1682
- return keyHash.digest("hex");
1683
- }
1684
- function swiftModuleEntry(root, surface = "module") {
1685
- const scope = moduleDigestScopes.getStore();
1686
- const key = surface + "\0" + path8.resolve(root);
1687
- const scoped = scope?.get(key);
1688
- if (scoped) return scoped;
1689
- const files = swiftModuleInputFiles(root, surface);
1690
- const stampHash = createHash4("sha256");
1691
- for (const file of files) {
1692
- const stat = statSync2(path8.join(root, file), { bigint: true });
1693
- stampHash.update(file);
1694
- stampHash.update(
1695
- `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}
1696
- `
1697
- );
1698
- }
1699
- const stamp = stampHash.digest("hex");
1700
- const cached = linkedModuleDigests.get(key);
1701
- if (cached?.stamp === stamp) {
1702
- scope?.set(key, cached);
1703
- return cached;
1704
- }
1705
- const digestDir = path8.join(swiftCacheDir(), "swift-module-digests");
1706
- const record = path8.join(
1707
- digestDir,
1708
- `${createHash4("sha256").update(key).digest("hex")}.json`
1709
- );
1710
- const writeRecord = (target, body) => {
1711
- mkdirSync2(path8.dirname(target), { recursive: true });
1712
- const partial = `${target}.${process.pid}.${randomUUID()}`;
1713
- writeFileSync2(partial, body);
1714
- renameSync(partial, target);
1715
- };
1716
- if (existsSync(record)) {
1717
- const saved = JSON.parse(readFileSync4(record, "utf8"));
1718
- if (saved && typeof saved === "object" && Reflect.get(saved, "stamp") === stamp && typeof Reflect.get(saved, "digest") === "string") {
1719
- const digest2 = Buffer.from(String(Reflect.get(saved, "digest")), "hex");
1720
- const entry2 = { stamp, digest: digest2 };
1721
- linkedModuleDigests.set(key, entry2);
1722
- scope?.set(key, entry2);
1723
- return entry2;
1724
- }
1725
- }
1726
- const gitKey = gitCleanModuleInputsKey(root, files);
1727
- const gitRecord = gitKey ? path8.join(digestDir, `git-${gitKey}.json`) : null;
1728
- if (gitRecord && existsSync(gitRecord)) {
1729
- const saved = JSON.parse(readFileSync4(gitRecord, "utf8"));
1730
- if (saved && typeof saved === "object" && typeof Reflect.get(saved, "digest") === "string") {
1731
- const hex2 = String(Reflect.get(saved, "digest"));
1732
- const digest2 = Buffer.from(hex2, "hex");
1733
- const entry2 = { stamp, digest: digest2 };
1734
- linkedModuleDigests.set(key, entry2);
1735
- scope?.set(key, entry2);
1736
- writeRecord(record, JSON.stringify({ stamp, digest: hex2 }));
1737
- return entry2;
1738
- }
1739
- }
1740
- const hash = createHash4("sha256");
1741
- for (const file of files) {
1742
- hash.update(createHash4("sha256").update(file).digest());
1743
- hash.update(
1744
- createHash4("sha256").update(readFileSync4(path8.join(root, file))).digest()
1745
- );
1746
- }
1747
- const digest = hash.digest();
1748
- const hex = digest.toString("hex");
1749
- const entry = { stamp, digest };
1750
- linkedModuleDigests.set(key, entry);
1751
- scope?.set(key, entry);
1752
- writeRecord(record, JSON.stringify({ stamp, digest: hex }));
1753
- if (gitRecord) writeRecord(gitRecord, JSON.stringify({ digest: hex }));
1754
- return entry;
1755
- }
1756
- function swiftModuleDigest(root) {
1757
- return swiftModuleEntry(root).digest;
1758
- }
1759
- function swiftGuestEngineInputDigest(root) {
1760
- return swiftModuleEntry(root, "engine").digest;
1761
- }
1762
- var compileSurfaces = /* @__PURE__ */ new WeakMap();
1763
- function swiftCompileSurfaceDigest(root) {
1764
- const distribution = swiftDistributionAt(root);
1765
- if (!distribution) return swiftModuleEntry(root, "framework").digest;
1766
- let digest = compileSurfaces.get(distribution);
1767
- if (!digest) {
1768
- digest = createHash4("sha256").update(
1769
- JSON.stringify([
1770
- distribution.release,
1771
- distribution.wasmSdkId,
1772
- distribution.wasmSdkChecksum,
1773
- distribution.modules,
1774
- distribution.plugins,
1775
- distribution.link,
1776
- Object.entries(distribution.files).filter(([file]) => !file.startsWith("lib/")).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)
1777
- ])
1778
- ).digest();
1779
- compileSurfaces.set(distribution, digest);
1780
- }
1781
- return digest;
1782
- }
1783
- var kleeneNot = (value) => value === void 0 ? void 0 : !value;
1784
- var kleeneAnd = (left, right) => left === false || right === false ? false : left === true && right === true ? true : void 0;
1785
- var kleeneOr = (left, right) => left === true || right === true ? true : left === false && right === false ? false : void 0;
1786
- var NON_IOS_MODULES = /* @__PURE__ */ new Set(["FoundationNetworking", "WASILibc"]);
1787
- function swiftCondition(text, available, defines) {
1788
- const tokens = text.match(/\w+\s*\([^()]*\)|&&|\|\||!|\(|\)|\w+/g) ?? [];
1789
- let index = 0;
1790
- const atom = () => {
1791
- const token = tokens[index++];
1792
- if (token === "!") return kleeneNot(atom());
1793
- if (token === "(") {
1794
- const value = either();
1795
- index++;
1796
- return value;
1797
- }
1798
- if (token === "true") return true;
1799
- if (token === "false") return false;
1800
- if (defines && /^[A-Za-z_]\w*$/.test(token ?? "")) return defines.has(token);
1801
- const call = /^(\w+)\s*\(\s*([^,()]*?)\s*(?:,[^()]*)?\)$/.exec(token ?? "");
1802
- if (!call) return void 0;
1803
- const [, name, argument] = call;
1804
- if (name === "os") return argument === "iOS";
1805
- if (name === "canImport")
1806
- return !NON_IOS_MODULES.has(argument) && available?.has(argument);
1807
- if (name === "targetEnvironment") return argument === "simulator";
1808
- if (name === "arch") return argument === "wasm64" || argument === "arm64";
1809
- return void 0;
1810
- };
1811
- const both = () => {
1812
- let value = atom();
1813
- while (tokens[index] === "&&") {
1814
- index++;
1815
- value = kleeneAnd(value, atom());
1816
- }
1817
- return value;
1818
- };
1819
- const either = () => {
1820
- let value = both();
1821
- while (tokens[index] === "||") {
1822
- index++;
1823
- value = kleeneOr(value, both());
1824
- }
1825
- return value;
1826
- };
1827
- return either();
1828
- }
1829
- function* swiftConditionalLines(contents2, available, defines) {
1830
- const frames = [];
1831
- for (const line of swiftCodeMask(contents2).split("\n")) {
1832
- const directive = /^\s*#(if|elseif|else|endif)\b(.*)$/.exec(line);
1833
- if (directive) {
1834
- const [, kind, rest] = directive;
1835
- const condition = (rest ?? "").replace(/\/\/.*$/, "").trim();
1836
- if (kind === "if") {
1837
- const active = swiftCondition(condition, available, defines);
1838
- frames.push({ active, taken: active });
1839
- } else if (kind === "endif") frames.pop();
1840
- else if (frames.length > 0) {
1841
- const frame = frames[frames.length - 1];
1842
- const holds = kind === "else" ? true : swiftCondition(condition, available, defines);
1843
- frame.active = frame.taken === true ? false : frame.taken === false ? holds : holds && void 0;
1844
- frame.taken = frame.taken === true || holds === true ? true : frame.taken === false ? holds : void 0;
1845
- }
1846
- yield { line, active: false };
1847
- continue;
1848
- }
1849
- yield {
1850
- line,
1851
- active: frames.some((frame) => frame.active === false) ? false : frames.every((frame) => frame.active === true) ? true : void 0
1852
- };
1853
- }
1854
- }
1855
- var importNamesCache = /* @__PURE__ */ new Map();
1856
- function swiftImportNames(contents2, available, defines) {
1857
- if (!contents2.includes("import")) return [];
1858
- const definesKey = available === void 0 ? defines ? [...defines].sort().join("\0") : "" : void 0;
1859
- if (definesKey !== void 0) {
1860
- const cached = importNamesCache.get(definesKey)?.get(contents2);
1861
- if (cached !== void 0) return cached;
1862
- }
1863
- const names = [];
1864
- for (const { line, active } of swiftConditionalLines(contents2, available, defines)) {
1865
- if (available ? active !== true : defines !== void 0 && active === false) continue;
1866
- const name = SWIFT_IMPORT.exec(line)?.[1];
1867
- if (name) names.push(name);
1868
- }
1869
- if (definesKey !== void 0) {
1870
- let bucket = importNamesCache.get(definesKey);
1871
- if (!bucket) {
1872
- bucket = /* @__PURE__ */ new Map();
1873
- importNamesCache.set(definesKey, bucket);
1874
- }
1875
- bucket.set(contents2, names);
1876
- }
1877
- return names;
1878
- }
1879
- function swiftPeachModules(moduleRoot) {
1880
- const distribution = swiftDistributionAt(moduleRoot);
1881
- return distribution ? distribution.modules : swiftManifestDeclarations(
1882
- readFileSync4(path8.join(moduleRoot, "Package.swift"), "utf8")
1883
- ).filter((target) => !target.executable && !target.path.startsWith("fixtures/")).map((target) => target.name);
1884
- }
1885
- var sdkPaths = /* @__PURE__ */ new Map();
1886
- function clearSwiftSdkPathsCache(sdkDir) {
1887
- for (const key of sdkPaths.keys()) if (key.includes(sdkDir)) sdkPaths.delete(key);
1888
- }
1889
- function swiftSdkPaths(moduleRoot, toolchainBin, options = swiftCompileSdkOptions(moduleRoot, toolchainBin), sdk = swiftModuleSdk(moduleRoot).wasmSdkId) {
1890
- const key = JSON.stringify([toolchainBin, sdk, options]);
1891
- const cached = sdkPaths.get(key);
1892
- if (cached) return cached;
1893
- const configuration = execFileSync3(
1894
- path8.join(toolchainBin, "swift"),
1895
- ["sdk", "configure", ...options, "--show-configuration", sdk, SWIFT_WASM_TRIPLE],
1896
- { encoding: "utf8", env: swiftEnvironment(), stdio: ["ignore", "pipe", "pipe"] }
1897
- );
1898
- const field = (name) => {
1899
- const value = new RegExp(`^${name}:\\s*(.+)$`, "m").exec(configuration)?.[1]?.trim();
1900
- if (!value) throw new Error(`swift sdk ${sdk} reports no ${name}`);
1901
- return value;
1902
- };
1903
- const sysroot = field("sdkRootPath");
1904
- const cFlags = [];
1905
- const frameworks = [];
1906
- const configuredToolsets = field("toolsetPaths");
1907
- if (configuredToolsets !== "not set") {
1908
- const toolsets = JSON.parse(configuredToolsets);
1909
- if (!Array.isArray(toolsets) || !toolsets.every((value) => typeof value === "string"))
1910
- throw new Error(`swift sdk ${sdk} reports invalid toolset paths`);
1911
- for (const toolset of toolsets) {
1912
- const config = JSON.parse(readFileSync4(toolset, "utf8"));
1913
- if (!config || typeof config !== "object" || !("swiftCompiler" in config)) continue;
1914
- const compiler = config.swiftCompiler;
1915
- if (!compiler || typeof compiler !== "object" || !("extraCLIOptions" in compiler))
1916
- continue;
1917
- const options2 = compiler.extraCLIOptions;
1918
- if (!Array.isArray(options2) || !options2.every((value) => typeof value === "string"))
1919
- throw new Error(
1920
- `swift sdk ${sdk} has invalid swift compiler options in ${toolset}`
1921
- );
1922
- for (let index = 0; index < options2.length; index++) {
1923
- if (options2[index] === "-Xcc" && typeof options2[index + 1] === "string") {
1924
- const flag = options2[index + 1];
1925
- if (flag !== "-fwasm-exceptions") cFlags.push(flag);
1926
- if (flag === "-iframeworkwithsysroot" && options2[index + 2] === "-Xcc" && typeof options2[index + 3] === "string") {
1927
- cFlags.push(options2[index + 3]);
1928
- frameworks.push(path8.join(sysroot, options2[index + 3]));
1929
- index += 3;
1930
- continue;
1931
- }
1932
- index += 1;
1933
- continue;
1934
- }
1935
- const option = options2[index];
1936
- if (option.startsWith("-iframework") || option.startsWith("-F"))
1937
- throw new Error(
1938
- `swift sdk ${sdk} has an unsupported framework search option ${option}`
1939
- );
1940
- }
1941
- }
1942
- }
1943
- const paths = {
1944
- sysroot,
1945
- darwin: path8.join(sysroot, "darwin"),
1946
- resources: field("swiftResourcesPath"),
1947
- frameworks,
1948
- cFlags
1949
- };
1950
- sdkPaths.set(key, paths);
1951
- return paths;
1952
- }
1953
- var FOUNDATION_IMPLICIT_MODULES = [
1954
- "PeachObjC",
1955
- "Dispatch",
1956
- "FoundationNetworking",
1957
- "PeachFoundationCombine",
1958
- "Darwin"
1959
- ];
1960
- var ASSOCIATION_POLICY_IMPORT = "enum PeachObjC.objc_AssociationPolicy";
1961
- var FOUNDATION_COMPANION_IMPORTS = [
1962
- ...FOUNDATION_IMPLICIT_MODULES,
1963
- ASSOCIATION_POLICY_IMPORT
1964
- ];
1965
- var FRAMEWORK_COMPANIONS = /* @__PURE__ */ new Map([
1966
- ["Dispatch", ["PeachFoundationCombine"]],
1967
- ["ObjectiveC", ["PeachObjC", ASSOCIATION_POLICY_IMPORT]],
1968
- ["SystemConfiguration", ["Dispatch", "Darwin"]]
1969
- ]);
1970
- var FRAMEWORK_COMPANION_IMPORT = /^[ \t]*((?:(?:@\w+(?:\([^)]*\))?|public|package|internal|fileprivate|private)[ \t]+)*)import[ \t]+(Foundation|UIKit|SwiftUI|Photos|CoreData|SystemConfiguration|Dispatch|ObjectiveC)[ \t]*;?[ \t]*$/;
1971
- function withFrameworkCompanionImports(source) {
1972
- const original = source.split("\n");
1973
- const imports = [];
1974
- let hasCompanions = false;
1975
- for (const [index, line] of swiftCodeMask(source).split("\n").entries()) {
1976
- const conditional = /#(?:(?:if|elseif)\b.*|(?:else|endif)\b)/.exec(line);
1977
- if (conditional) {
1978
- const start = conditional.index;
1979
- imports.push(original[index].slice(start, start + conditional[0].length));
1980
- continue;
1981
- }
1982
- const matched = FRAMEWORK_COMPANION_IMPORT.exec(line.trimEnd());
1983
- if (!matched) continue;
1984
- const [, attributes = "", framework = ""] = matched;
1985
- const modifiers = attributes.match(
1986
- /@(?:preconcurrency|_exported|_implementationOnly)\b|\b(?:public|package|internal|fileprivate|private)\b/g
1987
- ) ?? [];
1988
- const preconcurrency = modifiers.includes("@preconcurrency");
1989
- const modules = FRAMEWORK_COMPANIONS.get(framework) ?? (preconcurrency ? ["CoreFoundation", "ObjectiveC", ...FOUNDATION_COMPANION_IMPORTS] : FOUNDATION_COMPANION_IMPORTS);
1990
- const prefix = modifiers.length ? modifiers.join(" ") + " " : "";
1991
- imports.push(...modules.map((module) => `${prefix}import ${module}`));
1992
- if (framework === "Foundation" && modifiers.includes("public"))
1993
- imports.push(
1994
- "@_exported public import protocol Combine.ObservableObject",
1995
- "@_exported public import struct Combine.Published"
1996
- );
1997
- if (framework === "CoreData")
1998
- imports.push(
1999
- `${prefix}import protocol Combine.ObservableObject`,
2000
- `${prefix}import struct Combine.Published`
2001
- );
2002
- hasCompanions = true;
2003
- }
2004
- if (!hasCompanions) return source;
2005
- return `${source}${source.endsWith("\n") ? "" : "\n"}#if canImport(PeachObjC)
2006
- ${imports.join("\n")}
2007
- #endif
2008
- `;
2009
- }
2010
- var codeMasks = /* @__PURE__ */ new Map();
2011
- var codeMaskChars = 0;
2012
- var CODE_MASK_CACHE_CHARS = 256 * 1024 * 1024;
2013
- function swiftCodeMask(source) {
2014
- const cached = codeMasks.get(source);
2015
- if (cached !== void 0) return cached;
2016
- const masked = maskSwiftCode(source);
2017
- if (codeMaskChars + source.length > CODE_MASK_CACHE_CHARS) {
2018
- codeMasks.clear();
2019
- importNamesCache.clear();
2020
- codeMaskChars = 0;
2021
- }
2022
- codeMasks.set(source, masked);
2023
- codeMaskChars += source.length;
2024
- return masked;
2025
- }
2026
- var FOUNDATION_NETWORKING_TYPES = /* @__PURE__ */ new Set([
2027
- "NSURLConnection",
2028
- "NSURLConnectionDataDelegate",
2029
- "NSURLConnectionDelegate",
2030
- "NSURLConnectionDownloadDelegate"
2031
- ]);
2032
- var FOUNDATION_OVERLAY_TYPES = /* @__PURE__ */ new Set([
2033
- "AsyncCharacterSequence",
2034
- "AsyncLineSequence",
2035
- "AsyncUnicodeScalarSequence",
2036
- "DateComponentsFormatter",
2037
- "ErrorUserInfoKey",
2038
- "ListFormatter",
2039
- "LocalizedStringResource",
2040
- "MachError",
2041
- "MeasurementFormatUnitUsage",
2042
- "MessagePort",
2043
- "NSAssertionHandler",
2044
- "NSAttributedStringFormattingContextKey",
2045
- "NSBundleResourceRequest",
2046
- "NSConditionLock",
2047
- "NSExtensionItem",
2048
- "NSFastEnumerationIterator",
2049
- "NSFileManagerResumeSyncBehavior",
2050
- "NSFileManagerSupportedSyncControls",
2051
- "NSFileManagerUploadLocalVersionConflictPolicy",
2052
- "NSFileProviderService",
2053
- "NSFileProviderServiceName",
2054
- "NSFileSecurity",
2055
- "NSGrammaticalCase",
2056
- "NSGrammaticalDefiniteness",
2057
- "NSGrammaticalDetermination",
2058
- "NSGrammaticalGender",
2059
- "NSGrammaticalNumber",
2060
- "NSGrammaticalPartOfSpeech",
2061
- "NSGrammaticalPerson",
2062
- "NSGrammaticalPronounType",
2063
- "NSHashEnumerator",
2064
- "NSHashTableCallBacks",
2065
- "NSKeyValueOperator",
2066
- "NSKeyValueSetMutationKind",
2067
- "NSKeyValueSharedObservers",
2068
- "NSMapEnumerator",
2069
- "NSMapTableKeyCallBacks",
2070
- "NSMapTableValueCallBacks",
2071
- "NSMetadataItem",
2072
- "NSMetadataQuery",
2073
- "NSMetadataQueryAttributeValueTuple",
2074
- "NSMetadataQueryDelegate",
2075
- "NSMetadataQueryResultGroup",
2076
- "NSPredicateValidating",
2077
- "NSPurgeableData",
2078
- "NSSecureUnarchiveFromDataTransformer",
2079
- "NSUbiquitousKeyValueStore",
2080
- "NSXPCCoder",
2081
- "NSXPCConnection",
2082
- "NSXPCInterface",
2083
- "NSXPCListener",
2084
- "NSXPCListenerDelegate",
2085
- "NSXPCListenerEndpoint",
2086
- "PredicateCodableConfiguration",
2087
- "PresentationIntent",
2088
- "SocketPort",
2089
- "StringEncodingDetectionOptionsKey",
2090
- "TermOfAddress",
2091
- "URLFileProtection",
2092
- "URLResource",
2093
- "URLUbiquitousItemDownloadingStatus",
2094
- "URLUbiquitousSharedItemPermissions",
2095
- "URLUbiquitousSharedItemRole",
2096
- "ValueTransformer"
2097
- ]);
2098
- var FOUNDATION_OVERLAY_GLOBALS = /* @__PURE__ */ new Set([
2099
- "CFBridgingRetain",
2100
- "NSAllHashTableObjects",
2101
- "NSAllMapTableKeys",
2102
- "NSAllMapTableValues",
2103
- "NSAllocateMemoryPages",
2104
- "NSBuddhistCalendar",
2105
- "NSBundleResourceRequestLoadingPriorityUrgent",
2106
- "NSChineseCalendar",
2107
- "NSCompareHashTables",
2108
- "NSCompareMapTables",
2109
- "NSCopyHashTableWithZone",
2110
- "NSCopyMapTableWithZone",
2111
- "NSCopyMemoryPages",
2112
- "NSCountHashTable",
2113
- "NSCountMapTable",
2114
- "NSCreateHashTable",
2115
- "NSCreateHashTableWithZone",
2116
- "NSCreateMapTable",
2117
- "NSCreateMapTableWithZone",
2118
- "NSDeallocateMemoryPages",
2119
- "NSEndHashTableEnumeration",
2120
- "NSEndMapTableEnumeration",
2121
- "NSEnumerateHashTable",
2122
- "NSEnumerateMapTable",
2123
- "NSExtensionItemAttachmentsKey",
2124
- "NSExtensionItemAttributedContentTextKey",
2125
- "NSExtensionItemAttributedTitleKey",
2126
- "NSExtensionItemsAndErrorsKey",
2127
- "NSFreeHashTable",
2128
- "NSFreeMapTable",
2129
- "NSGetUncaughtExceptionHandler",
2130
- "NSGregorianCalendar",
2131
- "NSHashGet",
2132
- "NSHashInsert",
2133
- "NSHashInsertIfAbsent",
2134
- "NSHashInsertKnownAbsent",
2135
- "NSHashRemove",
2136
- "NSHebrewCalendar",
2137
- "NSISO8601Calendar",
2138
- "NSIndianCalendar",
2139
- "NSIslamicCalendar",
2140
- "NSIslamicCivilCalendar",
2141
- "NSJapaneseCalendar",
2142
- "NSLoadedClasses",
2143
- "NSLocalizedFailureErrorKey",
2144
- "NSLogPageSize",
2145
- "NSMACHOperatingSystem",
2146
- "NSMapGet",
2147
- "NSMapInsert",
2148
- "NSMapInsertIfAbsent",
2149
- "NSMapInsertKnownAbsent",
2150
- "NSMapMember",
2151
- "NSMapRemove",
2152
- "NSMultipleUnderlyingErrorsKey",
2153
- "NSNextHashEnumeratorItem",
2154
- "NSNextMapEnumeratorPair",
2155
- "NSNonOwnedPointerHashCallBacks",
2156
- "NSNonOwnedPointerMapKeyCallBacks",
2157
- "NSNonOwnedPointerMapValueCallBacks",
2158
- "NSNonOwnedPointerOrNullMapKeyCallBacks",
2159
- "NSNonRetainedObjectHashCallBacks",
2160
- "NSNonRetainedObjectMapKeyCallBacks",
2161
- "NSNonRetainedObjectMapValueCallBacks",
2162
- "NSObjectHashCallBacks",
2163
- "NSObjectMapKeyCallBacks",
2164
- "NSObjectMapValueCallBacks",
2165
- "NSOpenStepRootDirectory",
2166
- "NSOwnedObjectIdentityHashCallBacks",
2167
- "NSOwnedPointerHashCallBacks",
2168
- "NSOwnedPointerMapKeyCallBacks",
2169
- "NSOwnedPointerMapValueCallBacks",
2170
- "NSPersianCalendar",
2171
- "NSPointerToStructHashCallBacks",
2172
- "NSPropertyListErrorMaximum",
2173
- "NSPropertyListErrorMinimum",
2174
- "NSRepublicOfChinaCalendar",
2175
- "NSResetHashTable",
2176
- "NSResetMapTable",
2177
- "NSSolarisOperatingSystem",
2178
- "NSStringFromHashTable",
2179
- "NSStringFromMapTable",
2180
- "NSSunOSOperatingSystem",
2181
- "NSTextCheckingAllCustomTypes",
2182
- "NSTextCheckingAllSystemTypes",
2183
- "NSTextCheckingAllTypes",
2184
- "NSURLCredentialStorageRemoveSynchronizableCredentials",
2185
- "NSURLSessionUploadTaskResumeData",
2186
- "NSUbiquitousFileErrorMaximum",
2187
- "NSUbiquitousFileErrorMinimum",
2188
- "NSUbiquitousKeyValueStoreAccountChange",
2189
- "NSUbiquitousKeyValueStoreChangeReasonKey",
2190
- "NSUbiquitousKeyValueStoreChangedKeysKey",
2191
- "NSUbiquitousKeyValueStoreInitialSyncChange",
2192
- "NSUbiquitousKeyValueStoreQuotaViolationChange",
2193
- "NSUbiquitousKeyValueStoreServerChange",
2194
- "NSUndoCloseGroupingRunLoopOrdering",
2195
- "NSUndoManagerGroupIsDiscardableKey",
2196
- "NSUserActivityErrorMaximum",
2197
- "NSUserActivityErrorMinimum",
2198
- "NSValidationErrorMaximum",
2199
- "NSValidationErrorMinimum",
2200
- "NSWindows95OperatingSystem",
2201
- "NSWindowsNTOperatingSystem",
2202
- "NSWrapCalendarComponents",
2203
- "NSXPCConnectionCodeSigningRequirementFailure",
2204
- "NSXPCConnectionErrorMaximum",
2205
- "NSXPCConnectionErrorMinimum",
2206
- "kCFStringEncodingASCII"
2207
- ]);
2208
- function foundationOwnerOf(name) {
2209
- if (name === "NSKeyValueObservedChange" || name === "NSKeyValueObservation")
2210
- return "PeachObjC";
2211
- if (name === "DispatchData") return "Dispatch";
2212
- if (FOUNDATION_NETWORKING_TYPES.has(name)) return "FoundationNetworking";
2213
- if (FOUNDATION_OVERLAY_TYPES.has(name) || FOUNDATION_OVERLAY_GLOBALS.has(name))
2214
- return "PeachFoundation";
2215
- return void 0;
2216
- }
2217
- var emptyMacroEnvironment = {
2218
- defines: /* @__PURE__ */ new Map(),
2219
- predefines: /* @__PURE__ */ new Map(),
2220
- targetDefined: /* @__PURE__ */ new Set()
2221
- };
2222
- function cMacroDefined(name, env) {
2223
- if (env.defines.has(name) || env.predefines.has(name)) return true;
2224
- if (env.targetDefined.has(name)) return void 0;
2225
- return false;
2226
- }
2227
- function cMacroIntOrTrue(value) {
2228
- if (value === void 0) return true;
2229
- if (/^0[xX][0-9a-fA-F]+[uUlL]*$/.test(value) || /^\d+[uUlL]*$/.test(value))
2230
- return Number.parseInt(value) !== 0;
2231
- return void 0;
2232
- }
2233
- function cMacroBareValue(name, env) {
2234
- if (env.defines.has(name)) return cMacroIntOrTrue(env.defines.get(name));
2235
- if (env.predefines.has(name)) return cMacroIntOrTrue(env.predefines.get(name));
2236
- if (env.targetDefined.has(name)) return void 0;
2237
- return false;
2238
- }
2239
- function cMacroNegated(name, env) {
2240
- return kleeneNot(cMacroDefined(name, env));
2241
- }
2242
- function cConditionValue(expression, env) {
2243
- let i = 0;
2244
- const skipSpaces = () => {
2245
- while (i < expression.length && /\s/.test(expression[i])) i++;
2246
- };
2247
- const parseOr = () => {
2248
- let value2 = parseAnd();
2249
- for (; ; ) {
2250
- skipSpaces();
2251
- if (!expression.startsWith("||", i)) return value2;
2252
- i += 2;
2253
- value2 = kleeneOr(value2, parseAnd());
2254
- }
2255
- };
2256
- const parseAnd = () => {
2257
- let value2 = parseUnary();
2258
- for (; ; ) {
2259
- skipSpaces();
2260
- if (!expression.startsWith("&&", i)) return value2;
2261
- i += 2;
2262
- value2 = kleeneAnd(value2, parseUnary());
2263
- }
2264
- };
2265
- const parseUnary = () => {
2266
- skipSpaces();
2267
- if (expression[i] === "!") {
2268
- i++;
2269
- return kleeneNot(parseUnary());
2270
- }
2271
- if (expression[i] === "(") {
2272
- i++;
2273
- const value2 = parseOr();
2274
- skipSpaces();
2275
- return expression[i] === ")" ? (i++, value2) : void 0;
2276
- }
2277
- const defined = /^defined\b/.exec(expression.slice(i));
2278
- if (defined) {
2279
- i += defined[0].length;
2280
- skipSpaces();
2281
- const parenthesized = expression[i] === "(";
2282
- if (parenthesized) {
2283
- i++;
2284
- skipSpaces();
2285
- }
2286
- const name2 = /^\w+/.exec(expression.slice(i))?.[0];
2287
- if (!name2) return void 0;
2288
- i += name2.length;
2289
- skipSpaces();
2290
- if (parenthesized) {
2291
- if (expression[i] !== ")") return void 0;
2292
- i++;
2293
- }
2294
- return cMacroDefined(name2, env);
2295
- }
2296
- const literal = /^(0[xX][0-9a-fA-F]+|\d+)[uUlL]*/.exec(expression.slice(i));
2297
- if (literal) {
2298
- i += literal[0].length;
2299
- return Number(literal[1]) !== 0;
2300
- }
2301
- const name = /^\w+/.exec(expression.slice(i))?.[0];
2302
- if (!name) return void 0;
2303
- i += name.length;
2304
- return cMacroBareValue(name, env);
2305
- };
2306
- const value = parseOr();
2307
- skipSpaces();
2308
- return i === expression.length ? value : void 0;
2309
- }
2310
- function cActiveCode(code, env) {
2311
- const kept = [];
2312
- const stack = [];
2313
- let active = true;
2314
- for (const line of code.replace(/\\\r?\n/g, "").split("\n")) {
2315
- const directive = /^\s*#\s*(if|ifdef|ifndef|elif|elifdef|elifndef|else|endif)\b(.*)$/.exec(line);
2316
- if (!directive) {
2317
- if (active) kept.push(line);
2318
- continue;
2319
- }
2320
- const keyword = directive[1];
2321
- const rest = directive[2].trim();
2322
- if (keyword === "if" || keyword === "ifdef" || keyword === "ifndef") {
2323
- const name = /^\w+$/.exec(rest)?.[0];
2324
- const value = keyword === "if" ? cConditionValue(rest, env) : name === void 0 ? void 0 : keyword === "ifdef" ? cMacroDefined(name, env) : cMacroNegated(name, env);
2325
- stack.push({ parent: active, taken: value === true });
2326
- active = active && value !== false;
2327
- } else if (keyword === "endif") {
2328
- active = stack.pop()?.parent ?? true;
2329
- } else if (stack.length === 0) {
2330
- continue;
2331
- } else {
2332
- const frame = stack[stack.length - 1];
2333
- if (keyword === "else") {
2334
- active = frame.parent && !frame.taken;
2335
- frame.taken = true;
2336
- } else {
2337
- const name = /^\w+$/.exec(rest)?.[0];
2338
- const value = keyword === "elif" ? cConditionValue(rest, env) : name === void 0 ? void 0 : keyword === "elifdef" ? cMacroDefined(name, env) : cMacroNegated(name, env);
2339
- const branch = !frame.taken && value !== false;
2340
- if (branch && value === true) frame.taken = true;
2341
- active = frame.parent && branch;
2342
- }
2343
- }
2344
- }
2345
- return kept.join("\n");
2346
- }
2347
- function stripCCode(source) {
2348
- let code = "";
2349
- let i = 0;
2350
- while (i < source.length) {
2351
- if (source.startsWith("//", i)) {
2352
- const end = source.indexOf("\n", i);
2353
- i = end === -1 ? source.length : end;
2354
- } else if (source.startsWith("/*", i)) {
2355
- const end = source.indexOf("*/", i + 2);
2356
- i = end === -1 ? source.length : end + 2;
2357
- } else if (source[i] === '"' || source[i] === "'") {
2358
- const quote = source[i];
2359
- i++;
2360
- while (i < source.length && source[i] !== quote) i += source[i] === "\\" ? 2 : 1;
2361
- i++;
2362
- } else {
2363
- code += source[i];
2364
- i++;
2365
- }
2366
- }
2367
- return code;
2368
- }
2369
- var wasmMacroEnvironment = {
2370
- ...emptyMacroEnvironment,
2371
- defines: /* @__PURE__ */ new Map([
2372
- ["__wasm__", "1"],
2373
- ["__wasm64__", "1"],
2374
- ["__wasi__", "1"]
2375
- ])
2376
- };
2377
- function swiftCTakesReturnAddress(source) {
2378
- if (!source.includes("__builtin_return_address")) return false;
2379
- return /\b__builtin_return_address\s*\(/.test(
2380
- cActiveCode(stripCCode(source), wasmMacroEnvironment)
2381
- );
2382
- }
2383
- function swiftCDefinedNames(sources) {
2384
- const names = /* @__PURE__ */ new Set();
2385
- for (const source of sources)
2386
- for (const line of stripCCode(source).split("\n")) {
2387
- const name = /^\s*#\s*define\s+([A-Za-z_]\w*)/.exec(line)?.[1];
2388
- if (name) names.add(name);
2389
- }
2390
- return names;
2391
- }
2392
- function swiftModuleRelease(root) {
2393
- const pin = swiftDistributionAt(root) ?? JSON.parse(readFileSync4(path8.join(root, "toolchain.json"), "utf8"));
2394
- return pin.release;
2395
- }
2396
- function swiftModuleCompiler(root) {
2397
- const release = swiftModuleRelease(root);
2398
- return {
2399
- release,
2400
- toolchainBin: swiftCompiler(release)
2401
- };
2402
- }
2403
- function swiftModuleToolchain(root) {
2404
- const { release } = swiftModuleCompiler(root);
2405
- return { release, toolchainBin: swiftToolchain(release, swiftModuleSdk(root)) };
2406
- }
2407
-
2408
- // src/swift-objc-runtime.ts
2409
- var swiftObjCRuntime = "-fobjc-runtime=gnustep-2.2";
2410
- var swiftObjCRuntimeFlags = [
2411
- swiftObjCRuntime,
2412
- "-fblocks",
2413
- "-fconstant-string-class=__NSCFConstantString"
2414
- ];
2415
-
2416
- // src/sha256.ts
2417
- import { createHash as createHash5 } from "node:crypto";
2418
- function sha256Hex(input) {
2419
- if (typeof Bun !== "undefined") {
2420
- return new Bun.CryptoHasher("sha256").update(input).digest("hex");
2421
- }
2422
- return createHash5("sha256").update(input).digest("hex");
2423
- }
2424
-
2425
- // ../contrast-runtime-delivery/src/index.ts
2426
- import { spawn } from "node:child_process";
2427
- import crypto from "node:crypto";
2428
- import fs5 from "node:fs";
2429
- import os2 from "node:os";
2430
- import path10 from "node:path";
2431
- import { pipeline } from "node:stream/promises";
2432
- import zlib from "node:zlib";
2433
-
2434
- // ../contrast-runtime-delivery/src/product.ts
2435
- import fs4 from "node:fs";
2436
- import path9 from "node:path";
2437
-
2438
- // ../contrast-runtime-delivery/src/index.ts
2439
- async function installVerifiedTarball(tarball) {
2440
- const { destDir, installedMarker, signal } = tarball;
2441
- const presentAtStart = fs5.existsSync(path10.join(destDir, installedMarker));
2442
- await withRuntimeInstallLock(
2443
- destDir,
2444
- async () => {
2445
- if (!presentAtStart && fs5.existsSync(path10.join(destDir, installedMarker))) {
2446
- await tarball.verify?.(destDir);
2447
- return;
2448
- }
2449
- await installVerifiedTarballLocked(tarball, presentAtStart);
2450
- },
2451
- signal
2452
- );
2453
- }
2454
- async function withRuntimeInstallLock(destDir, install, signal) {
2455
- fs5.mkdirSync(path10.dirname(destDir), { recursive: true });
2456
- const lock = `${destDir}.lock`;
2457
- for (; ; ) {
2458
- signal?.throwIfAborted();
2459
- try {
2460
- fs5.writeFileSync(lock, String(process.pid), { flag: "wx" });
2461
- break;
2462
- } catch (err) {
2463
- if (!isErrnoCode(err, "EEXIST")) throw err;
2464
- if (lockOwnerGone(lock)) fs5.rmSync(lock, { force: true });
2465
- else await new Promise((resolve) => setTimeout(resolve, 250));
2466
- }
2467
- }
2468
- try {
2469
- return await install();
2470
- } finally {
2471
- fs5.rmSync(lock, { force: true });
2472
- }
2473
- }
2474
- function lockOwnerGone(lock) {
2475
- try {
2476
- process.kill(Number(fs5.readFileSync(lock, "utf8")), 0);
2477
- return false;
2478
- } catch (err) {
2479
- return !isErrnoCode(err, "EPERM", "ENOENT");
2480
- }
2481
- }
2482
- async function installVerifiedTarballLocked(tarball, presentAtStart) {
2483
- const { url, headers, digest, destDir, installedMarker, label, localPath, signal } = tarball;
2484
- signal?.throwIfAborted();
2485
- const downloadDir = fs5.mkdtempSync(path10.join(os2.tmpdir(), "runtime-delivery-download-"));
2486
- const archivePath = localPath ?? path10.join(downloadDir, "archive");
2487
- const tmpDir = fs5.mkdtempSync(
2488
- path10.join(path10.dirname(destDir), `.installing-${path10.basename(destDir)}-`)
2489
- );
2490
- try {
2491
- for (let attempt = 1; ; attempt++) {
2492
- if (!localPath) await downloadToFile(url, archivePath, signal, headers);
2493
- const actual = await digestFile(
2494
- archivePath,
2495
- digest.algorithm,
2496
- digest.encoding,
2497
- signal
2498
- );
2499
- if (actual === digest.value) break;
2500
- if (localPath || attempt >= 2) {
2501
- throw new Error(
2502
- `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
2503
- );
2504
- }
2505
- }
2506
- const { pathname } = new URL(url);
2507
- if (pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir, signal);
2508
- else
2509
- await extractTarball(
2510
- archivePath,
2511
- pathname.endsWith(".tar.zst"),
2512
- tmpDir,
2513
- tarball.stripComponents ?? 0,
2514
- signal
2515
- );
2516
- signal?.throwIfAborted();
2517
- if (!fs5.existsSync(path10.join(tmpDir, installedMarker))) {
2518
- throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
2519
- }
2520
- await tarball.verify?.(tmpDir);
2521
- signal?.throwIfAborted();
2522
- try {
2523
- fs5.renameSync(tmpDir, destDir);
2524
- } catch (err) {
2525
- if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
2526
- if (!presentAtStart && fs5.existsSync(path10.join(destDir, installedMarker))) {
2527
- await tarball.verify?.(destDir);
2528
- return;
2529
- }
2530
- const aside = `${tmpDir}-replaced`;
2531
- try {
2532
- fs5.renameSync(destDir, aside);
2533
- } catch (moveErr) {
2534
- if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
2535
- }
2536
- try {
2537
- fs5.renameSync(tmpDir, destDir);
2538
- } catch (landErr) {
2539
- if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !fs5.existsSync(path10.join(destDir, installedMarker))) {
2540
- throw landErr;
2541
- }
2542
- await tarball.verify?.(destDir);
2543
- } finally {
2544
- fs5.rmSync(aside, { recursive: true, force: true });
2545
- }
2546
- }
2547
- } finally {
2548
- fs5.rmSync(tmpDir, { recursive: true, force: true });
2549
- fs5.rmSync(downloadDir, { recursive: true, force: true });
2550
- }
2551
- }
2552
- function isErrnoCode(err, ...codes) {
2553
- return err instanceof Error && "code" in err && codes.includes(String(err.code));
2554
- }
2555
- var DownloadHttpError = class extends Error {
2556
- constructor(status, statusText, url) {
2557
- super(`download failed: ${status} ${statusText} (${url})`);
2558
- __publicField(this, "retryable");
2559
- this.retryable = status < 400 || status >= 500 || status === 408 || status === 429;
2560
- }
2561
- };
2562
- async function waitRetryDelay(ms, signal) {
2563
- signal?.throwIfAborted();
2564
- await new Promise((resolve, reject) => {
2565
- const onAbort = () => {
2566
- clearTimeout(timer);
2567
- const reason = signal?.reason;
2568
- reject(
2569
- reason instanceof Error ? reason : new Error("Download canceled", { cause: reason })
2570
- );
2571
- };
2572
- const timer = setTimeout(() => {
2573
- signal?.removeEventListener("abort", onAbort);
2574
- resolve();
2575
- }, ms);
2576
- signal?.addEventListener("abort", onAbort, { once: true });
2577
- });
2578
- }
2579
- async function downloadToFile(url, destPath, signal, headers) {
2580
- fs5.mkdirSync(path10.dirname(destPath), { recursive: true });
2581
- const tmp = `${destPath}.partial`;
2582
- for (let attempt = 1; attempt <= 4; attempt++) {
2583
- signal?.throwIfAborted();
2584
- let reader;
2585
- let handle;
2586
- let completed = false;
2587
- try {
2588
- const res = await fetch(url, { signal, headers });
2589
- if (!res.ok || !res.body) {
2590
- throw new DownloadHttpError(res.status, res.statusText, url);
2591
- }
2592
- reader = res.body.getReader();
2593
- handle = await fs5.promises.open(tmp, "w");
2594
- let written = 0;
2595
- for (; ; ) {
2596
- signal?.throwIfAborted();
2597
- const { done, value } = await reader.read();
2598
- if (done) break;
2599
- let offset = 0;
2600
- while (offset < value.byteLength) {
2601
- const { bytesWritten } = await handle.write(
2602
- value,
2603
- offset,
2604
- value.byteLength - offset
2605
- );
2606
- offset += bytesWritten;
2607
- }
2608
- written += value.byteLength;
2609
- }
2610
- await handle.close();
2611
- handle = void 0;
2612
- if (!res.headers.get("content-encoding")) {
2613
- const header = res.headers.get("content-length");
2614
- const expected = header ? Number(header) : Number.NaN;
2615
- if (Number.isFinite(expected) && expected > 0 && written !== expected) {
2616
- throw new Error(`incomplete download (${written}/${expected} bytes): ${url}`);
2617
- }
2618
- }
2619
- signal?.throwIfAborted();
2620
- fs5.renameSync(tmp, destPath);
2621
- completed = true;
2622
- return;
2623
- } catch (err) {
2624
- if (handle) await handle.close().catch(() => {
2625
- });
2626
- if (reader && !completed) await reader.cancel().catch(() => {
2627
- });
2628
- try {
2629
- fs5.unlinkSync(tmp);
2630
- } catch {
2631
- }
2632
- const nonRetryable = err instanceof DownloadHttpError && !err.retryable;
2633
- if (signal?.aborted || nonRetryable || attempt === 4) throw err;
2634
- await waitRetryDelay(250 * attempt, signal);
2635
- }
2636
- }
2637
- }
2638
- async function digestFile(filePath, algorithm, encoding, signal) {
2639
- const hash = crypto.createHash(algorithm);
2640
- await pipeline(fs5.createReadStream(filePath), hash, { signal });
2641
- return hash.digest(encoding);
2642
- }
2643
- function extractZip(zipPath, destDir, signal) {
2644
- return runExtractor("ditto", ["-x", "-k", zipPath, destDir], signal);
2645
- }
2646
- async function extractTarball(tarPath, zstd, destDir, stripComponents, signal) {
2647
- const args = [zstd ? "-xf" : "-xzf", "-"];
2648
- if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
2649
- if (zstd) {
2650
- const decoder = zlib.createZstdDecompress({
2651
- params: { [zlib.constants.ZSTD_d_windowLogMax]: 30 }
2652
- });
2653
- await runExtractor("tar", ["--ignore-zeros", ...args], signal, {
2654
- cwd: destDir,
2655
- stdin: (stdin) => pipeline(fs5.createReadStream(tarPath), decoder, stdin, { signal })
2656
- });
2657
- return;
2658
- }
2659
- const archive = fs5.openSync(tarPath, "r");
2660
- try {
2661
- await runExtractor("tar", args, signal, { cwd: destDir, stdin: archive });
2662
- } finally {
2663
- fs5.closeSync(archive);
2664
- }
2665
- }
2666
- async function runExtractor(command, args, signal, input) {
2667
- signal?.throwIfAborted();
2668
- const stdin = input?.stdin;
2669
- const stdio = [
2670
- typeof stdin === "function" ? "pipe" : stdin ?? "ignore",
2671
- "inherit",
2672
- "inherit"
2673
- ];
2674
- const child = spawn(command, args, {
2675
- cwd: input?.cwd,
2676
- stdio,
2677
- detached: process.platform !== "win32"
2678
- });
2679
- const fed = typeof stdin === "function" && child.stdin ? stdin(child.stdin) : void 0;
2680
- void fed?.catch(() => {
2681
- });
2682
- let stopping;
2683
- const abort = () => {
2684
- stopping ?? (stopping = terminateProcessGroup(child, "SIGKILL", 0));
2685
- void stopping.catch(() => {
2686
- });
2687
- };
2688
- try {
2689
- await new Promise((resolve, reject) => {
2690
- let failure;
2691
- child.on("error", (error) => {
2692
- failure = error;
2693
- });
2694
- child.on("close", (code) => {
2695
- if (signal?.aborted) {
2696
- const reason = signal.reason;
2697
- reject(
2698
- reason instanceof Error ? reason : new Error("Extraction canceled", { cause: reason })
2699
- );
2700
- } else if (failure) reject(failure);
2701
- else if (code === 0) resolve();
2702
- else reject(new Error(`${command} exited with code ${code}`));
2703
- });
2704
- signal?.addEventListener("abort", abort, { once: true });
2705
- if (signal?.aborted) abort();
2706
- });
2707
- await fed;
2708
- } finally {
2709
- signal?.removeEventListener("abort", abort);
2710
- await stopping;
2711
- }
2712
- }
2713
-
2714
- export {
2715
- writeBuildFile,
2716
- clearCaseInsensitiveHeaderOverlayCache,
2717
- caseInsensitiveHeaderOverlay,
2718
- swiftObjCPlatformFlags,
2719
- NATIVE_GRAPH_SDK_VERSION,
2720
- WASI_EMULATION_FLAGS,
2721
- objcSdkIntakeFlags,
2722
- objcAppIntakeFlags,
2723
- iosDeploymentMinimum,
2724
- sha256Hex,
2725
- installVerifiedTarball,
2726
- SWIFT_DISTRIBUTION_MANIFEST,
2727
- SWIFT_DISTRIBUTION_OBJC_SELECTORS,
2728
- parseSwiftDistributionLock,
2729
- swiftCodeScan,
2730
- mapSwiftConditionalLines,
2731
- encodeWasmNumber,
2732
- encodeWasmSigned,
2733
- encodeWasmName,
2734
- readULEB,
2735
- readSLEB,
2736
- skipLEB,
2737
- readWasmSection,
2738
- wasmSections,
2739
- SWIFT_DISTRIBUTION_MIRROR_RECORD,
2740
- swiftSharedSdkRoot,
2741
- swiftSharedSdkFlags,
2742
- weakenFoundationOverridesInArchive,
2743
- swiftSharedSdkViewOptions,
2744
- swiftSdkReplacedModules,
2745
- swiftBuildJobs,
2746
- swiftDistributionAt,
2747
- swiftDistributionCompileView,
2748
- REACH_STAGED_FRAMEWORKS,
2749
- swiftModuleInterface,
2750
- clangInterfaceHeader,
2751
- objcEnumerations,
2752
- withoutImportedSdkEnumForwards,
2753
- nativelyDeclaredFunctions,
2754
- sdkObjCDeclarationOwners,
2755
- swiftHeaderWithSuperclassImports,
2756
- swiftInterfaceDeclarations,
2757
- withoutSwiftDeclarations,
2758
- swiftModuleSdk,
2759
- swiftCompileSdkOptions,
2760
- swiftModuleInputFiles,
2761
- swiftMacroPlugins,
2762
- withSwiftModuleDigestScope,
2763
- clearSwiftModuleDigestScope,
2764
- clearLinkedModuleDigests,
2765
- swiftModuleDigest,
2766
- swiftGuestEngineInputDigest,
2767
- swiftCompileSurfaceDigest,
2768
- NON_IOS_MODULES,
2769
- swiftConditionalLines,
2770
- swiftImportNames,
2771
- swiftPeachModules,
2772
- clearSwiftSdkPathsCache,
2773
- swiftSdkPaths,
2774
- FOUNDATION_IMPLICIT_MODULES,
2775
- withFrameworkCompanionImports,
2776
- swiftCodeMask,
2777
- foundationOwnerOf,
2778
- emptyMacroEnvironment,
2779
- cActiveCode,
2780
- stripCCode,
2781
- wasmMacroEnvironment,
2782
- swiftCTakesReturnAddress,
2783
- swiftCDefinedNames,
2784
- swiftModuleRelease,
2785
- swiftModuleToolchain,
2786
- swiftObjCRuntimeFlags
2787
- };