peachsim 0.1.2439 → 0.1.2441

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 (143) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +8180 -8397
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +2 -2
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-FGE4PYDJ.mjs → acorn-FRQNHKFC.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-HIDNO3RP.mjs → chunk-4BZ3Z3IQ.mjs} +18 -18
  28. package/dist-lib/esm-chunks/{chunk-5T4XBUJP.mjs → chunk-4HEUXQGM.mjs} +4 -4
  29. package/dist-lib/esm-chunks/{chunk-7HANEMO4.mjs → chunk-4ZRMJ5YO.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-4ZFNH7TU.mjs → chunk-6A6JEVIF.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-KVTIDLBK.mjs → chunk-ABMB3G7I.mjs} +3 -3
  32. package/dist-lib/esm-chunks/{chunk-C3WBGYP6.mjs → chunk-BAYRN7ZL.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-KSQ5KM5Y.mjs → chunk-DJMWTW2B.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-DADGQELM.mjs → chunk-IRMC5BCX.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-YB27R6JG.mjs → chunk-NPLEBOWJ.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-HSADZOVN.mjs → chunk-O4EOBXAP.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-JCKI3VZ6.mjs → chunk-ORYS5CC4.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-2NPABFPN.mjs → chunk-PMGJ7FLI.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-6VY6HTJC.mjs → chunk-QUBR7LHU.mjs} +2036 -1918
  40. package/dist-lib/esm-chunks/{chunk-IWJUYJQO.mjs → chunk-QYYJESMK.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-CVGDRROP.mjs → chunk-VAQJQDWI.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-DEGYKHN7.mjs → chunk-VCAJFWZD.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-2EUHEBIJ.mjs → chunk-XO5GX4PI.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-MIQSRBVU.mjs → chunk-ZCMAKWHN.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{metro-layout-parser-MVUAXRUJ.mjs → metro-layout-parser-AUAVE5VL.mjs} +3 -3
  46. package/dist-lib/expo-swift-bundle.cjs +5580 -5768
  47. package/dist-lib/expo-swift-metadata.cjs +1 -1
  48. package/dist-lib/expo-swift-metadata.mjs +7 -7
  49. package/dist-lib/home-paths.cjs +1 -1
  50. package/dist-lib/host/bridge-host.cjs +6332 -6500
  51. package/dist-lib/host/fetch-proxy-handler.cjs +13891 -13919
  52. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  53. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  54. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  55. package/dist-lib/host/websocket-proxy.cjs +1 -1
  56. package/dist-lib/index.cjs +1 -1
  57. package/dist-lib/jump-to-source-babel.cjs +1 -1
  58. package/dist-lib/jump-to-source-native.cjs +1 -1
  59. package/dist-lib/kotlin-host.cjs +1 -1
  60. package/dist-lib/menu.cjs +1 -1
  61. package/dist-lib/menu.mjs +3 -3
  62. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  63. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  64. package/dist-lib/metro-production-bundle.cjs +1 -1
  65. package/dist-lib/metro-production-bundle.mjs +4 -4
  66. package/dist-lib/native-app-identity-project.cjs +784 -536
  67. package/dist-lib/native-app-identity-project.mjs +543 -408
  68. package/dist-lib/native-app-identity.cjs +1 -1
  69. package/dist-lib/native-app-identity.mjs +6 -6
  70. package/dist-lib/native-firebase-metadata.cjs +1 -1
  71. package/dist-lib/native-firebase-metadata.mjs +3 -3
  72. package/dist-lib/pdfium-raster.cjs +1 -1
  73. package/dist-lib/pdfium-raster.mjs +2 -2
  74. package/dist-lib/plist.cjs +1 -1
  75. package/dist-lib/plist.mjs +3 -3
  76. package/dist-lib/profiles.cjs +1 -1
  77. package/dist-lib/public-brand.cjs +1 -1
  78. package/dist-lib/public-origins-lib-esm.json +81 -79
  79. package/dist-lib/public-origins-lib.json +185 -195
  80. package/dist-lib/react-native-host-modules.cjs +1 -1
  81. package/dist-lib/react-native-host-modules.mjs +2 -2
  82. package/dist-lib/reap-browser.cjs +1 -1
  83. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  84. package/dist-lib/sdk.cjs +1 -1
  85. package/dist-lib/sdk.mjs +7 -7
  86. package/dist-lib/skills.cjs +7579 -7758
  87. package/dist-lib/swift-compile.cjs +1978 -1922
  88. package/dist-lib/swift-compile.mjs +8 -8
  89. package/dist-lib/swift-package.cjs +1 -1
  90. package/dist-lib/swift-package.mjs +3 -3
  91. package/dist-lib/swift-submit.cjs +1 -1
  92. package/dist-lib/swift-submit.mjs +5 -5
  93. package/dist-lib/swift-toolchain.cjs +3 -1
  94. package/dist-lib/swift.cjs +1 -1
  95. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  96. package/dist-lib/vendor/acorn.cjs +1 -1
  97. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  98. package/dist-lib/vendor/ignore.cjs +1 -1
  99. package/dist-lib/vendor/magic-string.cjs +1 -1
  100. package/dist-lib/vendor/plist.cjs +17 -17
  101. package/dist-lib/vendor/smol-toml.cjs +1 -1
  102. package/dist-lib/vendor/stream-json.cjs +1 -1
  103. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  104. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  105. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  106. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  107. package/dist-lib/vendor/sucrase.cjs +1 -1
  108. package/dist-lib/vendor/terser.cjs +1 -1
  109. package/dist-lib/vendor/valibot.cjs +1 -1
  110. package/dist-lib/vendor/zod.cjs +1 -1
  111. package/dist-lib/worklet-executable.cjs +1 -1
  112. package/dist-lib/worklet-executable.mjs +3 -3
  113. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-cookies.d.ts +4 -0
  114. package/dist-types/packages/peach-engine/src/remote-stream/cloud-display.d.ts +2 -2
  115. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +9 -0
  116. package/package.json +1 -1
  117. package/runtime-companion.json +1 -1
  118. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSDateComponentsFormatter.h +1 -1
  119. package/src/expo-discovery-cache.ts +9 -45
  120. package/src/expo-native-compiler-digest.ts +8 -0
  121. package/src/expo-native-prebuilt.ts +1 -10
  122. package/src/expo-native-workspace.ts +5 -120
  123. package/src/expo-pod-prebuilt.ts +1 -1
  124. package/src/expo-swift-host.ts +48 -35
  125. package/src/host/bridge-host.ts +2 -0
  126. package/src/installed-native-libraries.ts +10 -20
  127. package/src/native-slices.ts +1 -1
  128. package/src/pod-graph-specifications.ts +11 -0
  129. package/src/pods-install.ts +10 -7
  130. package/src/podspec-cocoapods.ts +8 -3
  131. package/src/podspec-sources.ts +19 -15
  132. package/src/swift-clang-type-ownership.ts +118 -0
  133. package/src/swift-compile.ts +20 -12
  134. package/src/swift-guest-image-ledger.ts +48 -0
  135. package/src/swift-guest-link.ts +11 -1
  136. package/src/swift-host.ts +7 -8
  137. package/src/swift-package-manifest.ts +13 -8
  138. package/src/swift-packages.ts +0 -5
  139. package/src/swift-toolchain.ts +1 -1
  140. package/src/xcode-project.ts +64 -46
  141. package/src/portable-expo-contract.ts +0 -108
  142. package/src/portable-expo-workspace.ts +0 -100
  143. package/src/prepared-xcode-phases.ts +0 -194
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2439 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2441 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  import {
3
3
  OBJC_RESOURCE_ACCESSOR_BODY,
4
4
  OBJC_RESOURCE_ACCESSOR_HEADER,
@@ -20,7 +20,7 @@ import {
20
20
  swiftPackagePartition,
21
21
  swiftTargetModuleName,
22
22
  withoutGlogModuleMap
23
- } from "./chunk-2EUHEBIJ.mjs";
23
+ } from "./chunk-XO5GX4PI.mjs";
24
24
  import {
25
25
  SWIFT_NATIVE_INPUT_ROOT,
26
26
  SWIFT_NATIVE_SDK_INCLUDE,
@@ -33,13 +33,13 @@ import {
33
33
  isSwiftResourcePath,
34
34
  isSwiftSourceLinkGraph,
35
35
  swiftProjectFilesProblems
36
- } from "./chunk-C3WBGYP6.mjs";
36
+ } from "./chunk-BAYRN7ZL.mjs";
37
37
  import {
38
38
  isRecord
39
- } from "./chunk-JCKI3VZ6.mjs";
39
+ } from "./chunk-ORYS5CC4.mjs";
40
40
  import {
41
41
  __publicField
42
- } from "./chunk-IWJUYJQO.mjs";
42
+ } from "./chunk-QYYJESMK.mjs";
43
43
 
44
44
  // src/swift-compile.ts
45
45
  import {
@@ -3324,6 +3324,9 @@ function swiftHostCompilerPin(release) {
3324
3324
  if (!compiler) throw new Error(`unqualified host compiler ${release}`);
3325
3325
  return compiler;
3326
3326
  }
3327
+ function registerSwiftHostCompiler(release, pin) {
3328
+ compilerArchives[release] = pin;
3329
+ }
3327
3330
  function swiftHostCompilerArchive(release, host2 = `${process.platform}-${process.arch}`) {
3328
3331
  const compiler = swiftHostCompilerPin(release);
3329
3332
  const archive = compiler.hosts[host2];
@@ -4796,6 +4799,40 @@ function parseSwiftDistributionManifest(value) {
4796
4799
  plugins: value.plugins
4797
4800
  };
4798
4801
  }
4802
+ function parseSwiftDistributionLock(value) {
4803
+ if (!isRecord(value) || typeof value.id !== "string" || !/^[a-f0-9]{16}$/.test(value.id) || 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)) {
4804
+ throw new Error("invalid Swift distribution lock");
4805
+ }
4806
+ const hosts = value.hosts;
4807
+ const entry = (host2) => {
4808
+ const item = hosts[host2];
4809
+ if (!isRecord(item) || typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256) || typeof item.size !== "number") {
4810
+ throw new Error(`invalid Swift distribution lock entry for ${host2}`);
4811
+ }
4812
+ return { sha256: item.sha256, size: item.size };
4813
+ };
4814
+ return {
4815
+ id: value.id,
4816
+ release: value.release,
4817
+ wasmSdkId: value.wasmSdkId,
4818
+ wasmSdkUrl: value.wasmSdkUrl,
4819
+ wasmSdkChecksum: value.wasmSdkChecksum,
4820
+ source: value.source,
4821
+ targets: value.targets,
4822
+ systemEnvironment: Object.fromEntries(
4823
+ Object.entries(value.systemEnvironment).map(([key, values]) => {
4824
+ if (!isStrings(values))
4825
+ throw new Error(`invalid Swift system environment values for ${key}`);
4826
+ return [key, values];
4827
+ })
4828
+ ),
4829
+ hosts: {
4830
+ "darwin-arm64": entry("darwin-arm64"),
4831
+ "linux-x64": entry("linux-x64"),
4832
+ "linux-arm64": entry("linux-arm64")
4833
+ }
4834
+ };
4835
+ }
4799
4836
 
4800
4837
  // src/swift-foundation.ts
4801
4838
  var foundationCategoryObjects = [
@@ -7085,8 +7122,8 @@ function aliasGuestLinkIdentities(identities, archives) {
7085
7122
 
7086
7123
  // src/swift-guest-link.ts
7087
7124
  import { execFileSync as execFileSync7 } from "node:child_process";
7088
- import fs6 from "node:fs";
7089
- import path16 from "node:path";
7125
+ import fs9 from "node:fs";
7126
+ import path19 from "node:path";
7090
7127
  import { StringDecoder } from "node:string_decoder";
7091
7128
 
7092
7129
  // src/swift-guest-image-ledger.ts
@@ -7688,6 +7725,48 @@ function createGuestImageLedger(input) {
7688
7725
  llvmIR: ir.join("\n") + "\n"
7689
7726
  };
7690
7727
  }
7728
+ function nameGuestImageAliases(wasm, symbols) {
7729
+ const alias = /^__peach_image_\d+_symbol_(\d+)$/;
7730
+ const parts = [wasm.subarray(0, 8)];
7731
+ let position = 8;
7732
+ while (position < wasm.length) {
7733
+ const [size, start] = readNumber(wasm, position + 1);
7734
+ const end = start + size;
7735
+ const custom = wasm[position] === 0 ? readString(wasm, start) : void 0;
7736
+ if (custom?.[0] !== "name") {
7737
+ parts.push(wasm.subarray(position, end));
7738
+ position = end;
7739
+ continue;
7740
+ }
7741
+ const subsections = [encodedString("name")];
7742
+ let at = custom[1];
7743
+ while (at < end) {
7744
+ const [subSize, subStart] = readNumber(wasm, at + 1);
7745
+ const subEnd = subStart + subSize;
7746
+ if (wasm[at] !== 1) {
7747
+ subsections.push(wasm.subarray(at, subEnd));
7748
+ at = subEnd;
7749
+ continue;
7750
+ }
7751
+ let [count, cursor] = readNumber(wasm, subStart);
7752
+ const entries = [encodeNumber(count)];
7753
+ for (; count > 0; count--) {
7754
+ const [index, next] = readNumber(wasm, cursor);
7755
+ const [name2, after] = readString(wasm, next);
7756
+ cursor = after;
7757
+ const symbol = symbols[Number(alias.exec(name2)?.[1] ?? -1)];
7758
+ entries.push(encodeNumber(index), encodedString(symbol ?? name2));
7759
+ }
7760
+ const content = Buffer.concat(entries);
7761
+ subsections.push(Buffer.from([1]), encodeNumber(content.length), content);
7762
+ at = subEnd;
7763
+ }
7764
+ const section = Buffer.concat(subsections);
7765
+ parts.push(Buffer.from([0]), encodeNumber(section.length), section);
7766
+ position = end;
7767
+ }
7768
+ return Buffer.concat(parts);
7769
+ }
7691
7770
 
7692
7771
  // src/swift-guest-link-plan.ts
7693
7772
  function selectedGuestInputImage(artifact, member) {
@@ -9205,2045 +9284,2068 @@ function guestAliasedSdkArchiveArtifacts(options) {
9205
9284
  return result;
9206
9285
  }
9207
9286
 
9208
- // src/swift-guest-link.ts
9209
- function remapGuestLinkPlan(plan, rewritten) {
9210
- return {
9211
- ...plan,
9212
- artifacts: plan.artifacts.map((artifact) => ({
9213
- ...artifact,
9214
- path: rewritten.get(artifact.path) ?? artifact.path
9215
- }))
9216
- };
9217
- }
9218
- function guestLinkInputFiles(args) {
9219
- const dirs = [];
9220
- for (let i = 0; i < args.length; i++) {
9221
- const arg = args[i];
9222
- if (arg === "-L" || arg === "--library-path") dirs.push(args[++i]);
9223
- else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9224
- else if (arg.startsWith("--library-path=")) dirs.push(arg.slice(15));
9225
- }
9226
- const inputs = /* @__PURE__ */ new Set();
9227
- for (let i = 0; i < args.length; i++) {
9228
- const arg = args[i];
9229
- if (arg === "-L" || arg === "--library-path" || arg === "-o" || arg === "--output") {
9230
- i++;
9231
- continue;
9287
+ // src/wasm-optimize.ts
9288
+ import { execFile as execFile2 } from "node:child_process";
9289
+ import { existsSync as existsSync2, readFileSync as readFileSync11, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
9290
+ import { dirname, join as join2 } from "node:path";
9291
+ import { promisify as promisify2 } from "node:util";
9292
+
9293
+ // ../contrast-runtime-delivery/src/index.ts
9294
+ import { spawn as spawn3 } from "node:child_process";
9295
+ import crypto from "node:crypto";
9296
+ import fs7 from "node:fs";
9297
+ import os2 from "node:os";
9298
+ import path17 from "node:path";
9299
+ import { pipeline as pipeline2 } from "node:stream/promises";
9300
+ import zlib2 from "node:zlib";
9301
+
9302
+ // ../contrast-runtime-delivery/src/product.ts
9303
+ import fs6 from "node:fs";
9304
+ import path16 from "node:path";
9305
+
9306
+ // ../contrast-runtime-delivery/src/index.ts
9307
+ async function installVerifiedTarball(tarball) {
9308
+ const { destDir, installedMarker, signal } = tarball;
9309
+ fs7.mkdirSync(path17.dirname(destDir), { recursive: true });
9310
+ const presentAtStart = fs7.existsSync(path17.join(destDir, installedMarker));
9311
+ const lock = `${destDir}.lock`;
9312
+ for (; ; ) {
9313
+ signal?.throwIfAborted();
9314
+ try {
9315
+ fs7.writeFileSync(lock, String(process.pid), { flag: "wx" });
9316
+ break;
9317
+ } catch (err) {
9318
+ if (!isErrnoCode(err, "EEXIST")) throw err;
9319
+ if (lockOwnerGone(lock)) fs7.rmSync(lock, { force: true });
9320
+ else await new Promise((resolve) => setTimeout(resolve, 250));
9232
9321
  }
9233
- if (arg.startsWith("@")) throw new Error(`nested linker response file ${arg}`);
9234
- let file;
9235
- if (arg === "-l" || arg === "--library" || arg.startsWith("--library=") || arg.startsWith("-l") && arg.length > 2) {
9236
- const name2 = arg === "-l" || arg === "--library" ? args[++i] : arg.startsWith("--library=") ? arg.slice(10) : arg.slice(2);
9237
- const archive = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
9238
- file = dirs.map((dir) => path16.join(dir, archive)).find((item) => fs6.existsSync(item));
9239
- if (!file) throw new Error(`unresolved guest link library ${name2}`);
9240
- } else if (!arg.startsWith("-") && fs6.existsSync(arg) && fs6.statSync(arg).isFile()) {
9241
- const fd = fs6.openSync(arg, "r");
9242
- const magic = Buffer.alloc(8);
9243
- try {
9244
- fs6.readSync(fd, magic, 0, magic.length, 0);
9245
- } finally {
9246
- fs6.closeSync(fd);
9247
- }
9248
- if (magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) || magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) || magic.toString("ascii") === "!<arch>\n" || magic.toString("ascii") === "!<thin>\n")
9249
- file = arg;
9322
+ }
9323
+ try {
9324
+ if (!presentAtStart && fs7.existsSync(path17.join(destDir, installedMarker))) {
9325
+ await tarball.verify?.(destDir);
9326
+ return;
9250
9327
  }
9251
- if (file) inputs.add(path16.resolve(file));
9328
+ await installVerifiedTarballLocked(tarball, presentAtStart);
9329
+ } finally {
9330
+ fs7.rmSync(lock, { force: true });
9252
9331
  }
9253
- return [...inputs];
9254
9332
  }
9255
- function unownedGuestLinkInputs(plan, args) {
9256
- const owned = new Set(plan.artifacts.map((artifact) => path16.resolve(artifact.path)));
9257
- return guestLinkInputFiles(args).filter((file) => !owned.has(file));
9258
- }
9259
- function occurrences(plan, args) {
9260
- const dirs = [];
9261
- for (let i = 0; i < args.length; i++) {
9262
- const arg = args[i];
9263
- if (arg === "-L") dirs.push(args[++i]);
9264
- else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9333
+ function lockOwnerGone(lock) {
9334
+ try {
9335
+ process.kill(Number(fs7.readFileSync(lock, "utf8")), 0);
9336
+ return false;
9337
+ } catch (err) {
9338
+ return !isErrnoCode(err, "EPERM", "ENOENT");
9265
9339
  }
9266
- const owned = new Map(
9267
- plan.artifacts.map((artifact) => [path16.resolve(artifact.path), artifact])
9340
+ }
9341
+ async function installVerifiedTarballLocked(tarball, presentAtStart) {
9342
+ const { url, digest, destDir, installedMarker, label, signal } = tarball;
9343
+ signal?.throwIfAborted();
9344
+ const downloadDir = fs7.mkdtempSync(path17.join(os2.tmpdir(), "runtime-delivery-download-"));
9345
+ const archivePath = path17.join(downloadDir, "archive");
9346
+ const tmpDir = fs7.mkdtempSync(
9347
+ path17.join(path17.dirname(destDir), `.installing-${path17.basename(destDir)}-`)
9268
9348
  );
9269
- if (owned.size !== plan.artifacts.length)
9270
- throw new Error("duplicate guest link artifact");
9271
- const found = [];
9272
- const seen = /* @__PURE__ */ new Map();
9273
- let lazy = false;
9274
- let whole = false;
9275
- for (const token of args) {
9276
- if (token === "--start-lib") {
9277
- lazy = true;
9278
- continue;
9279
- }
9280
- if (token === "--end-lib") {
9281
- lazy = false;
9282
- continue;
9283
- }
9284
- if (token === "--whole-archive") {
9285
- whole = true;
9286
- continue;
9287
- }
9288
- if (token === "--no-whole-archive") {
9289
- whole = false;
9290
- continue;
9349
+ try {
9350
+ for (let attempt = 1; ; attempt++) {
9351
+ await downloadToFile(url, archivePath, signal);
9352
+ const actual = await digestFile(
9353
+ archivePath,
9354
+ digest.algorithm,
9355
+ digest.encoding,
9356
+ signal
9357
+ );
9358
+ if (actual === digest.value) break;
9359
+ if (attempt >= 2) {
9360
+ throw new Error(
9361
+ `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
9362
+ );
9363
+ }
9291
9364
  }
9292
- let filename = token;
9293
- if (token.startsWith("-l") && token.length > 2) {
9294
- const library = token.slice(2);
9295
- filename = dirs.map(
9296
- (dir) => path16.join(
9297
- dir,
9298
- library.startsWith(":") ? library.slice(1) : `lib${library}.a`
9299
- )
9300
- ).find((file) => fs6.existsSync(file)) ?? token;
9365
+ const { pathname } = new URL(url);
9366
+ if (pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir, signal);
9367
+ else
9368
+ await extractTarball(
9369
+ archivePath,
9370
+ pathname.endsWith(".tar.zst"),
9371
+ tmpDir,
9372
+ tarball.stripComponents ?? 0,
9373
+ signal
9374
+ );
9375
+ signal?.throwIfAborted();
9376
+ if (!fs7.existsSync(path17.join(tmpDir, installedMarker))) {
9377
+ throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
9301
9378
  }
9302
- const artifact = owned.get(path16.resolve(filename));
9303
- if (artifact) {
9304
- const prior = seen.get(artifact.path);
9305
- if (prior) {
9306
- if (prior.lazy !== lazy || prior.whole !== whole)
9307
- throw new Error(
9308
- `guest link input has conflicting occurrence modes: ${artifact.path}`
9309
- );
9310
- continue;
9379
+ await tarball.verify?.(tmpDir);
9380
+ signal?.throwIfAborted();
9381
+ try {
9382
+ fs7.renameSync(tmpDir, destDir);
9383
+ } catch (err) {
9384
+ if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
9385
+ if (!presentAtStart && fs7.existsSync(path17.join(destDir, installedMarker))) {
9386
+ await tarball.verify?.(destDir);
9387
+ return;
9388
+ }
9389
+ const aside = `${tmpDir}-replaced`;
9390
+ try {
9391
+ fs7.renameSync(destDir, aside);
9392
+ } catch (moveErr) {
9393
+ if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
9394
+ }
9395
+ try {
9396
+ fs7.renameSync(tmpDir, destDir);
9397
+ } catch (landErr) {
9398
+ if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !fs7.existsSync(path17.join(destDir, installedMarker))) {
9399
+ throw landErr;
9400
+ }
9401
+ await tarball.verify?.(destDir);
9402
+ } finally {
9403
+ fs7.rmSync(aside, { recursive: true, force: true });
9311
9404
  }
9312
- const occurrence = { artifact, token, lazy, whole };
9313
- seen.set(artifact.path, occurrence);
9314
- found.push(occurrence);
9315
9405
  }
9406
+ } finally {
9407
+ fs7.rmSync(tmpDir, { recursive: true, force: true });
9408
+ fs7.rmSync(downloadDir, { recursive: true, force: true });
9316
9409
  }
9317
- if (found.length !== plan.artifacts.length)
9318
- throw new Error("guest plan does not match linker inputs");
9319
- return found;
9320
9410
  }
9321
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
9322
- const rows = whyExtract.trimEnd().split("\n");
9323
- if (rows.shift() !== "reference extracted symbol")
9324
- throw new Error("invalid wasm-ld extraction report");
9325
- const extracted = new Set(
9326
- rows.map((row) => {
9327
- const fields = row.split(" ");
9328
- if (fields.length !== 3) throw new Error("invalid wasm-ld extraction row");
9329
- return fields[1];
9330
- })
9331
- );
9332
- const traced = new Set(linkTrace.split("\n").filter(Boolean));
9333
- for (const file of extracted)
9334
- if (!traced.has(file))
9335
- throw new Error(`extracted guest input is absent from link trace ${file}`);
9336
- const result = [];
9337
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
9338
- if (artifact.kind === "object") {
9339
- if (!lazy && !traced.has(artifact.path))
9340
- throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
9341
- if (traced.has(artifact.path))
9342
- result.push({ artifact: artifact.path, member: null });
9343
- continue;
9344
- }
9345
- const prefix = `${artifact.path}(`;
9346
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
9347
- const members = readArMembers(fs6.readFileSync(artifact.path));
9348
- for (const member of members) {
9349
- if (whole || names.includes(member.name))
9350
- result.push({ artifact: artifact.path, member: member.name });
9351
- }
9352
- for (const name2 of names)
9353
- if (members.filter((member) => member.name === name2).length !== 1)
9354
- throw new Error(
9355
- `ambiguous or unsupported archive member ${artifact.path}(${name2})`
9356
- );
9357
- }
9358
- return result;
9411
+ function isErrnoCode(err, ...codes) {
9412
+ return err instanceof Error && "code" in err && codes.includes(String(err.code));
9359
9413
  }
9360
- function outputPath(args) {
9361
- let output = "";
9362
- for (let i = 0; i < args.length; i++) {
9363
- const arg = args[i];
9364
- if (arg === "-o" || arg === "--output") output = args[++i];
9365
- else if (arg.startsWith("--output=")) output = arg.slice("--output=".length);
9366
- }
9367
- if (!output) throw new Error("guest link has no output path");
9368
- return output;
9369
- }
9370
- function withOutput(args, output, discovery) {
9371
- const result = [];
9372
- for (let i = 0; i < args.length; i++) {
9373
- const arg = args[i];
9374
- if (arg === "-o" || arg === "--output") {
9375
- i++;
9376
- continue;
9377
- }
9378
- if (arg.startsWith("--output=")) continue;
9379
- if (discovery && (arg.startsWith("--why-extract=") || arg.startsWith("--Map=")))
9380
- continue;
9381
- result.push(arg);
9414
+ var DownloadHttpError = class extends Error {
9415
+ constructor(status, statusText, url) {
9416
+ super(`download failed: ${status} ${statusText} (${url})`);
9417
+ __publicField(this, "retryable");
9418
+ this.retryable = status < 400 || status >= 500 || status === 408 || status === 429;
9382
9419
  }
9383
- result.push("-o", output);
9384
- return result;
9420
+ };
9421
+ async function waitRetryDelay(ms, signal) {
9422
+ signal?.throwIfAborted();
9423
+ await new Promise((resolve, reject) => {
9424
+ const onAbort = () => {
9425
+ clearTimeout(timer);
9426
+ const reason = signal?.reason;
9427
+ reject(
9428
+ reason instanceof Error ? reason : new Error("Download canceled", { cause: reason })
9429
+ );
9430
+ };
9431
+ const timer = setTimeout(() => {
9432
+ signal?.removeEventListener("abort", onAbort);
9433
+ resolve();
9434
+ }, ms);
9435
+ signal?.addEventListener("abort", onAbort, { once: true });
9436
+ });
9385
9437
  }
9386
- function linkGuestImages(options) {
9387
- const { args, directory, wasmLd, clang, llvmAr } = options;
9388
- let plan = options.plan;
9389
- if (!plan.images.some((image) => image.id === options.ledgerDataImage))
9390
- throw new Error(`unknown ledger data image ${options.ledgerDataImage}`);
9391
- fs6.mkdirSync(directory, { recursive: true });
9392
- const discovery = path16.join(directory, "discovery.wasm");
9393
- const whyPath = path16.join(directory, "why-extract.txt");
9394
- const mapPath = path16.join(directory, "discovery.map");
9395
- const runLink = (name2, arguments_) => {
9396
- const response = path16.join(directory, `${name2}.rsp`);
9397
- const trace = path16.join(directory, `${name2}-inputs.txt`);
9398
- fs6.writeFileSync(
9399
- response,
9400
- [...arguments_, "--trace"].map((argument2) => JSON.stringify(argument2)).join(" ")
9401
- );
9402
- const output = fs6.openSync(trace, "w");
9438
+ async function downloadToFile(url, destPath, signal) {
9439
+ fs7.mkdirSync(path17.dirname(destPath), { recursive: true });
9440
+ const tmp = `${destPath}.partial`;
9441
+ for (let attempt = 1; attempt <= 4; attempt++) {
9442
+ signal?.throwIfAborted();
9443
+ let reader2;
9444
+ let handle;
9445
+ let completed = false;
9403
9446
  try {
9404
- execFileSync7(wasmLd, [`@${response}`], { stdio: ["ignore", output, "pipe"] });
9405
- } finally {
9406
- fs6.closeSync(output);
9407
- }
9408
- return fs6.readFileSync(trace, "utf8");
9409
- };
9410
- let discoveryProjection;
9411
- if (options.projection) {
9412
- const source = path16.join(directory, "projection-discovery.c");
9413
- discoveryProjection = path16.join(directory, "projection-discovery.o");
9414
- fs6.writeFileSync(
9415
- source,
9416
- '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
9417
- );
9418
- execFileSync7(
9419
- clang,
9420
- [...options.projection.clangOptions, "-c", source, "-o", discoveryProjection],
9421
- { stdio: "pipe" }
9422
- );
9423
- }
9424
- const archives = /* @__PURE__ */ new Map();
9425
- const memberBytes = /* @__PURE__ */ new Map();
9426
- const prepare = (provider2) => {
9427
- const trace = runLink("discovery", [
9428
- ...withOutput(args, discovery, true),
9429
- ...discoveryProjection ? [discoveryProjection] : [],
9430
- ...provider2 ? ["--undefined=__peach_dlsym_from_image"] : [],
9431
- `--why-extract=${whyPath}`,
9432
- `--Map=${mapPath}`
9433
- ]);
9434
- const selected2 = selectedGuestLinkInputs(
9435
- plan,
9436
- args,
9437
- fs6.readFileSync(whyPath, "utf8"),
9438
- trace
9439
- );
9440
- if (options.resolvePlan) {
9441
- const identity = (value) => JSON.stringify([
9442
- value.images.map(({ id, name: name2 }) => [id, name2]),
9443
- value.artifacts.map(
9444
- ({
9445
- path: file,
9446
- kind,
9447
- image,
9448
- memberImages,
9449
- memberOrigins,
9450
- instrumentDynamicLookups
9451
- }) => [
9452
- file,
9453
- kind,
9454
- image,
9455
- memberImages ? [...memberImages] : null,
9456
- memberOrigins ? [...memberOrigins] : null,
9457
- instrumentDynamicLookups
9458
- ]
9459
- )
9460
- ]);
9461
- const originalOwnership = identity(plan);
9462
- const resolved = options.resolvePlan(selected2, plan);
9463
- if (identity(resolved) !== originalOwnership)
9464
- throw new Error("resolved guest scopes changed input ownership");
9465
- plan = resolved;
9466
- }
9467
- const objectsByImage = /* @__PURE__ */ new Map();
9468
- for (const image of plan.images) objectsByImage.set(image.id, []);
9469
- const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
9470
- for (const item of selected2) {
9471
- const artifact = artifacts.get(item.artifact);
9472
- const image = selectedGuestInputImage(artifact, item.member);
9473
- let bytes;
9474
- if (item.member === null) bytes = fs6.readFileSync(item.artifact);
9475
- else {
9476
- let byName = memberBytes.get(item.artifact);
9477
- if (!byName) {
9478
- const members = readArMembers(fs6.readFileSync(item.artifact));
9479
- archives.set(item.artifact, members);
9480
- byName = /* @__PURE__ */ new Map();
9481
- for (const member of members)
9482
- if (!byName.has(member.name)) byName.set(member.name, member.bytes);
9483
- memberBytes.set(item.artifact, byName);
9447
+ const res = await fetch(url, { signal });
9448
+ if (!res.ok || !res.body) {
9449
+ throw new DownloadHttpError(res.status, res.statusText, url);
9450
+ }
9451
+ reader2 = res.body.getReader();
9452
+ handle = await fs7.promises.open(tmp, "w");
9453
+ let written = 0;
9454
+ for (; ; ) {
9455
+ signal?.throwIfAborted();
9456
+ const { done, value } = await reader2.read();
9457
+ if (done) break;
9458
+ let offset = 0;
9459
+ while (offset < value.byteLength) {
9460
+ const { bytesWritten } = await handle.write(
9461
+ value,
9462
+ offset,
9463
+ value.byteLength - offset
9464
+ );
9465
+ offset += bytesWritten;
9484
9466
  }
9485
- bytes = byName.get(item.member);
9467
+ written += value.byteLength;
9486
9468
  }
9487
- const objects = objectsByImage.get(image);
9488
- if (!objects) throw new Error(`unknown image ${image}`);
9489
- objects.push({
9490
- path: item.member === null ? item.artifact : `${item.artifact}(${item.member})`,
9491
- bytes,
9492
- // the actual loader delegates non-ledger lookups to libc; wrapping its
9493
- // own dlsym call would recurse back into the loader.
9494
- instrumentDynamicLookups: artifact.instrumentDynamicLookups && !guestWasmSymbols(bytes).defined.includes("__peach_dlsym_from_image")
9469
+ await handle.close();
9470
+ handle = void 0;
9471
+ if (!res.headers.get("content-encoding")) {
9472
+ const header = res.headers.get("content-length");
9473
+ const expected = header ? Number(header) : Number.NaN;
9474
+ if (Number.isFinite(expected) && expected > 0 && written !== expected) {
9475
+ throw new Error(`incomplete download (${written}/${expected} bytes): ${url}`);
9476
+ }
9477
+ }
9478
+ signal?.throwIfAborted();
9479
+ fs7.renameSync(tmp, destPath);
9480
+ completed = true;
9481
+ return;
9482
+ } catch (err) {
9483
+ if (handle) await handle.close().catch(() => {
9495
9484
  });
9485
+ if (reader2 && !completed) await reader2.cancel().catch(() => {
9486
+ });
9487
+ try {
9488
+ fs7.unlinkSync(tmp);
9489
+ } catch {
9490
+ }
9491
+ const nonRetryable = err instanceof DownloadHttpError && !err.retryable;
9492
+ if (signal?.aborted || nonRetryable || attempt === 4) throw err;
9493
+ await waitRetryDelay(250 * attempt, signal);
9496
9494
  }
9497
- const ledger2 = createGuestImageLedger({
9498
- images: plan.images.map((image) => ({
9499
- ...image,
9500
- objects: objectsByImage.get(image.id)
9501
- })),
9502
- callers: plan.callers,
9503
- symbols: plan.symbols,
9504
- liveSymbols: linkedMapSymbols(fs6.readFileSync(mapPath, "utf8")),
9505
- commandLineSymbols: commandLineSymbols(args),
9506
- directBindings: plan.directBindings
9495
+ }
9496
+ }
9497
+ async function digestFile(filePath, algorithm, encoding, signal) {
9498
+ const hash = crypto.createHash(algorithm);
9499
+ await pipeline2(fs7.createReadStream(filePath), hash, { signal });
9500
+ return hash.digest(encoding);
9501
+ }
9502
+ function extractZip(zipPath, destDir, signal) {
9503
+ return runExtractor("ditto", ["-x", "-k", zipPath, destDir], signal);
9504
+ }
9505
+ async function extractTarball(tarPath, zstd, destDir, stripComponents, signal) {
9506
+ const args = [zstd ? "-xf" : "-xzf", "-"];
9507
+ if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
9508
+ if (zstd) {
9509
+ const decoder = zlib2.createZstdDecompress({
9510
+ params: { [zlib2.constants.ZSTD_d_windowLogMax]: 30 }
9507
9511
  });
9508
- return { selected: selected2, ledger: ledger2 };
9509
- };
9510
- let prepared = prepare(false);
9511
- const provider = prepared.ledger.callerWrappers.some(
9512
- ({ symbol }) => symbol.startsWith("__peach_dlsym_caller_")
9513
- );
9514
- if (provider) prepared = prepare(true);
9515
- const { selected, ledger } = prepared;
9516
- const replacements = /* @__PURE__ */ new Map();
9517
- const linkedOwners = /* @__PURE__ */ new Map();
9518
- const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]));
9519
- for (const [index, artifact] of plan.artifacts.entries()) {
9520
- const prefix = `${artifact.path}(`;
9521
- if (artifact.kind === "object") {
9522
- const object2 = ledgerObjects.get(artifact.path);
9523
- if (!object2) continue;
9524
- const output2 = path16.join(directory, `object-${index}.o`);
9525
- fs6.writeFileSync(output2, object2.bytes);
9526
- replacements.set(artifact.path, output2);
9527
- linkedOwners.set(output2, selectedGuestInputImage(artifact, null));
9528
- continue;
9529
- }
9530
- const members = archives.get(artifact.path);
9531
- if (!members) continue;
9532
- const listed = execFileSync7(llvmAr, ["t", artifact.path], { encoding: "utf8" }).trimEnd().split("\n");
9533
- if (listed.length !== members.length || new Set(listed).size !== listed.length || members.some(
9534
- (member, i) => listed[i] !== member.name || path16.basename(member.name) !== member.name
9535
- ))
9536
- throw new Error(`unsupported archive layout ${artifact.path}`);
9537
- const memberDir = path16.join(directory, `archive-${index}`);
9538
- fs6.mkdirSync(memberDir, { recursive: true });
9539
- const output = path16.join(directory, `archive-${index}.a`);
9540
- const inputs = members.map((member) => {
9541
- const memberOutput = path16.join(memberDir, member.name);
9542
- const rewritten = ledgerObjects.get(`${prefix}${member.name})`);
9543
- fs6.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes);
9544
- if (rewritten) {
9545
- linkedOwners.set(
9546
- `${output}(${member.name})`,
9547
- selectedGuestInputImage(artifact, member.name)
9548
- );
9549
- }
9550
- return memberOutput;
9512
+ await runExtractor("tar", ["--ignore-zeros", ...args], signal, {
9513
+ cwd: destDir,
9514
+ stdin: (stdin) => pipeline2(fs7.createReadStream(tarPath), decoder, stdin, { signal })
9551
9515
  });
9552
- fs6.rmSync(output, { force: true });
9553
- const response = path16.join(memberDir, "members.rsp");
9554
- fs6.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(" "));
9555
- execFileSync7(llvmAr, ["rcs", output, `@${response}`], { stdio: "pipe" });
9556
- replacements.set(artifact.path, output);
9516
+ return;
9557
9517
  }
9558
- const irPath = path16.join(directory, "ledger.ll");
9559
- const ledgerObject = path16.join(directory, "ledger.o");
9560
- fs6.writeFileSync(irPath, ledger.llvmIR);
9561
- execFileSync7(
9562
- clang,
9563
- ["--target=wasm64-unknown-wasip1", "-c", irPath, "-o", ledgerObject],
9564
- { stdio: "pipe" }
9565
- );
9566
- linkedOwners.set(ledgerObject, options.ledgerDataImage);
9567
- let projectionObject;
9568
- let projectionStorage;
9569
- if (options.projection) {
9570
- const projection = options.projection;
9571
- if (!plan.images.some((image) => image.id === projection.image))
9572
- throw new Error("guest projection has no source image");
9573
- if (projection.images.length !== plan.images.length || projection.images.some(
9574
- (image, index) => image.image !== index || plan.images[index]?.id !== index
9575
- ))
9576
- throw new Error("guest projection image order differs from link plan");
9577
- const selectedInputs = selectedGuestManifestInputs(
9578
- plan,
9579
- selected,
9580
- projection.identities
9581
- );
9582
- const images = projection.images.map(
9583
- (image) => createGuestImageManifest({
9584
- ...image,
9585
- inputs: selectedInputs.get(image.image) ?? [],
9586
- linkOptions: projection.linkOptions,
9587
- regions: []
9588
- })
9589
- );
9590
- const ledgerPieces = guestProjectionRegionCapacity([fs6.readFileSync(ledgerObject)], 0);
9591
- const capacities = ledger.images.map((image) => ({
9592
- regions: guestProjectionRegionCapacity(
9593
- image.objects.map((object2) => object2.bytes),
9594
- 1 + ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length + (image.id === options.ledgerDataImage ? ledgerPieces : 0) + (image.id === projection.image ? images.length + 2 : 0)
9595
- ),
9596
- memoryProtection: projection.memoryProtection,
9597
- tableProtection: projection.tableProtection
9598
- }));
9599
- projectionStorage = reserveGuestProjectionStorage(images, capacities);
9600
- const projectionSource = path16.join(directory, "projection.c");
9601
- projectionObject = path16.join(directory, "projection.o");
9602
- fs6.writeFileSync(projectionSource, projectionStorage.source);
9603
- execFileSync7(
9604
- clang,
9605
- [...projection.clangOptions, "-c", projectionSource, "-o", projectionObject],
9606
- {
9607
- stdio: "pipe"
9608
- }
9609
- );
9610
- linkedOwners.set(projectionObject, projection.image);
9611
- }
9612
- const byToken = new Map(
9613
- occurrences(plan, args).map(({ artifact, token }) => [
9614
- token,
9615
- replacements.get(artifact.path)
9616
- ])
9617
- );
9618
- const placed = /* @__PURE__ */ new Set();
9619
- const finalArgs = args.map((arg) => byToken.get(arg) ?? arg).filter((arg) => {
9620
- if (!arg.endsWith(".o") && !arg.endsWith(".a")) return true;
9621
- if (placed.has(arg)) return false;
9622
- placed.add(arg);
9623
- return true;
9624
- });
9625
- const finalOutput = path16.join(directory, "final.wasm");
9626
- const finalWhy = path16.join(directory, "final-why-extract.txt");
9627
- const finalTrace = runLink("final", [
9628
- ...withOutput(finalArgs, finalOutput, false),
9629
- ledgerObject,
9630
- ...projectionObject ? [projectionObject] : [],
9631
- ...provider ? ["--undefined=__peach_dlsym_from_image"] : [],
9632
- `--why-extract=${finalWhy}`
9633
- ]);
9634
- const finalSelection = selectedGuestLinkInputs(
9635
- remapGuestLinkPlan(plan, replacements),
9636
- finalArgs,
9637
- fs6.readFileSync(finalWhy, "utf8"),
9638
- finalTrace
9639
- );
9640
- const original = new Map([...replacements].map(([before2, after2]) => [after2, before2]));
9641
- const key = (item) => JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member]);
9642
- const before = new Set(selected.map(key));
9643
- const after = new Set(finalSelection.map(key));
9644
- const changed = [...before].filter((item) => !after.has(item));
9645
- changed.push(...[...after].filter((item) => !before.has(item)));
9646
- if (changed.length)
9647
- throw new Error(
9648
- `guest link selected different inputs after rewriting:
9649
- ${changed.join("\n")}`
9650
- );
9651
- fs6.renameSync(finalOutput, outputPath(args));
9652
- if (projectionStorage && projectionObject)
9653
- options.projection.onReserved(projectionStorage, projectionObject);
9654
- options.onLinkedOwners?.(linkedOwners);
9655
- options.onLinkedSections?.(
9656
- new Map(
9657
- ledger.callerWrappers.map(({ symbol, image }) => [
9658
- `${ledgerObject}:(${symbol})`,
9659
- image
9660
- ])
9661
- )
9662
- );
9663
- return selected;
9664
- }
9665
- function linkedMapSymbols(map) {
9666
- const names = /* @__PURE__ */ new Set();
9667
- for (const match of map.matchAll(/^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/gm))
9668
- names.add(match[1]);
9669
- return names;
9670
- }
9671
- function commandLineSymbols(args) {
9672
- const names = [];
9673
- for (const [i, arg] of args.entries()) {
9674
- if (arg === "--entry" || arg === "-e" || arg === "-u") names.push(args[i + 1]);
9675
- else
9676
- for (const flag of [
9677
- "--entry=",
9678
- "--undefined=",
9679
- "--export=",
9680
- "--export-if-defined="
9681
- ])
9682
- if (arg.startsWith(flag)) names.push(arg.slice(flag.length));
9683
- }
9684
- return names;
9685
- }
9686
- function normalizedGuestLinkArgs(input) {
9687
- const args = [];
9688
- for (let i = 0; i < input.length; i++) {
9689
- const arg = input[i];
9690
- if (arg === "-l" || arg === "--library") args.push(`-l${input[++i]}`);
9691
- else if (arg === "-L" || arg === "--library-path") args.push(`-L${input[++i]}`);
9692
- else if (arg.startsWith("--library=")) args.push(`-l${arg.slice(10)}`);
9693
- else if (arg.startsWith("--library-path=")) args.push(`-L${arg.slice(15)}`);
9694
- else args.push(arg);
9518
+ const archive = fs7.openSync(tarPath, "r");
9519
+ try {
9520
+ await runExtractor("tar", args, signal, { cwd: destDir, stdin: archive });
9521
+ } finally {
9522
+ fs7.closeSync(archive);
9695
9523
  }
9696
- return args;
9697
- }
9698
- function aliasGuestLinkArguments(input, archives) {
9699
- const args = normalizedGuestLinkArgs(input);
9700
- const directories = args.filter((arg) => arg.startsWith("-L")).map((arg) => arg.slice(2));
9701
- const aliases = new Map(
9702
- archives.map((archive) => [path16.resolve(archive.source), archive.archive])
9703
- );
9704
- if (aliases.size !== archives.length)
9705
- throw new Error("duplicate original guest archive");
9706
- const used = /* @__PURE__ */ new Set();
9707
- const result = args.map((arg) => {
9708
- let file = arg;
9709
- if (arg.startsWith("-l") && arg.length > 2) {
9710
- const name2 = arg.slice(2);
9711
- const library = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
9712
- file = directories.map((directory) => path16.join(directory, library)).find((candidate) => fs6.existsSync(candidate)) ?? arg;
9713
- }
9714
- if (file.startsWith("-")) return arg;
9715
- const source = path16.resolve(file);
9716
- const alias = aliases.get(source);
9717
- if (alias === void 0) return arg;
9718
- used.add(source);
9719
- return alias;
9720
- });
9721
- if (used.size !== aliases.size)
9722
- throw new Error("aliased guest archive is not a link input");
9723
- return result;
9724
9524
  }
9725
- function linkCompleteGuestImages(options) {
9726
- const args = normalizedGuestLinkArgs(options.args);
9727
- const unowned = unownedGuestLinkInputs(options.plan, args);
9728
- const candidates = unowned.map((file) => {
9729
- const descriptor = fs6.openSync(file, "r");
9730
- const magic = Buffer.alloc(8);
9731
- try {
9732
- fs6.readSync(descriptor, magic, 0, magic.length, 0);
9733
- } finally {
9734
- fs6.closeSync(descriptor);
9735
- }
9736
- return {
9737
- path: file,
9738
- kind: magic.toString("ascii") === "!<arch>\n" ? "archive" : "object",
9739
- image: null,
9740
- instrumentDynamicLookups: false
9741
- };
9742
- });
9743
- return linkGuestImages({
9744
- ...options,
9745
- args,
9746
- plan: { ...options.plan, artifacts: [...options.plan.artifacts, ...candidates] }
9525
+ async function runExtractor(command, args, signal, input) {
9526
+ signal?.throwIfAborted();
9527
+ const stdin = input?.stdin;
9528
+ const stdio = [
9529
+ typeof stdin === "function" ? "pipe" : stdin ?? "ignore",
9530
+ "inherit",
9531
+ "inherit"
9532
+ ];
9533
+ const child = spawn3(command, args, {
9534
+ cwd: input?.cwd,
9535
+ stdio,
9536
+ detached: process.platform !== "win32"
9747
9537
  });
9748
- }
9749
- function discoverGuestLinkInputs(options) {
9750
- const args = normalizedGuestLinkArgs(options.args);
9751
- const artifacts = guestLinkInputFiles(args).map((file) => {
9752
- const descriptor = fs6.openSync(file, "r");
9753
- const magic = Buffer.alloc(8);
9754
- try {
9755
- fs6.readSync(descriptor, magic, 0, magic.length, 0);
9756
- } finally {
9757
- fs6.closeSync(descriptor);
9758
- }
9759
- const kind = magic.toString("ascii") === "!<arch>\n" ? "archive" : "object";
9760
- return { path: file, kind, image: 0, instrumentDynamicLookups: false };
9538
+ const fed = typeof stdin === "function" && child.stdin ? stdin(child.stdin) : void 0;
9539
+ void fed?.catch(() => {
9761
9540
  });
9762
- const plan = { images: [], callers: [], artifacts, symbols: [] };
9763
- fs6.mkdirSync(options.directory, { recursive: true });
9764
- const why = path16.join(options.directory, "preselection-why.txt");
9765
- const response = path16.join(options.directory, "preselection.rsp");
9766
- const output = path16.join(options.directory, "preselection.wasm");
9767
- const flags = [
9768
- ...withOutput(args, output, true),
9769
- ...options.objects,
9770
- // the loader runtime backs every image's lookup wrappers, so it belongs to
9771
- // the selection that assigns member owners.
9772
- "--undefined=__peach_dlsym_from_image",
9773
- `--why-extract=${why}`,
9774
- "--trace"
9775
- ];
9776
- fs6.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(" "));
9777
- const trace = path16.join(options.directory, "preselection-inputs.txt");
9778
- const traceOutput = fs6.openSync(trace, "w");
9541
+ let stopping;
9542
+ const abort = () => {
9543
+ stopping ?? (stopping = terminateProcessGroup(child, "SIGKILL", 0));
9544
+ void stopping.catch(() => {
9545
+ });
9546
+ };
9779
9547
  try {
9780
- execFileSync7(options.wasmLd, [`@${response}`], {
9781
- stdio: ["ignore", traceOutput, "pipe"]
9548
+ await new Promise((resolve, reject) => {
9549
+ let failure;
9550
+ child.on("error", (error) => {
9551
+ failure = error;
9552
+ });
9553
+ child.on("close", (code) => {
9554
+ if (signal?.aborted) {
9555
+ const reason = signal.reason;
9556
+ reject(
9557
+ reason instanceof Error ? reason : new Error("Extraction canceled", { cause: reason })
9558
+ );
9559
+ } else if (failure) reject(failure);
9560
+ else if (code === 0) resolve();
9561
+ else reject(new Error(`${command} exited with code ${code}`));
9562
+ });
9563
+ signal?.addEventListener("abort", abort, { once: true });
9564
+ if (signal?.aborted) abort();
9782
9565
  });
9566
+ await fed;
9783
9567
  } finally {
9784
- fs6.closeSync(traceOutput);
9568
+ signal?.removeEventListener("abort", abort);
9569
+ await stopping;
9785
9570
  }
9786
- return selectedGuestLinkInputs(
9787
- plan,
9788
- args,
9789
- fs6.readFileSync(why, "utf8"),
9790
- fs6.readFileSync(trace, "utf8")
9791
- );
9792
9571
  }
9793
- function prepareGuestRuntimeInputs(options) {
9794
- const originals = new Map(
9795
- [...options.rewritten].map(([before, after]) => [
9796
- path16.resolve(after),
9797
- path16.resolve(before)
9798
- ])
9799
- );
9800
- if (originals.size !== options.rewritten.size)
9801
- throw new Error("ambiguous rewritten runtime input");
9802
- const recordedArchives = new Set(
9803
- options.products.flatMap(
9804
- ({ product, root }) => product.artifacts.flatMap(
9805
- (artifact) => artifact.kind === "archive" ? [path16.resolve(root, artifact.path)] : []
9806
- )
9807
- )
9808
- );
9809
- const archives = [];
9810
- for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
9811
- const original = originals.get(file) ?? file;
9812
- if (!recordedArchives.has(original)) continue;
9813
- const members = readArMembers(fs6.readFileSync(file));
9814
- if (new Set(members.map((member) => member.name)).size === members.length) continue;
9815
- archives.push(
9816
- aliasGuestArchive({
9817
- archive: file,
9818
- directory: path16.join(options.directory, `archive-${archives.length}`),
9819
- llvmAr: options.llvmAr
9820
- })
9821
- );
9822
- }
9823
- const args = aliasGuestLinkArguments(options.args, archives);
9824
- const selected = discoverGuestLinkInputs({
9825
- args,
9826
- directory: options.directory,
9827
- wasmLd: options.wasmLd,
9828
- objects: options.discoveryObjects
9829
- });
9830
- const closure = guestRuntimeProductsForInputs({
9831
- products: options.products,
9832
- selected: originalGuestArchiveSelections(selected, archives),
9833
- rewritten: options.rewritten,
9834
- sdk: options.sdk,
9835
- firstImage: options.firstImage,
9836
- containingImage: options.containingImage,
9837
- framework: options.framework
9838
- });
9839
- const aliasSources = new Set(
9840
- archives.map(
9841
- (archive) => originals.get(path16.resolve(archive.source)) ?? path16.resolve(archive.source)
9842
- )
9843
- );
9844
- const sdkProducts = {
9845
- products: options.products,
9846
- images: closure.images,
9847
- containingImages: closure.containingImages,
9848
- linkedArchives: closure.linkedArchives.filter(
9849
- (archive) => !aliasSources.has(path16.resolve(archive))
9850
- )
9851
- };
9852
- const archiveArtifacts = guestAliasedSdkArchiveArtifacts({
9853
- products: options.products,
9854
- archives,
9855
- selected,
9856
- rewritten: options.rewritten,
9857
- images: new Map([...closure.images, ...closure.containingImages])
9858
- });
9859
- return { args, selected, archives, sdkProducts, archiveArtifacts };
9860
- }
9861
- function selectedGuestSymbolInputs(plan, selected) {
9862
- const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
9863
- const archives = /* @__PURE__ */ new Map();
9864
- const symbols = /* @__PURE__ */ new Set();
9865
- const hostImports = /* @__PURE__ */ new Set();
9866
- const tags = /* @__PURE__ */ new Set();
9867
- const definitions = /* @__PURE__ */ new Set();
9868
- const owners = /* @__PURE__ */ new Map();
9869
- const weakReferences = /* @__PURE__ */ new Map();
9870
- const weakDefinitions = /* @__PURE__ */ new Map();
9871
- const definitionObjects = /* @__PURE__ */ new Map();
9872
- for (const item of selected) {
9873
- const artifact = artifacts.get(item.artifact);
9874
- if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
9875
- let bytes;
9876
- let name2 = item.artifact;
9877
- if (item.member === null) bytes = fs6.readFileSync(item.artifact);
9878
- else {
9879
- let members = archives.get(item.artifact);
9880
- if (!members) {
9881
- members = Map.groupBy(
9882
- readArMembers(fs6.readFileSync(item.artifact)),
9883
- (member) => member.name
9884
- );
9885
- archives.set(item.artifact, members);
9886
- }
9887
- const matching = members.get(item.member) ?? [];
9888
- if (matching.length !== 1)
9889
- throw new Error(
9890
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
9891
- );
9892
- bytes = matching[0].bytes;
9893
- name2 += `(${item.member})`;
9894
- }
9895
- if (owners.has(name2)) throw new Error(`duplicate selected symbol input ${name2}`);
9896
- owners.set(name2, selectedGuestInputImage(artifact, item.member));
9897
- const names = guestWasmSymbols(bytes);
9898
- weakReferences.set(name2, new Set(names.weakUndefined));
9899
- weakDefinitions.set(name2, new Set(names.weakDefined));
9900
- for (const symbol of names.undefined) symbols.add(symbol);
9901
- for (const symbol of names.hostImports) hostImports.add(symbol);
9902
- for (const symbol of names.tags) tags.add(symbol);
9903
- for (const symbol of names.defined) {
9904
- definitions.add(symbol);
9905
- const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
9906
- objects.add(name2);
9907
- definitionObjects.set(symbol, objects);
9572
+
9573
+ // src/binaryen.lock.json
9574
+ var binaryen_lock_default = {
9575
+ version: "132",
9576
+ licenseSha256: "64c0d02491e16eced74826440ecd2bcf7722d37fa586faf457b2494293afbffe",
9577
+ platforms: {
9578
+ "linux-x64": {
9579
+ asset: "x86_64-linux",
9580
+ upstreamSha256: "195ddc94f9bc89f45abdabb0b9eea86023d727ba90eac8b35b80f2544fc30572",
9581
+ sha256: "0396b1a540e9f97f30eb6a378d829305c218c821a0bd88c74e83d3d6923dad0b"
9582
+ },
9583
+ "linux-arm64": {
9584
+ asset: "aarch64-linux",
9585
+ upstreamSha256: "c58562417836c5d0493d89bdefc434933bdc097db641b483df86bcfa557a107f",
9586
+ sha256: "25e3747f19614b0281a28b9a909ddc602b546ccdfacebc8cae2f7165665328fa"
9587
+ },
9588
+ "darwin-arm64": {
9589
+ asset: "arm64-macos",
9590
+ upstreamSha256: "98aad827847af7ef990ed7098d885725c8e5b5aae75073403635617ae4e259aa",
9591
+ sha256: "34281566fe32df71337aaf0b60aa265dc853587d92bda0b5b1fac8aed8c2f8ab"
9908
9592
  }
9909
9593
  }
9910
- return {
9911
- symbols: [...symbols].filter((symbol) => !tags.has(symbol)),
9912
- definitions: [...definitions].filter((symbol) => !tags.has(symbol)),
9913
- hostImports,
9914
- owners,
9915
- weakReferences,
9916
- weakDefinitions,
9917
- definitionObjects
9918
- };
9594
+ };
9595
+
9596
+ // src/home-paths.ts
9597
+ import { randomUUID as randomUUID2 } from "node:crypto";
9598
+ import fs8 from "node:fs";
9599
+ import { homedir } from "node:os";
9600
+ import path18 from "node:path";
9601
+ var PEACH_HOME_ENV = "PEACH_HOME";
9602
+ var ACTIVE_RUNTIME_FILE = "active";
9603
+ function ambientHomeDir() {
9604
+ return path18.join(homedir(), ".peach");
9919
9605
  }
9920
- function verifyGuestSymbolScopes(options) {
9921
- const symbols = [...new Set(options.symbols)];
9922
- const requested = new Set(symbols);
9923
- if (symbols.some((symbol) => !symbol || symbol.includes("\0") || symbol.includes("\n")))
9924
- throw new Error("invalid traced guest symbol");
9925
- if (!symbols.length) return { bindings: [], directBindings: [] };
9926
- fs6.mkdirSync(options.directory, { recursive: true });
9927
- const response = path16.join(options.directory, "scope-trace.rsp");
9928
- const output = path16.join(options.directory, "scope-trace.wasm");
9929
- const args = [
9930
- ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
9931
- ...options.objects,
9932
- ...symbols.map((symbol) => `--trace-symbol=${symbol}`)
9933
- ];
9934
- fs6.writeFileSync(response, args.map((arg) => JSON.stringify(arg)).join(" "));
9935
- const tracePath = path16.join(options.directory, "scope-trace.txt");
9936
- const traceOutput = fs6.openSync(tracePath, "w");
9606
+ function rnxHomeDir() {
9607
+ const override = process.env[PEACH_HOME_ENV];
9608
+ return override && override.length > 0 ? path18.resolve(override) : ambientHomeDir();
9609
+ }
9610
+ function runtimesDir() {
9611
+ return path18.join(rnxHomeDir(), "runtimes");
9612
+ }
9613
+ function runtimeDir(version2) {
9614
+ return path18.join(runtimesDir(), version2);
9615
+ }
9616
+ function activeRuntimeFile() {
9617
+ return path18.join(runtimesDir(), ACTIVE_RUNTIME_FILE);
9618
+ }
9619
+ function cacheDir() {
9620
+ return path18.join(rnxHomeDir(), "cache");
9621
+ }
9622
+ function readActiveRuntime() {
9937
9623
  try {
9938
- execFileSync7(options.wasmLd, [`@${response}`], {
9939
- stdio: ["ignore", traceOutput, "pipe"]
9940
- });
9941
- } finally {
9942
- fs6.closeSync(traceOutput);
9624
+ const value = fs8.readFileSync(activeRuntimeFile(), "utf8").trim();
9625
+ return value.length > 0 ? value : null;
9626
+ } catch {
9627
+ return null;
9943
9628
  }
9944
- const records = /* @__PURE__ */ new Map();
9945
- const consume = (line) => {
9946
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
9947
- if (!match) return;
9948
- const [, object2, kind, symbol] = match;
9949
- if (!requested.has(symbol)) return;
9950
- if (options.hostImports.has(symbol)) return;
9951
- const record = records.get(symbol) ?? {
9952
- references: /* @__PURE__ */ new Map(),
9953
- providers: /* @__PURE__ */ new Map(),
9954
- physicalModule: false
9955
- };
9956
- if (object2 === "<internal>") {
9957
- if (kind === "definition of") record.physicalModule = true;
9958
- } else {
9959
- const image = options.owners.get(object2);
9960
- if (image === void 0)
9961
- throw new Error(`traced guest object has no owner ${object2}`);
9962
- (kind === "reference to" ? record.references : record.providers).set(
9963
- object2,
9964
- image
9965
- );
9629
+ }
9630
+ var DAEMON_LOCKFILE_MAX_BYTES = 16 * 1024;
9631
+
9632
+ // src/wasm-narrow-boundary.ts
9633
+ var I64 = 126;
9634
+ var VALUE_TYPES = /* @__PURE__ */ new Map([
9635
+ [127, "i32"],
9636
+ [I64, "i64"],
9637
+ [125, "f32"],
9638
+ [124, "f64"],
9639
+ [123, "v128"],
9640
+ [112, "funcref"],
9641
+ [111, "externref"]
9642
+ ]);
9643
+ var GUEST = "guest";
9644
+ var BOUNDARY = "boundary";
9645
+ var WIDE = "$wide.";
9646
+ var NARROW = "$narrow.";
9647
+ function encodeNumber2(value) {
9648
+ const bytes = [];
9649
+ for (let rest = value; ; ) {
9650
+ const byte = rest % 128;
9651
+ rest = Math.floor(rest / 128);
9652
+ if (rest === 0) return [...bytes, byte];
9653
+ bytes.push(byte | 128);
9654
+ }
9655
+ }
9656
+ function encodeName(name2) {
9657
+ const bytes = [...Buffer.from(name2)];
9658
+ return [...encodeNumber2(bytes.length), ...bytes];
9659
+ }
9660
+ function reader(bytes, start, end) {
9661
+ let at = start;
9662
+ const number3 = () => {
9663
+ let value = 0;
9664
+ for (let shift = 0; ; shift += 7) {
9665
+ if (at >= end || shift > 63) throw new Error("invalid wasm integer");
9666
+ const byte = bytes[at++];
9667
+ value += (byte & 127) * 2 ** shift;
9668
+ if (!(byte & 128)) return value;
9966
9669
  }
9967
- records.set(symbol, record);
9968
9670
  };
9969
- const traceInput = fs6.openSync(tracePath, "r");
9970
- try {
9971
- const decoder = new StringDecoder("utf8");
9972
- const buffer = Buffer.allocUnsafe(64 * 1024);
9973
- let pending = "";
9974
- let count;
9975
- while ((count = fs6.readSync(traceInput, buffer, 0, buffer.length, null)) > 0) {
9976
- pending += decoder.write(buffer.subarray(0, count));
9977
- let end;
9978
- while ((end = pending.indexOf("\n")) !== -1) {
9979
- consume(pending.slice(0, end));
9980
- pending = pending.slice(end + 1);
9981
- }
9982
- }
9983
- consume(pending + decoder.end());
9984
- } finally {
9985
- fs6.closeSync(traceInput);
9671
+ return {
9672
+ number: number3,
9673
+ byte: () => {
9674
+ if (at >= end) throw new Error("truncated wasm section");
9675
+ return bytes[at++];
9676
+ },
9677
+ name: () => {
9678
+ const length = number3();
9679
+ at += length;
9680
+ if (at > end) throw new Error("truncated wasm name");
9681
+ return Buffer.from(bytes.subarray(at - length, at)).toString();
9682
+ },
9683
+ position: () => at,
9684
+ done: () => at === end
9685
+ };
9686
+ }
9687
+ function sections(bytes) {
9688
+ if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
9689
+ throw new Error("not a wasm module");
9690
+ const found = [];
9691
+ for (let at = 8; at < bytes.length; ) {
9692
+ const header = reader(bytes, at, bytes.length);
9693
+ const id = header.byte();
9694
+ const size = header.number();
9695
+ const start = header.position();
9696
+ found.push({ id, start, end: start + size });
9697
+ at = start + size;
9986
9698
  }
9987
- const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]));
9988
- const result = [];
9989
- const directBindings = [];
9990
- for (const symbol of symbols) {
9991
- const record = records.get(symbol);
9992
- if (!record || !record.references.size) continue;
9993
- if (!record.providers.size && options.hostImports.has(symbol)) continue;
9994
- const startupReferences = [...record.references].filter(
9995
- ([object2]) => options.startupObjects.has(object2) && options.weakReferences.get(object2)?.has(symbol)
9996
- );
9997
- const otherReferences = [...record.references].filter(
9998
- ([object2]) => !startupReferences.some(([startup]) => startup === object2)
9699
+ return found;
9700
+ }
9701
+ function withSections(bytes, layout2, replacements) {
9702
+ const parts = [bytes.subarray(0, 8)];
9703
+ let at = 8;
9704
+ for (const section of layout2) {
9705
+ const body = replacements.get(section.id);
9706
+ parts.push(
9707
+ body ? Uint8Array.from([section.id, ...encodeNumber2(body.length), ...body]) : bytes.subarray(at, section.end)
9999
9708
  );
10000
- for (const [, caller] of startupReferences)
10001
- if (!callers.has(caller))
10002
- throw new Error(`guest image has no caller scope ${caller}`);
10003
- if (startupReferences.length && !record.physicalModule) {
10004
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10005
- if (candidates.size > 1 || record.providers.size > 1)
10006
- throw new Error(`ambiguous startup provider ${symbol}`);
10007
- if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object2) => !candidates.has(object2)))
10008
- throw new Error(`unproven startup provider ${symbol}`);
10009
- if (record.providers.size === 1) {
10010
- const [providerObject, providerImage] = [...record.providers][0];
10011
- if (options.weakDefinitions.get(providerObject)?.has(symbol))
10012
- throw new Error(`weak startup provider ${symbol}`);
10013
- for (const [object2] of startupReferences)
10014
- directBindings.push({ object: object2, symbol, providerObject, providerImage });
10015
- }
10016
- if (!otherReferences.length) continue;
9709
+ at = section.end;
9710
+ }
9711
+ return Buffer.concat(parts);
9712
+ }
9713
+ var quoted = (name2) => `"${[...Buffer.from(name2)].map((byte) => `\\${byte.toString(16).padStart(2, "0")}`).join("")}"`;
9714
+ var signature = (types, keyword, narrow) => types.length === 0 ? "" : ` (${keyword} ${types.map((type) => {
9715
+ const name2 = VALUE_TYPES.get(narrow && type === I64 ? 127 : type);
9716
+ if (!name2) throw new Error(`unsupported wasm boundary type ${type}`);
9717
+ return name2;
9718
+ }).join(" ")})`;
9719
+ var wide = (type) => type.parameters.includes(I64) || type.results.includes(I64);
9720
+ function narrowWasmBoundary(bytes) {
9721
+ const layout2 = sections(bytes);
9722
+ const section = (id) => {
9723
+ const found = layout2.find((entry) => entry.id === id);
9724
+ return found && reader(bytes, found.start, found.end);
9725
+ };
9726
+ const types = [];
9727
+ const typeSection = section(1);
9728
+ if (typeSection) {
9729
+ for (let count = typeSection.number(); count > 0; count--) {
9730
+ if (typeSection.byte() !== 96) throw new Error("unsupported wasm type");
9731
+ const values = () => Array.from({ length: typeSection.number() }, () => typeSection.byte());
9732
+ types.push({ parameters: values(), results: values() });
10017
9733
  }
10018
- if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
10019
- (object2) => options.weakReferences.get(object2)?.has(symbol)
10020
- ))
10021
- continue;
10022
- const providerImages = new Set(record.providers.values());
10023
- const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
10024
- (object2) => {
10025
- const image = options.owners.get(object2);
10026
- return image === void 0 ? [] : [{ image, weak: !!options.weakDefinitions.get(object2)?.has(symbol) }];
10027
- }
10028
- );
10029
- const copyImages = new Set(copies.map((copy) => copy.image));
10030
- const strongImages = new Set(
10031
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
10032
- );
10033
- const interposed = !record.physicalModule && copyImages.size > 1 && strongImages.size <= 1;
10034
- const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
10035
- if (!providerCount) continue;
10036
- if (providerCount !== 1)
10037
- throw new Error(`guest symbol has ambiguous provider ${symbol}`);
10038
- const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
10039
- for (const [object2, caller] of scopedReferences) {
10040
- const scope = callers.get(caller);
10041
- if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
10042
- if (record.physicalModule) {
10043
- result.push({ symbol, caller, provider: { kind: "physical-module" } });
10044
- continue;
10045
- }
10046
- const provider = interposed ? [caller, ...scope].find((image) => copyImages.has(image)) ?? [...strongImages][0] ?? [...providerImages][0] : [...providerImages][0];
10047
- if (provider === void 0)
10048
- throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
10049
- if (caller === provider) continue;
10050
- if ([...options.definitionObjects.get(symbol) ?? []].some(
10051
- (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
10052
- ))
10053
- continue;
10054
- if (!scope.includes(provider)) {
10055
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10056
- const traced = [...record.providers.keys()];
10057
- const strongTraced = traced.filter(
10058
- (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10059
- );
10060
- const providers = strongTraced.length === 1 ? strongTraced : traced;
10061
- if (options.weakReferences.get(object2)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
10062
- continue;
10063
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
10064
- (definer) => options.weakDefinitions.get(definer)?.has(symbol)
9734
+ }
9735
+ const typeAt = (index) => {
9736
+ const type = types[index];
9737
+ if (!type) throw new Error("invalid wasm type index");
9738
+ return type;
9739
+ };
9740
+ const thunks = [];
9741
+ const functionTypes = [];
9742
+ const importBody = [];
9743
+ const importSection = section(2);
9744
+ if (importSection) {
9745
+ const count = importSection.number();
9746
+ importBody.push(...encodeNumber2(count));
9747
+ for (let index = 0; index < count; index++) {
9748
+ const module = importSection.name();
9749
+ const name2 = importSection.name();
9750
+ const start = importSection.position();
9751
+ const kind = importSection.byte();
9752
+ const limits = () => {
9753
+ const flags = importSection.number();
9754
+ importSection.number();
9755
+ if (flags & 1) importSection.number();
9756
+ };
9757
+ let type;
9758
+ if (kind === 0) {
9759
+ type = typeAt(importSection.number());
9760
+ functionTypes.push(type);
9761
+ } else if (kind === 1) {
9762
+ importSection.byte();
9763
+ limits();
9764
+ } else if (kind === 2) limits();
9765
+ else if (kind === 3) {
9766
+ importSection.byte();
9767
+ importSection.byte();
9768
+ } else if (kind === 4) {
9769
+ importSection.byte();
9770
+ importSection.number();
9771
+ } else throw new Error("unsupported wasm import");
9772
+ const scalar64 = (parameter) => module === "wasi_snapshot_preview1" && (!name2.startsWith("peach_") || name2 === "peach_fs_path_birthtime_set" && parameter === 2) || module === "peach" && name2 === "hw_memsize" && parameter === null || module === "peach_notify" && name2 === "set" && parameter === 1;
9773
+ const parameters = type?.parameters.map(
9774
+ (value, index2) => value === I64 && !scalar64(index2) ? 127 : value
9775
+ );
9776
+ const results = type?.results.map(
9777
+ (value) => value === I64 && !scalar64(null) ? 127 : value
9778
+ );
9779
+ if (type && parameters && results && (parameters.some((value, index2) => value !== type.parameters[index2]) || results.some((value, index2) => value !== type.results[index2]))) {
9780
+ if (type.results.length > 1)
9781
+ throw new Error(`import ${module}.${name2} returns several values`);
9782
+ const id = thunks.length;
9783
+ const call = `(call $host${id}${type.parameters.map(
9784
+ (value, at) => value !== parameters[at] ? ` (i32.wrap_i64 (local.get ${at}))` : ` (local.get ${at})`
9785
+ ).join("")})`;
9786
+ thunks.push(
9787
+ `(import ${quoted(module)} ${quoted(name2)} (func $host${id}${signature(parameters, "param", false)}${signature(results, "result", false)}))`,
9788
+ `(func (export "${NARROW}${id}")${signature(type.parameters, "param", false)}${signature(type.results, "result", false)} ${type.results[0] !== results[0] ? `(i64.extend_i32_u ${call})` : call})`
10065
9789
  );
10066
- const strongCandidates = [...candidates].filter(
10067
- (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
9790
+ importBody.push(...encodeName(BOUNDARY), ...encodeName(`${NARROW}${id}`));
9791
+ } else importBody.push(...encodeName(module), ...encodeName(name2));
9792
+ importBody.push(...bytes.subarray(start, importSection.position()));
9793
+ }
9794
+ if (!importSection.done()) throw new Error("invalid wasm imports");
9795
+ }
9796
+ const functionSection = section(3);
9797
+ if (functionSection)
9798
+ for (let count = functionSection.number(); count > 0; count--)
9799
+ functionTypes.push(typeAt(functionSection.number()));
9800
+ const exportBody = [];
9801
+ const exportSection = section(7);
9802
+ if (exportSection) {
9803
+ const count = exportSection.number();
9804
+ exportBody.push(...encodeNumber2(count));
9805
+ for (let index = 0; index < count; index++) {
9806
+ const name2 = exportSection.name();
9807
+ const kind = exportSection.byte();
9808
+ const target = exportSection.number();
9809
+ const type = kind === 0 ? functionTypes[target] : void 0;
9810
+ if (kind === 0 && !type) throw new Error("invalid wasm export");
9811
+ if (type && wide(type)) {
9812
+ if (type.results.length > 1)
9813
+ throw new Error(`export ${name2} returns several values`);
9814
+ const id = thunks.length;
9815
+ const call = `(call $guest${id}${type.parameters.map(
9816
+ (value, at) => value === I64 ? ` (i64.extend_i32_u (local.get ${at}))` : ` (local.get ${at})`
9817
+ ).join("")})`;
9818
+ thunks.push(
9819
+ `(import "${GUEST}" "${WIDE}${id}" (func $guest${id}${signature(type.parameters, "param", false)}${signature(type.results, "result", false)}))`,
9820
+ `(func (export ${quoted(name2)})${signature(type.parameters, "param", true)}${signature(type.results, "result", true)} ${type.results[0] === I64 ? `(i32.wrap_i64 ${call})` : call})`
10068
9821
  );
10069
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
10070
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
10071
- // scope, the root image and its dependency closure, as in elf.
10072
- provider === 0 || callers.get(0)?.includes(provider) || !options.weakReferences.get(object2)?.has(symbol) && options.frameworkProviders.get(object2)?.has(providers[0]))))
10073
- throw new Error(
10074
- `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
10075
- );
10076
- directBindings.push({
10077
- object: object2,
10078
- symbol,
10079
- providerObject: providers[0],
10080
- providerImage: provider
10081
- });
10082
- continue;
10083
- }
10084
- result.push({ symbol, caller, provider: { kind: "image", image: provider } });
9822
+ exportBody.push(...encodeName(`${WIDE}${id}`));
9823
+ } else exportBody.push(...encodeName(name2));
9824
+ exportBody.push(kind, ...encodeNumber2(target));
10085
9825
  }
9826
+ if (!exportSection.done()) throw new Error("invalid wasm exports");
10086
9827
  }
10087
- return { bindings: result, directBindings };
9828
+ if (thunks.length === 0) return void 0;
9829
+ const imports = thunks.filter((line) => line.startsWith("(import"));
9830
+ const functions = thunks.filter((line) => !line.startsWith("(import"));
9831
+ return {
9832
+ module: withSections(
9833
+ bytes,
9834
+ layout2,
9835
+ /* @__PURE__ */ new Map([
9836
+ [2, importBody],
9837
+ [7, exportBody]
9838
+ ])
9839
+ ),
9840
+ thunks: `(module
9841
+ ${[...imports, ...functions].join("\n")}
9842
+ )
9843
+ `
9844
+ };
10088
9845
  }
10089
- function linkPrunedGuestImages(options) {
10090
- let result;
10091
- pruneSwiftWasmLink(
10092
- options.buildDirectory,
10093
- options.toolchainBin,
10094
- options.moduleRoot,
10095
- options.staticClangTargets,
10096
- void 0,
10097
- (args, rewritten, sdk) => {
10098
- if (args.some((arg) => arg === "--Map" || arg.startsWith("--Map=")))
10099
- throw new Error("guest link already has a linker map");
10100
- const framework = options.framework;
10101
- const prepared = options.prepareRuntime?.(args, rewritten, sdk);
10102
- if (prepared && options.sdkProducts !== null)
10103
- throw new Error("guest runtime products supplied twice");
10104
- const linkedArgs = prepared?.args ?? args;
10105
- const sdkProducts = prepared?.sdkProducts ?? (typeof options.sdkProducts === "function" ? options.sdkProducts(args, rewritten, sdk) : options.sdkProducts);
10106
- const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts);
10107
- let frameworkArtifacts = [];
10108
- const selectedObjects = prepared && new Set(
10109
- prepared.selected.filter((item) => item.member === null).map((item) => path16.resolve(item.artifact))
10110
- );
10111
- const selectedFramework = framework && (!prepared || framework.product.objects.some((object2) => {
10112
- const original = path16.resolve(framework.root, object2.path);
10113
- const linked = path16.resolve(rewritten.get(original) ?? original);
10114
- return selectedObjects?.has(linked) ?? false;
10115
- }));
10116
- if (framework && selectedFramework) {
10117
- const image = sdkProducts?.images.get(
10118
- frameworkRuntimeProductId(framework.product)
10119
- );
10120
- if (image === void 0)
10121
- throw new Error(
10122
- "framework objects require their declared compiler runtime image"
10123
- );
10124
- frameworkArtifacts = guestFrameworkLinkArtifacts(
10125
- framework.product,
10126
- framework.root,
10127
- linkedArgs,
10128
- rewritten,
10129
- image
10130
- );
10131
- }
10132
- if (sdkProducts) {
10133
- for (const image of guestSdkProductImages(
10134
- sdkProducts.products.map((entry) => entry.product),
10135
- sdkProducts.images
10136
- )) {
10137
- const planned = sourcePlan.images.find((entry) => entry.id === image.id);
10138
- if (!planned || planned.name !== image.name || planned.dependencies.length !== image.dependencies.length || planned.dependencies.some(
10139
- (dependency, index) => dependency !== image.dependencies[index]
10140
- ))
10141
- throw new Error(`SDK image scope differs from source product ${image.name}`);
10142
- }
10143
- }
10144
- const plan = remapGuestLinkPlan(
10145
- {
10146
- ...sourcePlan,
10147
- artifacts: [
10148
- ...sourcePlan.artifacts,
10149
- ...frameworkArtifacts,
10150
- ...sdkProducts ? guestSdkProductLinkArtifacts(
10151
- sdkProducts.products,
10152
- sdk,
10153
- linkedArgs,
10154
- sdkProducts.linkedArchives,
10155
- rewritten,
10156
- new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
10157
- prepared?.selected
10158
- ) : [],
10159
- ...prepared?.archiveArtifacts ?? []
10160
- ]
10161
- },
10162
- rewritten
10163
- );
10164
- let owners = /* @__PURE__ */ new Map();
10165
- let generatedSectionOwners = /* @__PURE__ */ new Map();
10166
- let projection = typeof options.projection === "function" ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan) : options.projection;
10167
- if (projection && prepared) {
10168
- const identities = new Map(projection.identities);
10169
- for (const [before, after] of rewritten) {
10170
- const identity = identities.get(before);
10171
- const existing = identities.get(after);
10172
- if (identity !== void 0 && existing !== void 0 && existing !== identity)
10173
- throw new Error(`rewritten guest input has conflicting identity ${after}`);
10174
- if (identity !== void 0) identities.set(after, identity);
10175
- }
10176
- projection = {
10177
- ...projection,
10178
- identities: aliasGuestLinkIdentities(identities, prepared.archives)
10179
- };
10180
- }
10181
- const selected = linkCompleteGuestImages({
10182
- plan,
10183
- args: [...linkedArgs, `--Map=${options.mapPath}`],
10184
- directory: options.linkDirectory,
10185
- wasmLd: path16.join(options.toolchainBin, "wasm-ld"),
10186
- clang: path16.join(options.toolchainBin, "clang"),
10187
- llvmAr: path16.join(options.toolchainBin, "llvm-ar"),
10188
- ledgerDataImage: options.ledgerDataImage,
10189
- projection,
10190
- resolvePlan: options.resolvePlan,
10191
- onLinkedOwners: (value) => {
10192
- owners = value;
10193
- },
10194
- onLinkedSections: (value) => {
10195
- generatedSectionOwners = value;
10196
- }
10197
- });
10198
- result = {
10199
- selected,
10200
- owners,
10201
- generatedSectionOwners,
10202
- sdk,
10203
- mapPath: options.mapPath,
10204
- generatedLedgerObject: path16.join(options.linkDirectory, "ledger.o")
10205
- };
10206
- },
10207
- options.resourceReferences
9846
+ var NARROW_MERGE_NAMES = { guest: GUEST, boundary: BOUNDARY };
9847
+ function dropBoundaryExports(bytes) {
9848
+ const layout2 = sections(bytes);
9849
+ const found = layout2.find((entry) => entry.id === 7);
9850
+ if (!found) throw new Error("merged module has no exports");
9851
+ const exportSection = reader(bytes, found.start, found.end);
9852
+ const kept = [];
9853
+ for (let count = exportSection.number(); count > 0; count--) {
9854
+ const name2 = exportSection.name();
9855
+ const kind = exportSection.byte();
9856
+ const target = exportSection.number();
9857
+ if (!name2.startsWith(WIDE) && !name2.startsWith(NARROW))
9858
+ kept.push([...encodeName(name2), kind, ...encodeNumber2(target)]);
9859
+ }
9860
+ return withSections(
9861
+ bytes,
9862
+ layout2,
9863
+ /* @__PURE__ */ new Map([[7, [...encodeNumber2(kept.length), ...kept.flat()]]])
9864
+ );
9865
+ }
9866
+
9867
+ // src/wasm-optimize.ts
9868
+ var FEATURES = [
9869
+ "memory64",
9870
+ "threads",
9871
+ "bulk-memory",
9872
+ "bulk-memory-opt",
9873
+ "call-indirect-overlong",
9874
+ "exception-handling",
9875
+ "multivalue",
9876
+ "mutable-globals",
9877
+ "nontrapping-float-to-int",
9878
+ "reference-types",
9879
+ "sign-ext"
9880
+ ];
9881
+ var KEEP_WASM_NAMES = process.env.PEACH_SWIFT_NAMES === "1";
9882
+ var LOWERING = ["--memory64-lowering", "--table64-lowering"];
9883
+ var BINARYEN_VERSION = binaryen_lock_default.version;
9884
+ var runBinaryen = promisify2(execFile2);
9885
+ var WASM_LOWER_IDENTITY = `binaryen ${BINARYEN_VERSION} narrow ${LOWERING.join(" ")} ${FEATURES.join(",")} unoptimized-names`;
9886
+ var BINARYEN_RELEASES = new Map(Object.entries(binaryen_lock_default.platforms));
9887
+ async function runWasmOpt(file, output, optimize, skipPasses, binary) {
9888
+ const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES);
9889
+ const requestedCores = Number(process.env.BINARYEN_CORES);
9890
+ const environment = { ...process.env };
9891
+ if (Number.isInteger(admittedCores) && admittedCores > 0)
9892
+ environment.BINARYEN_CORES = String(
9893
+ Number.isInteger(requestedCores) && requestedCores > 0 ? Math.min(admittedCores, requestedCores) : admittedCores
9894
+ );
9895
+ const features = FEATURES.map((feature) => `--enable-${feature}`);
9896
+ const names = optimize && !KEEP_WASM_NAMES ? [] : ["-g"];
9897
+ const narrowed = narrowWasmBoundary(readFileSync11(file));
9898
+ const merged = `${output}.narrowed`;
9899
+ if (narrowed) {
9900
+ const guest = `${output}.guest`;
9901
+ const thunks = `${output}.thunks.wat`;
9902
+ writeFileSync4(guest, narrowed.module);
9903
+ writeFileSync4(thunks, narrowed.thunks);
9904
+ await runBinaryen(
9905
+ join2(dirname(binary), "wasm-merge"),
9906
+ [
9907
+ ...features,
9908
+ ...names,
9909
+ guest,
9910
+ NARROW_MERGE_NAMES.guest,
9911
+ thunks,
9912
+ NARROW_MERGE_NAMES.boundary,
9913
+ "-o",
9914
+ merged
9915
+ ],
9916
+ { env: environment }
9917
+ );
9918
+ writeFileSync4(merged, dropBoundaryExports(readFileSync11(merged)));
9919
+ rmSync4(guest);
9920
+ rmSync4(thunks);
9921
+ }
9922
+ try {
9923
+ await runBinaryen(
9924
+ binary,
9925
+ [
9926
+ ...LOWERING,
9927
+ ...optimize ? ["-Oz"] : [],
9928
+ ...names,
9929
+ ...skipPasses.flatMap((pass) => ["--skip-pass", pass]),
9930
+ ...features,
9931
+ narrowed ? merged : file,
9932
+ "-o",
9933
+ output
9934
+ ],
9935
+ { env: environment, maxBuffer: Infinity }
9936
+ );
9937
+ } finally {
9938
+ if (narrowed) rmSync4(merged);
9939
+ }
9940
+ }
9941
+ async function installWasmOpt() {
9942
+ const platform = `${process.platform}-${process.arch}`;
9943
+ const release = BINARYEN_RELEASES.get(platform);
9944
+ if (!release) throw new Error(`no pinned Binaryen release for ${platform}`);
9945
+ const destDir = join2(rnxHomeDir(), "tools", "binaryen", BINARYEN_VERSION, platform);
9946
+ const binary = join2(destDir, "bin", "wasm-opt");
9947
+ if (!existsSync2(binary))
9948
+ await installVerifiedTarball({
9949
+ url: `https://r2.rnxsim.com/peach/binaryen/${release.sha256}/${platform}.tar.gz`,
9950
+ digest: { algorithm: "sha256", encoding: "hex", value: release.sha256 },
9951
+ destDir,
9952
+ installedMarker: "bin/wasm-opt",
9953
+ label: `Binaryen ${BINARYEN_VERSION}`
9954
+ });
9955
+ return binary;
9956
+ }
9957
+ async function lowerWasm(file, output, options) {
9958
+ await runWasmOpt(
9959
+ file,
9960
+ output,
9961
+ options.optimize,
9962
+ options.skipPasses ?? [],
9963
+ await installWasmOpt()
10208
9964
  );
10209
- if (!result) throw new Error("guest link did not receive pruned inputs");
10210
- return result;
10211
9965
  }
10212
9966
 
10213
- // src/swift-guest-source-inputs.ts
10214
- import { execFileSync as execFileSync8 } from "node:child_process";
10215
- import { createHash as createHash11 } from "node:crypto";
10216
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync11, realpathSync as realpathSync2, writeFileSync as writeFileSync4 } from "node:fs";
10217
- import path17 from "node:path";
10218
-
10219
- // src/forked-script-contract.ts
10220
- var PEACH_FORKED_SCRIPT_ENV = "PEACH_RUNS_FORKED_SCRIPTS";
10221
-
10222
- // src/swift-guest-source-inputs.ts
10223
- function clangIrLinkOptions(ir) {
10224
- const list = /^!llvm\.linker\.options = !\{([^\n]*)\}$/m.exec(ir);
10225
- if (!list) {
10226
- if (/^!llvm\.linker\.options\s*=/m.test(ir))
10227
- throw new Error("invalid clang link metadata list");
10228
- return [];
9967
+ // src/swift-guest-link.ts
9968
+ function remapGuestLinkPlan(plan, rewritten) {
9969
+ return {
9970
+ ...plan,
9971
+ artifacts: plan.artifacts.map((artifact) => ({
9972
+ ...artifact,
9973
+ path: rewritten.get(artifact.path) ?? artifact.path
9974
+ }))
9975
+ };
9976
+ }
9977
+ function guestLinkInputFiles(args) {
9978
+ const dirs = [];
9979
+ for (let i = 0; i < args.length; i++) {
9980
+ const arg = args[i];
9981
+ if (arg === "-L" || arg === "--library-path") dirs.push(args[++i]);
9982
+ else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9983
+ else if (arg.startsWith("--library-path=")) dirs.push(arg.slice(15));
10229
9984
  }
10230
- const ids = list[1].split(",").map((item) => item.trim());
10231
- if (ids.length === 1 && ids[0] === "") return [];
10232
- const result = [];
10233
- for (const id of ids) {
10234
- if (!/^!\d+$/.test(id)) throw new Error(`invalid clang link metadata ${id}`);
10235
- const node = new RegExp(`^${id} = !\\{([^\\n]*)\\}$`, "m").exec(ir);
10236
- if (!node) throw new Error(`missing clang link metadata ${id}`);
10237
- const parts = node[1].split(/,\s*(?=!")/);
10238
- for (const part of parts) {
10239
- const value = /^!"((?:[^"\\]|\\[0-9A-Fa-f]{2})*)"$/.exec(part.trim());
10240
- if (!value) throw new Error(`invalid clang link option ${part}`);
10241
- const decoded = value[1].replace(
10242
- /\\([0-9A-Fa-f]{2})/g,
10243
- (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))
10244
- );
10245
- const flag = Buffer.from(decoded, "latin1").toString("utf8");
10246
- if (!flag || flag.includes("\0")) throw new Error("invalid empty clang link option");
10247
- result.push(flag);
9985
+ const inputs = /* @__PURE__ */ new Set();
9986
+ for (let i = 0; i < args.length; i++) {
9987
+ const arg = args[i];
9988
+ if (arg === "-L" || arg === "--library-path" || arg === "-o" || arg === "--output") {
9989
+ i++;
9990
+ continue;
9991
+ }
9992
+ if (arg.startsWith("@")) throw new Error(`nested linker response file ${arg}`);
9993
+ let file;
9994
+ if (arg === "-l" || arg === "--library" || arg.startsWith("--library=") || arg.startsWith("-l") && arg.length > 2) {
9995
+ const name2 = arg === "-l" || arg === "--library" ? args[++i] : arg.startsWith("--library=") ? arg.slice(10) : arg.slice(2);
9996
+ const archive = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
9997
+ file = dirs.map((dir) => path19.join(dir, archive)).find((item) => fs9.existsSync(item));
9998
+ if (!file) throw new Error(`unresolved guest link library ${name2}`);
9999
+ } else if (!arg.startsWith("-") && fs9.existsSync(arg) && fs9.statSync(arg).isFile()) {
10000
+ const fd = fs9.openSync(arg, "r");
10001
+ const magic = Buffer.alloc(8);
10002
+ try {
10003
+ fs9.readSync(fd, magic, 0, magic.length, 0);
10004
+ } finally {
10005
+ fs9.closeSync(fd);
10006
+ }
10007
+ if (magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) || magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) || magic.toString("ascii") === "!<arch>\n" || magic.toString("ascii") === "!<thin>\n")
10008
+ file = arg;
10248
10009
  }
10010
+ if (file) inputs.add(path19.resolve(file));
10249
10011
  }
10250
- return result;
10012
+ return [...inputs];
10251
10013
  }
10252
- var CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
10253
- var PARALLEL_REPLAY = `
10254
- const { spawn } = require('node:child_process')
10255
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
10256
- let next = 0
10257
- const run = () => {
10258
- if (next >= commands.length) return Promise.resolve()
10259
- const [file, ...args] = commands[next++]
10260
- return new Promise((resolve, reject) => {
10261
- const child = spawn(file, args, { stdio: 'inherit' })
10262
- child.on('error', reject)
10263
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
10264
- }).then(run)
10014
+ function unownedGuestLinkInputs(plan, args) {
10015
+ const owned = new Set(plan.artifacts.map((artifact) => path19.resolve(artifact.path)));
10016
+ return guestLinkInputFiles(args).filter((file) => !owned.has(file));
10265
10017
  }
10266
- const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
10267
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
10268
- console.error(error.message)
10269
- process.exit(1)
10270
- })
10271
- `;
10272
- function sourceGuestClangLinkOptions(options) {
10273
- const wanted = new Set(options.objects.map((file) => path17.resolve(file)));
10274
- const commands = /* @__PURE__ */ new Map();
10275
- let tool = "";
10276
- let outputs = [];
10277
- for (const line of readFileSync11(
10278
- path17.join(options.buildDirectory, ".build", "release.yaml"),
10279
- "utf8"
10280
- ).split("\n")) {
10281
- if (line.startsWith(' "') && line.endsWith(":")) {
10282
- tool = "";
10283
- outputs = [];
10018
+ function occurrences(plan, args) {
10019
+ const dirs = [];
10020
+ for (let i = 0; i < args.length; i++) {
10021
+ const arg = args[i];
10022
+ if (arg === "-L") dirs.push(args[++i]);
10023
+ else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
10024
+ }
10025
+ const owned = new Map(
10026
+ plan.artifacts.map((artifact) => [path19.resolve(artifact.path), artifact])
10027
+ );
10028
+ if (owned.size !== plan.artifacts.length)
10029
+ throw new Error("duplicate guest link artifact");
10030
+ const found = [];
10031
+ const seen = /* @__PURE__ */ new Map();
10032
+ let lazy = false;
10033
+ let whole = false;
10034
+ for (const token of args) {
10035
+ if (token === "--start-lib") {
10036
+ lazy = true;
10284
10037
  continue;
10285
10038
  }
10286
- if (line.startsWith(" tool: ")) tool = line.slice(10).trim();
10287
- if (line.startsWith(" outputs: ")) {
10288
- const value2 = JSON.parse(line.slice(13));
10289
- if (!Array.isArray(value2) || !value2.every((item) => typeof item === "string"))
10290
- throw new Error("invalid build command outputs");
10291
- outputs = value2;
10039
+ if (token === "--end-lib") {
10040
+ lazy = false;
10041
+ continue;
10292
10042
  }
10293
- if (!line.startsWith(" args: ") || !outputs.some((file) => wanted.has(path17.resolve(file))))
10043
+ if (token === "--whole-archive") {
10044
+ whole = true;
10294
10045
  continue;
10295
- const value = JSON.parse(line.slice(10));
10296
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
10297
- throw new Error("invalid build command arguments");
10298
- for (const output of outputs) {
10299
- const file = path17.resolve(output);
10300
- if (!wanted.has(file)) continue;
10301
- if (commands.has(file)) throw new Error(`ambiguous source object producer ${file}`);
10302
- commands.set(file, { tool, args: value });
10303
10046
  }
10304
- }
10305
- const replays = [];
10306
- for (const [index, file] of [...wanted].entries()) {
10307
- const command = commands.get(file);
10308
- if (!command) throw new Error(`missing source object producer ${file}`);
10309
- if (command.tool === "shell") {
10310
- if (!command.args.length || realpathSync2(command.args[0]) !== realpathSync2(options.swiftCompiler))
10311
- throw new Error(`unsupported source object producer ${file}`);
10047
+ if (token === "--no-whole-archive") {
10048
+ whole = false;
10312
10049
  continue;
10313
10050
  }
10314
- const compiler = command.args[0] ? realpathSync2(command.args[0]) : "";
10315
- if (command.tool !== "clang" || compiler !== realpathSync2(path17.join(options.toolchainBin, "clang")) && compiler !== realpathSync2(path17.join(options.buildDirectory, CLANG_TARGET_MODULE_WRAPPER)))
10316
- throw new Error(`unsupported source object producer ${file}`);
10317
- const args = command.args.slice(1).filter((arg) => arg !== "-c");
10318
- const targetBuild = path17.relative(options.buildDirectory, file).split(path17.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
10319
- const outputDirectory = path17.join(
10320
- options.directory,
10321
- targetBuild ?? path17.basename(path17.dirname(file))
10322
- );
10323
- mkdirSync3(outputDirectory, { recursive: true });
10324
- const output = path17.join(outputDirectory, `clang-link-${index}.ll`);
10325
- for (const flag of ["-o", "-MF"]) {
10326
- const index2 = args.lastIndexOf(flag);
10327
- if (index2 < 0 || index2 + 1 >= args.length)
10328
- throw new Error(`missing clang ${flag} for ${file}`);
10329
- args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
10051
+ let filename = token;
10052
+ if (token.startsWith("-l") && token.length > 2) {
10053
+ const library = token.slice(2);
10054
+ filename = dirs.map(
10055
+ (dir) => path19.join(
10056
+ dir,
10057
+ library.startsWith(":") ? library.slice(1) : `lib${library}.a`
10058
+ )
10059
+ ).find((file) => fs9.existsSync(file)) ?? token;
10060
+ }
10061
+ const artifact = owned.get(path19.resolve(filename));
10062
+ if (artifact) {
10063
+ const prior = seen.get(artifact.path);
10064
+ if (prior) {
10065
+ if (prior.lazy !== lazy || prior.whole !== whole)
10066
+ throw new Error(
10067
+ `guest link input has conflicting occurrence modes: ${artifact.path}`
10068
+ );
10069
+ continue;
10070
+ }
10071
+ const occurrence = { artifact, token, lazy, whole };
10072
+ seen.set(artifact.path, occurrence);
10073
+ found.push(occurrence);
10330
10074
  }
10331
- replays.push({
10332
- file,
10333
- compiler: command.args[0],
10334
- args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
10335
- output
10336
- });
10337
10075
  }
10338
- const plan = path17.join(options.directory, "clang-link-replays.json");
10339
- writeFileSync4(
10340
- plan,
10341
- JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
10076
+ if (found.length !== plan.artifacts.length)
10077
+ throw new Error("guest plan does not match linker inputs");
10078
+ return found;
10079
+ }
10080
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
10081
+ const rows = whyExtract.trimEnd().split("\n");
10082
+ if (rows.shift() !== "reference extracted symbol")
10083
+ throw new Error("invalid wasm-ld extraction report");
10084
+ const extracted = new Set(
10085
+ rows.map((row) => {
10086
+ const fields = row.split(" ");
10087
+ if (fields.length !== 3) throw new Error("invalid wasm-ld extraction row");
10088
+ return fields[1];
10089
+ })
10342
10090
  );
10343
- const script = path17.join(options.directory, "clang-link-replay.cjs");
10344
- writeFileSync4(script, PARALLEL_REPLAY);
10345
- execFileSync8(process.execPath, [script], {
10346
- stdio: "inherit",
10347
- env: {
10348
- ...process.env,
10349
- [PEACH_FORKED_SCRIPT_ENV]: "1",
10350
- PEACH_CLANG_REPLAYS: plan,
10351
- PEACH_CLANG_JOBS: String(options.jobs)
10091
+ const traced = new Set(linkTrace.split("\n").filter(Boolean));
10092
+ for (const file of extracted)
10093
+ if (!traced.has(file))
10094
+ throw new Error(`extracted guest input is absent from link trace ${file}`);
10095
+ const result = [];
10096
+ for (const { artifact, lazy, whole } of occurrences(plan, args)) {
10097
+ if (artifact.kind === "object") {
10098
+ if (!lazy && !traced.has(artifact.path))
10099
+ throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
10100
+ if (traced.has(artifact.path))
10101
+ result.push({ artifact: artifact.path, member: null });
10102
+ continue;
10352
10103
  }
10353
- });
10354
- const result = /* @__PURE__ */ new Map();
10355
- for (const { file, output } of replays) {
10356
- const flags = clangIrLinkOptions(readFileSync11(output, "utf8"));
10357
- for (let index = 0; index < flags.length; index++) {
10358
- const flag = flags[index];
10359
- if (flag === "-framework" || flag === "-l" || flag === "--library") {
10360
- const name2 = flags[++index];
10361
- if (!name2 || name2.startsWith("-"))
10362
- throw new Error(`missing clang link name after ${flag}`);
10363
- } else if (!/^(-l.+|--library=.+)$/.test(flag)) {
10364
- throw new Error(`unsupported clang link option ${flag}`);
10365
- }
10104
+ const prefix = `${artifact.path}(`;
10105
+ const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
10106
+ const members = readArMembers(fs9.readFileSync(artifact.path));
10107
+ for (const member of members) {
10108
+ if (whole || names.includes(member.name))
10109
+ result.push({ artifact: artifact.path, member: member.name });
10366
10110
  }
10367
- result.set(file, flags);
10111
+ for (const name2 of names)
10112
+ if (members.filter((member) => member.name === name2).length !== 1)
10113
+ throw new Error(
10114
+ `ambiguous or unsupported archive member ${artifact.path}(${name2})`
10115
+ );
10116
+ }
10117
+ return result;
10118
+ }
10119
+ function outputPath(args) {
10120
+ let output = "";
10121
+ for (let i = 0; i < args.length; i++) {
10122
+ const arg = args[i];
10123
+ if (arg === "-o" || arg === "--output") output = args[++i];
10124
+ else if (arg.startsWith("--output=")) output = arg.slice("--output=".length);
10368
10125
  }
10369
- return result;
10126
+ if (!output) throw new Error("guest link has no output path");
10127
+ return output;
10370
10128
  }
10371
- function sourceGuestInputIdentities(graph, buildDirectory, objects) {
10372
- const producers = /* @__PURE__ */ new Map();
10373
- for (const target of graph.targets)
10374
- if (target.sourceTarget !== null)
10375
- producers.set(
10376
- target.sourceTarget,
10377
- producers.has(target.sourceTarget) ? null : target.id
10378
- );
10379
- const identities = /* @__PURE__ */ new Map();
10380
- for (const object2 of objects) {
10381
- const target = producers.get(object2.sourceTarget);
10382
- if (target === null || target === void 0)
10383
- throw new Error(`ambiguous source producer ${object2.sourceTarget}`);
10384
- if (object2.kind === "archive") {
10385
- identities.set(
10386
- object2.path,
10387
- JSON.stringify([
10388
- "source",
10389
- target,
10390
- `libraries/lib${libraryArchiveTarget(object2.path)}.a`
10391
- ])
10392
- );
10129
+ function withOutput(args, output, discovery) {
10130
+ const result = [];
10131
+ for (let i = 0; i < args.length; i++) {
10132
+ const arg = args[i];
10133
+ if (arg === "-o" || arg === "--output") {
10134
+ i++;
10393
10135
  continue;
10394
10136
  }
10395
- const relative = path17.relative(buildDirectory, object2.path).split(path17.sep);
10396
- if (!relative[0]?.endsWith(".build") || relative.length < 2)
10397
- throw new Error(`source object is outside its producer ${object2.path}`);
10398
- identities.set(object2.path, JSON.stringify(["source", target, relative.join("/")]));
10137
+ if (arg.startsWith("--output=")) continue;
10138
+ if (discovery && (arg.startsWith("--why-extract=") || arg.startsWith("--Map=")))
10139
+ continue;
10140
+ result.push(arg);
10399
10141
  }
10400
- return identities;
10142
+ result.push("-o", output);
10143
+ return result;
10401
10144
  }
10402
- function sourceGuestRuntimeLinks(options) {
10403
- const aliases = /* @__PURE__ */ new Map();
10404
- const artifacts = /* @__PURE__ */ new Map();
10405
- const frameworkAliases = /* @__PURE__ */ new Map();
10406
- const sdkAliases = /* @__PURE__ */ new Map();
10407
- for (const { product, root } of options.products) {
10408
- for (const alias of product.frameworkAliases) {
10409
- if (product.linkOwnership !== "image")
10410
- throw new Error(`framework namespace has no image owner ${product.id}`);
10411
- const previous = sdkAliases.get(alias.name);
10412
- if (previous) {
10413
- if (previous.product !== product.id || previous.moduleMap !== alias.moduleMap || previous.sha256 !== alias.moduleMapSha256)
10414
- throw new Error(`ambiguous declared framework ${alias.name}`);
10415
- continue;
10145
+ function linkGuestImages(options) {
10146
+ const { args, directory, wasmLd, clang, llvmAr } = options;
10147
+ let plan = options.plan;
10148
+ if (!plan.images.some((image) => image.id === options.ledgerDataImage))
10149
+ throw new Error(`unknown ledger data image ${options.ledgerDataImage}`);
10150
+ fs9.mkdirSync(directory, { recursive: true });
10151
+ const discovery = path19.join(directory, "discovery.wasm");
10152
+ const whyPath = path19.join(directory, "why-extract.txt");
10153
+ const mapPath = path19.join(directory, "discovery.map");
10154
+ const runLink = (name2, arguments_) => {
10155
+ const response = path19.join(directory, `${name2}.rsp`);
10156
+ const trace = path19.join(directory, `${name2}-inputs.txt`);
10157
+ fs9.writeFileSync(
10158
+ response,
10159
+ [...arguments_, "--trace"].map((argument2) => JSON.stringify(argument2)).join(" ")
10160
+ );
10161
+ const output = fs9.openSync(trace, "w");
10162
+ try {
10163
+ execFileSync7(wasmLd, [`@${response}`], { stdio: ["ignore", output, "pipe"] });
10164
+ } finally {
10165
+ fs9.closeSync(output);
10166
+ }
10167
+ return fs9.readFileSync(trace, "utf8");
10168
+ };
10169
+ let discoveryProjection;
10170
+ if (options.projection) {
10171
+ const source = path19.join(directory, "projection-discovery.c");
10172
+ discoveryProjection = path19.join(directory, "projection-discovery.o");
10173
+ fs9.writeFileSync(
10174
+ source,
10175
+ '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
10176
+ );
10177
+ execFileSync7(
10178
+ clang,
10179
+ [...options.projection.clangOptions, "-c", source, "-o", discoveryProjection],
10180
+ { stdio: "pipe" }
10181
+ );
10182
+ }
10183
+ const archives = /* @__PURE__ */ new Map();
10184
+ const memberBytes = /* @__PURE__ */ new Map();
10185
+ const prepare = (provider2) => {
10186
+ const trace = runLink("discovery", [
10187
+ ...withOutput(args, discovery, true),
10188
+ ...discoveryProjection ? [discoveryProjection] : [],
10189
+ ...provider2 ? ["--undefined=__peach_dlsym_from_image"] : [],
10190
+ `--why-extract=${whyPath}`,
10191
+ `--Map=${mapPath}`
10192
+ ]);
10193
+ const selected2 = selectedGuestLinkInputs(
10194
+ plan,
10195
+ args,
10196
+ fs9.readFileSync(whyPath, "utf8"),
10197
+ trace
10198
+ );
10199
+ if (options.resolvePlan) {
10200
+ const identity = (value) => JSON.stringify([
10201
+ value.images.map(({ id, name: name2 }) => [id, name2]),
10202
+ value.artifacts.map(
10203
+ ({
10204
+ path: file,
10205
+ kind,
10206
+ image,
10207
+ memberImages,
10208
+ memberOrigins,
10209
+ instrumentDynamicLookups
10210
+ }) => [
10211
+ file,
10212
+ kind,
10213
+ image,
10214
+ memberImages ? [...memberImages] : null,
10215
+ memberOrigins ? [...memberOrigins] : null,
10216
+ instrumentDynamicLookups
10217
+ ]
10218
+ )
10219
+ ]);
10220
+ const originalOwnership = identity(plan);
10221
+ const resolved = options.resolvePlan(selected2, plan);
10222
+ if (identity(resolved) !== originalOwnership)
10223
+ throw new Error("resolved guest scopes changed input ownership");
10224
+ plan = resolved;
10225
+ }
10226
+ const objectsByImage = /* @__PURE__ */ new Map();
10227
+ for (const image of plan.images) objectsByImage.set(image.id, []);
10228
+ const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
10229
+ for (const item of selected2) {
10230
+ const artifact = artifacts.get(item.artifact);
10231
+ const image = selectedGuestInputImage(artifact, item.member);
10232
+ let bytes;
10233
+ if (item.member === null) bytes = fs9.readFileSync(item.artifact);
10234
+ else {
10235
+ let byName = memberBytes.get(item.artifact);
10236
+ if (!byName) {
10237
+ const members = readArMembers(fs9.readFileSync(item.artifact));
10238
+ archives.set(item.artifact, members);
10239
+ byName = /* @__PURE__ */ new Map();
10240
+ for (const member of members)
10241
+ if (!byName.has(member.name)) byName.set(member.name, member.bytes);
10242
+ memberBytes.set(item.artifact, byName);
10243
+ }
10244
+ bytes = byName.get(item.member);
10416
10245
  }
10417
- const directory = path17.resolve(options.sdk.root);
10418
- const file = path17.resolve(directory, alias.moduleMap);
10419
- if (!file.startsWith(directory + path17.sep))
10420
- throw new Error(`invalid framework module map ${alias.moduleMap}`);
10421
- if (createHash11("sha256").update(readFileSync11(file)).digest("hex") !== alias.moduleMapSha256)
10422
- throw new Error(`framework module map changed ${alias.moduleMap}`);
10423
- sdkAliases.set(alias.name, {
10424
- product: product.id,
10425
- moduleMap: alias.moduleMap,
10426
- sha256: alias.moduleMapSha256
10246
+ const objects = objectsByImage.get(image);
10247
+ if (!objects) throw new Error(`unknown image ${image}`);
10248
+ objects.push({
10249
+ path: item.member === null ? item.artifact : `${item.artifact}(${item.member})`,
10250
+ bytes,
10251
+ // the actual loader delegates non-ledger lookups to libc; wrapping its
10252
+ // own dlsym call would recurse back into the loader.
10253
+ instrumentDynamicLookups: artifact.instrumentDynamicLookups && !guestWasmSymbols(bytes).defined.includes("__peach_dlsym_from_image")
10427
10254
  });
10428
- frameworkAliases.set(alias.name, { kind: "sdk", product: product.id });
10429
- }
10430
- for (const artifact of product.artifacts) {
10431
- const file = path17.resolve(root, artifact.path);
10432
- const prior = artifacts.get(file);
10433
- artifacts.set(file, prior === void 0 || prior === product.id ? product.id : null);
10434
10255
  }
10435
- for (const name2 of product.linkNames) {
10436
- const prior = aliases.get(name2);
10437
- if (prior !== void 0 && prior !== product.id)
10438
- throw new Error(`ambiguous declared runtime link name ${name2}`);
10439
- aliases.set(name2, product.id);
10256
+ const ledger2 = createGuestImageLedger({
10257
+ images: plan.images.map((image) => ({
10258
+ ...image,
10259
+ objects: objectsByImage.get(image.id)
10260
+ })),
10261
+ callers: plan.callers,
10262
+ symbols: plan.symbols,
10263
+ liveSymbols: linkedMapSymbols(fs9.readFileSync(mapPath, "utf8")),
10264
+ commandLineSymbols: commandLineSymbols(args),
10265
+ directBindings: plan.directBindings
10266
+ });
10267
+ return { selected: selected2, ledger: ledger2 };
10268
+ };
10269
+ let prepared = prepare(false);
10270
+ const provider = prepared.ledger.callerWrappers.some(
10271
+ ({ symbol }) => symbol.startsWith("__peach_dlsym_caller_")
10272
+ );
10273
+ if (provider) prepared = prepare(true);
10274
+ const { selected, ledger } = prepared;
10275
+ const replacements = /* @__PURE__ */ new Map();
10276
+ const linkedOwners = /* @__PURE__ */ new Map();
10277
+ const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]));
10278
+ for (const [index, artifact] of plan.artifacts.entries()) {
10279
+ const prefix = `${artifact.path}(`;
10280
+ if (artifact.kind === "object") {
10281
+ const object2 = ledgerObjects.get(artifact.path);
10282
+ if (!object2) continue;
10283
+ const output2 = path19.join(directory, `object-${index}.o`);
10284
+ fs9.writeFileSync(output2, object2.bytes);
10285
+ replacements.set(artifact.path, output2);
10286
+ linkedOwners.set(output2, selectedGuestInputImage(artifact, null));
10287
+ continue;
10440
10288
  }
10289
+ const members = archives.get(artifact.path);
10290
+ if (!members) continue;
10291
+ const listed = execFileSync7(llvmAr, ["t", artifact.path], { encoding: "utf8" }).trimEnd().split("\n");
10292
+ if (listed.length !== members.length || new Set(listed).size !== listed.length || members.some(
10293
+ (member, i) => listed[i] !== member.name || path19.basename(member.name) !== member.name
10294
+ ))
10295
+ throw new Error(`unsupported archive layout ${artifact.path}`);
10296
+ const memberDir = path19.join(directory, `archive-${index}`);
10297
+ fs9.mkdirSync(memberDir, { recursive: true });
10298
+ const output = path19.join(directory, `archive-${index}.a`);
10299
+ const inputs = members.map((member) => {
10300
+ const memberOutput = path19.join(memberDir, member.name);
10301
+ const rewritten = ledgerObjects.get(`${prefix}${member.name})`);
10302
+ fs9.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes);
10303
+ if (rewritten) {
10304
+ linkedOwners.set(
10305
+ `${output}(${member.name})`,
10306
+ selectedGuestInputImage(artifact, member.name)
10307
+ );
10308
+ }
10309
+ return memberOutput;
10310
+ });
10311
+ fs9.rmSync(output, { force: true });
10312
+ const response = path19.join(memberDir, "members.rsp");
10313
+ fs9.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(" "));
10314
+ execFileSync7(llvmAr, ["rcs", output, `@${response}`], { stdio: "pipe" });
10315
+ replacements.set(artifact.path, output);
10316
+ }
10317
+ const irPath = path19.join(directory, "ledger.ll");
10318
+ const ledgerObject = path19.join(directory, "ledger.o");
10319
+ fs9.writeFileSync(irPath, ledger.llvmIR);
10320
+ execFileSync7(
10321
+ clang,
10322
+ ["--target=wasm64-unknown-wasip1", "-c", irPath, "-o", ledgerObject],
10323
+ { stdio: "pipe" }
10324
+ );
10325
+ linkedOwners.set(ledgerObject, options.ledgerDataImage);
10326
+ let projectionObject;
10327
+ let projectionStorage;
10328
+ if (options.projection) {
10329
+ const projection = options.projection;
10330
+ if (!plan.images.some((image) => image.id === projection.image))
10331
+ throw new Error("guest projection has no source image");
10332
+ if (projection.images.length !== plan.images.length || projection.images.some(
10333
+ (image, index) => image.image !== index || plan.images[index]?.id !== index
10334
+ ))
10335
+ throw new Error("guest projection image order differs from link plan");
10336
+ const selectedInputs = selectedGuestManifestInputs(
10337
+ plan,
10338
+ selected,
10339
+ projection.identities
10340
+ );
10341
+ const images = projection.images.map(
10342
+ (image) => createGuestImageManifest({
10343
+ ...image,
10344
+ inputs: selectedInputs.get(image.image) ?? [],
10345
+ linkOptions: projection.linkOptions,
10346
+ regions: []
10347
+ })
10348
+ );
10349
+ const ledgerPieces = guestProjectionRegionCapacity([fs9.readFileSync(ledgerObject)], 0);
10350
+ const capacities = ledger.images.map((image) => ({
10351
+ regions: guestProjectionRegionCapacity(
10352
+ image.objects.map((object2) => object2.bytes),
10353
+ 1 + ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length + (image.id === options.ledgerDataImage ? ledgerPieces : 0) + (image.id === projection.image ? images.length + 2 : 0)
10354
+ ),
10355
+ memoryProtection: projection.memoryProtection,
10356
+ tableProtection: projection.tableProtection
10357
+ }));
10358
+ projectionStorage = reserveGuestProjectionStorage(images, capacities);
10359
+ const projectionSource = path19.join(directory, "projection.c");
10360
+ projectionObject = path19.join(directory, "projection.o");
10361
+ fs9.writeFileSync(projectionSource, projectionStorage.source);
10362
+ execFileSync7(
10363
+ clang,
10364
+ [...projection.clangOptions, "-c", projectionSource, "-o", projectionObject],
10365
+ {
10366
+ stdio: "pipe"
10367
+ }
10368
+ );
10369
+ linkedOwners.set(projectionObject, projection.image);
10441
10370
  }
10442
- const frameworkId = frameworkRuntimeProductId(options.framework.product);
10443
- const owners = options.products.filter(({ product }) => product.id === frameworkId);
10444
- if (owners.length !== 1 || owners[0].product.linkOwnership !== "image" || path17.resolve(owners[0].root) !== path17.resolve(options.framework.root))
10445
- throw new Error(`missing or ambiguous packaged image ${frameworkId}`);
10446
- const targets = new Map(
10447
- options.framework.product.targets.map((target) => [target.name, target])
10371
+ const byToken = new Map(
10372
+ occurrences(plan, args).map(({ artifact, token }) => [
10373
+ token,
10374
+ replacements.get(artifact.path)
10375
+ ])
10448
10376
  );
10449
- if (targets.size !== options.framework.product.targets.length)
10450
- throw new Error("ambiguous packaged framework target");
10451
- const objectTargets = new Set(
10452
- options.framework.product.objects.map((object2) => object2.target)
10377
+ const placed = /* @__PURE__ */ new Set();
10378
+ const finalArgs = args.map((arg) => byToken.get(arg) ?? arg).filter((arg) => {
10379
+ if (!arg.endsWith(".o") && !arg.endsWith(".a")) return true;
10380
+ if (placed.has(arg)) return false;
10381
+ placed.add(arg);
10382
+ return true;
10383
+ });
10384
+ const finalOutput = path19.join(directory, "final.wasm");
10385
+ const finalWhy = path19.join(directory, "final-why-extract.txt");
10386
+ const finalTrace = runLink("final", [
10387
+ ...withOutput(finalArgs, finalOutput, false),
10388
+ ledgerObject,
10389
+ ...projectionObject ? [projectionObject] : [],
10390
+ ...provider ? ["--undefined=__peach_dlsym_from_image"] : [],
10391
+ `--why-extract=${finalWhy}`
10392
+ ]);
10393
+ const finalSelection = selectedGuestLinkInputs(
10394
+ remapGuestLinkPlan(plan, replacements),
10395
+ finalArgs,
10396
+ fs9.readFileSync(finalWhy, "utf8"),
10397
+ finalTrace
10453
10398
  );
10454
- const closure = (names) => {
10455
- const linked = /* @__PURE__ */ new Set();
10456
- const visit = (name2) => {
10457
- if (linked.has(name2)) return;
10458
- const target = targets.get(name2);
10459
- if (!target) throw new Error(`unknown packaged framework target ${name2}`);
10460
- linked.add(name2);
10461
- for (const dependency of target.dependencies) visit(dependency);
10462
- };
10463
- for (const name2 of names) visit(name2);
10464
- return [...linked];
10465
- };
10466
- for (const alias of options.framework.product.frameworkAliases) {
10467
- if (frameworkAliases.has(alias.name))
10468
- throw new Error(`ambiguous declared framework ${alias.name}`);
10469
- if (alias.wasmSdkId !== options.sdk.wasmSdkId || alias.wasmSdkChecksum !== options.sdk.wasmSdkChecksum)
10470
- throw new Error(`framework SDK identity differs for ${alias.name}`);
10471
- if (!alias.targets.length || alias.targets.some((target) => !targets.has(target) || !objectTargets.has(target)))
10472
- throw new Error(`framework target ownership differs for ${alias.name}`);
10473
- const root = path17.resolve(options.framework.root);
10474
- const map = path17.resolve(root, alias.moduleMap);
10475
- if (!map.startsWith(root + path17.sep))
10476
- throw new Error(`invalid framework module map ${alias.moduleMap}`);
10477
- if (createHash11("sha256").update(readFileSync11(map)).digest("hex") !== alias.moduleMapSha256)
10478
- throw new Error(`framework module map changed ${alias.moduleMap}`);
10479
- frameworkAliases.set(alias.name, { kind: "package", targets: closure(alias.targets) });
10480
- }
10481
- for (const name2 of objectTargets)
10482
- if (!frameworkAliases.has(name2) && targets.has(name2))
10483
- frameworkAliases.set(name2, { kind: "package", targets: closure([name2]) });
10484
- const result = /* @__PURE__ */ new Map();
10485
- const frameworkRequests = /* @__PURE__ */ new Map();
10486
- for (const image of options.images) {
10487
- if (result.has(image.id)) throw new Error(`duplicate source image ${image.id}`);
10488
- const response = path17.join(options.directory, `image-${image.id}-autolink.rsp`);
10489
- writeFileSync4(
10490
- response,
10491
- image.objects.map((file) => JSON.stringify(file)).join("\n") + "\n"
10399
+ const original = new Map([...replacements].map(([before2, after2]) => [after2, before2]));
10400
+ const key = (item) => JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member]);
10401
+ const before = new Set(selected.map(key));
10402
+ const after = new Set(finalSelection.map(key));
10403
+ const changed = [...before].filter((item) => !after.has(item));
10404
+ changed.push(...[...after].filter((item) => !before.has(item)));
10405
+ if (changed.length)
10406
+ throw new Error(
10407
+ `guest link selected different inputs after rewriting:
10408
+ ${changed.join("\n")}`
10492
10409
  );
10493
- const autolink = image.objects.length ? execFileSync8(
10494
- path17.join(options.toolchainBin, "swift-autolink-extract"),
10495
- [`@${response}`, "-o", "-"],
10496
- { encoding: "utf8" }
10497
- ).split("\n").map((line) => line.trim()).filter((line) => line.length > 0) : [];
10498
- const links = [];
10499
- const requests = [];
10500
- const optionGroups = [
10501
- { object: null, flags: image.linkerFlags, autoLinked: false },
10502
- { object: null, flags: autolink, autoLinked: true },
10503
- ...image.clangLinkOptions.map((options2) => ({ ...options2, autoLinked: true }))
10504
- ];
10505
- for (const { object: object2, flags, autoLinked } of optionGroups) {
10506
- for (let index = 0; index < flags.length; index++) {
10507
- const flag = flags[index];
10508
- const artifact = artifacts.get(flag);
10509
- if (artifact === null)
10510
- throw new Error(`ambiguous declared runtime artifact ${flag}`);
10511
- if (artifact !== void 0) {
10512
- if (!links.includes(artifact)) links.push(artifact);
10513
- continue;
10514
- }
10515
- if (path17.isAbsolute(flag) && flag.endsWith(".a"))
10516
- throw new Error(
10517
- `source image ${image.id} has unresolved runtime artifact ${flag}`
10518
- );
10519
- if (flag === "-framework") {
10520
- const name3 = flags[++index];
10521
- const provider = name3 && frameworkAliases.get(name3);
10522
- if (!provider && name3 && autoLinked) continue;
10523
- if (!provider)
10524
- throw new Error(
10525
- `source image ${image.id} has unresolved framework linkage ${name3}`
10526
- );
10527
- requests.push({ object: object2, provider });
10528
- continue;
10529
- }
10530
- if (flag.startsWith("-weak") || flag.startsWith("-reexport") || flag.startsWith("-upward") || flag.startsWith("-lazy") || flag.startsWith("-Wl,"))
10531
- throw new Error(
10532
- `source image ${image.id} has unsupported runtime scope flag ${flag}`
10533
- );
10534
- const name2 = flag === "-l" || flag === "--library" ? flags[++index] : flag.startsWith("-l") ? flag.slice(2) : flag.startsWith("--library=") ? flag.slice("--library=".length) : null;
10535
- if (name2 === null) continue;
10536
- const product = name2 === void 0 ? void 0 : aliases.get(name2);
10537
- if (product === void 0)
10538
- throw new Error(`source image ${image.id} has unresolved runtime link ${name2}`);
10539
- if (!links.includes(product)) links.push(product);
10540
- }
10541
- }
10542
- result.set(image.id, links);
10543
- frameworkRequests.set(image.id, requests);
10410
+ fs9.renameSync(finalOutput, outputPath(args));
10411
+ if (KEEP_WASM_NAMES)
10412
+ fs9.writeFileSync(
10413
+ outputPath(args),
10414
+ nameGuestImageAliases(fs9.readFileSync(outputPath(args)), plan.symbols)
10415
+ );
10416
+ if (projectionStorage && projectionObject)
10417
+ options.projection.onReserved(projectionStorage, projectionObject);
10418
+ options.onLinkedOwners?.(linkedOwners);
10419
+ options.onLinkedSections?.(
10420
+ new Map(
10421
+ ledger.callerWrappers.map(({ symbol, image }) => [
10422
+ `${ledgerObject}:(${symbol})`,
10423
+ image
10424
+ ])
10425
+ )
10426
+ );
10427
+ return selected;
10428
+ }
10429
+ function linkedMapSymbols(map) {
10430
+ const names = /* @__PURE__ */ new Set();
10431
+ for (const match of map.matchAll(/^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/gm))
10432
+ names.add(match[1]);
10433
+ return names;
10434
+ }
10435
+ function commandLineSymbols(args) {
10436
+ const names = [];
10437
+ for (const [i, arg] of args.entries()) {
10438
+ if (arg === "--entry" || arg === "-e" || arg === "-u") names.push(args[i + 1]);
10439
+ else
10440
+ for (const flag of [
10441
+ "--entry=",
10442
+ "--undefined=",
10443
+ "--export=",
10444
+ "--export-if-defined="
10445
+ ])
10446
+ if (arg.startsWith(flag)) names.push(arg.slice(flag.length));
10544
10447
  }
10545
- return { links: result, frameworkRequests };
10448
+ return names;
10546
10449
  }
10547
- function logicalGuestLinkOptions(args, identities, roots) {
10548
- const orderedRoots = [...roots].sort(
10549
- (left, right) => right.path.length - left.path.length
10450
+ function normalizedGuestLinkArgs(input) {
10451
+ const args = [];
10452
+ for (let i = 0; i < input.length; i++) {
10453
+ const arg = input[i];
10454
+ if (arg === "-l" || arg === "--library") args.push(`-l${input[++i]}`);
10455
+ else if (arg === "-L" || arg === "--library-path") args.push(`-L${input[++i]}`);
10456
+ else if (arg.startsWith("--library=")) args.push(`-l${arg.slice(10)}`);
10457
+ else if (arg.startsWith("--library-path=")) args.push(`-L${arg.slice(15)}`);
10458
+ else args.push(arg);
10459
+ }
10460
+ return args;
10461
+ }
10462
+ function aliasGuestLinkArguments(input, archives) {
10463
+ const args = normalizedGuestLinkArgs(input);
10464
+ const directories = args.filter((arg) => arg.startsWith("-L")).map((arg) => arg.slice(2));
10465
+ const aliases = new Map(
10466
+ archives.map((archive) => [path19.resolve(archive.source), archive.archive])
10550
10467
  );
10551
- const logicalPath = (file) => {
10552
- const direct = identities.get(file);
10553
- if (direct !== void 0) return direct;
10554
- if (/\.(?:o|obj|a)$/.test(file))
10555
- throw new Error(`link input has no logical identity ${file}`);
10556
- for (const root of orderedRoots) {
10557
- const relative = path17.relative(root.path, file);
10558
- if (relative !== ".." && !relative.startsWith(`..${path17.sep}`) && !path17.isAbsolute(relative))
10559
- return `${root.identity}/${relative.split(path17.sep).join("/")}`;
10560
- }
10561
- throw new Error(`link option has no logical path identity ${file}`);
10562
- };
10563
- const output = [];
10564
- for (let index = 0; index < args.length; index++) {
10565
- const arg = args[index];
10566
- if (arg === "-o" || arg === "--output" || arg === "--Map") {
10567
- index++;
10568
- continue;
10569
- }
10570
- if (arg.startsWith("--output=") || arg.startsWith("--Map=")) continue;
10571
- if (arg === "-L" || arg === "--library-path") {
10572
- output.push(arg, logicalPath(args[++index]));
10573
- continue;
10468
+ if (aliases.size !== archives.length)
10469
+ throw new Error("duplicate original guest archive");
10470
+ const used = /* @__PURE__ */ new Set();
10471
+ const result = args.map((arg) => {
10472
+ let file = arg;
10473
+ if (arg.startsWith("-l") && arg.length > 2) {
10474
+ const name2 = arg.slice(2);
10475
+ const library = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
10476
+ file = directories.map((directory) => path19.join(directory, library)).find((candidate) => fs9.existsSync(candidate)) ?? arg;
10574
10477
  }
10575
- if (arg.startsWith("-L")) output.push(`-L${logicalPath(arg.slice(2))}`);
10576
- else if (arg.startsWith("--library-path="))
10577
- output.push(`--library-path=${logicalPath(arg.slice("--library-path=".length))}`);
10578
- else if (path17.isAbsolute(arg)) output.push(logicalPath(arg));
10579
- else if (/^[^=]+=\//.test(arg)) {
10580
- const equals = arg.indexOf("=");
10581
- output.push(arg.slice(0, equals + 1) + logicalPath(arg.slice(equals + 1)));
10582
- } else output.push(identities.get(arg) ?? arg);
10583
- }
10584
- return output;
10478
+ if (file.startsWith("-")) return arg;
10479
+ const source = path19.resolve(file);
10480
+ const alias = aliases.get(source);
10481
+ if (alias === void 0) return arg;
10482
+ used.add(source);
10483
+ return alias;
10484
+ });
10485
+ if (used.size !== aliases.size)
10486
+ throw new Error("aliased guest archive is not a link input");
10487
+ return result;
10585
10488
  }
10586
-
10587
- // src/wasm-optimize.ts
10588
- import { execFile as execFile2 } from "node:child_process";
10589
- import { existsSync as existsSync2, readFileSync as readFileSync12, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
10590
- import { dirname, join as join2 } from "node:path";
10591
- import { promisify as promisify2 } from "node:util";
10592
-
10593
- // ../contrast-runtime-delivery/src/index.ts
10594
- import { spawn as spawn3 } from "node:child_process";
10595
- import crypto from "node:crypto";
10596
- import fs8 from "node:fs";
10597
- import os2 from "node:os";
10598
- import path19 from "node:path";
10599
- import { pipeline as pipeline2 } from "node:stream/promises";
10600
- import zlib2 from "node:zlib";
10601
-
10602
- // ../contrast-runtime-delivery/src/product.ts
10603
- import fs7 from "node:fs";
10604
- import path18 from "node:path";
10605
-
10606
- // ../contrast-runtime-delivery/src/index.ts
10607
- async function installVerifiedTarball(tarball) {
10608
- const { destDir, installedMarker, signal } = tarball;
10609
- fs8.mkdirSync(path19.dirname(destDir), { recursive: true });
10610
- const presentAtStart = fs8.existsSync(path19.join(destDir, installedMarker));
10611
- const lock = `${destDir}.lock`;
10612
- for (; ; ) {
10613
- signal?.throwIfAborted();
10489
+ function linkCompleteGuestImages(options) {
10490
+ const args = normalizedGuestLinkArgs(options.args);
10491
+ const unowned = unownedGuestLinkInputs(options.plan, args);
10492
+ const candidates = unowned.map((file) => {
10493
+ const descriptor = fs9.openSync(file, "r");
10494
+ const magic = Buffer.alloc(8);
10614
10495
  try {
10615
- fs8.writeFileSync(lock, String(process.pid), { flag: "wx" });
10616
- break;
10617
- } catch (err) {
10618
- if (!isErrnoCode(err, "EEXIST")) throw err;
10619
- if (lockOwnerGone(lock)) fs8.rmSync(lock, { force: true });
10620
- else await new Promise((resolve) => setTimeout(resolve, 250));
10496
+ fs9.readSync(descriptor, magic, 0, magic.length, 0);
10497
+ } finally {
10498
+ fs9.closeSync(descriptor);
10621
10499
  }
10622
- }
10623
- try {
10624
- if (!presentAtStart && fs8.existsSync(path19.join(destDir, installedMarker))) {
10625
- await tarball.verify?.(destDir);
10626
- return;
10500
+ return {
10501
+ path: file,
10502
+ kind: magic.toString("ascii") === "!<arch>\n" ? "archive" : "object",
10503
+ image: null,
10504
+ instrumentDynamicLookups: false
10505
+ };
10506
+ });
10507
+ return linkGuestImages({
10508
+ ...options,
10509
+ args,
10510
+ plan: { ...options.plan, artifacts: [...options.plan.artifacts, ...candidates] }
10511
+ });
10512
+ }
10513
+ function discoverGuestLinkInputs(options) {
10514
+ const args = normalizedGuestLinkArgs(options.args);
10515
+ const artifacts = guestLinkInputFiles(args).map((file) => {
10516
+ const descriptor = fs9.openSync(file, "r");
10517
+ const magic = Buffer.alloc(8);
10518
+ try {
10519
+ fs9.readSync(descriptor, magic, 0, magic.length, 0);
10520
+ } finally {
10521
+ fs9.closeSync(descriptor);
10627
10522
  }
10628
- await installVerifiedTarballLocked(tarball, presentAtStart);
10523
+ const kind = magic.toString("ascii") === "!<arch>\n" ? "archive" : "object";
10524
+ return { path: file, kind, image: 0, instrumentDynamicLookups: false };
10525
+ });
10526
+ const plan = { images: [], callers: [], artifacts, symbols: [] };
10527
+ fs9.mkdirSync(options.directory, { recursive: true });
10528
+ const why = path19.join(options.directory, "preselection-why.txt");
10529
+ const response = path19.join(options.directory, "preselection.rsp");
10530
+ const output = path19.join(options.directory, "preselection.wasm");
10531
+ const flags = [
10532
+ ...withOutput(args, output, true),
10533
+ ...options.objects,
10534
+ // the loader runtime backs every image's lookup wrappers, so it belongs to
10535
+ // the selection that assigns member owners.
10536
+ "--undefined=__peach_dlsym_from_image",
10537
+ `--why-extract=${why}`,
10538
+ "--trace"
10539
+ ];
10540
+ fs9.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(" "));
10541
+ const trace = path19.join(options.directory, "preselection-inputs.txt");
10542
+ const traceOutput = fs9.openSync(trace, "w");
10543
+ try {
10544
+ execFileSync7(options.wasmLd, [`@${response}`], {
10545
+ stdio: ["ignore", traceOutput, "pipe"]
10546
+ });
10629
10547
  } finally {
10630
- fs8.rmSync(lock, { force: true });
10548
+ fs9.closeSync(traceOutput);
10631
10549
  }
10550
+ return selectedGuestLinkInputs(
10551
+ plan,
10552
+ args,
10553
+ fs9.readFileSync(why, "utf8"),
10554
+ fs9.readFileSync(trace, "utf8")
10555
+ );
10632
10556
  }
10633
- function lockOwnerGone(lock) {
10634
- try {
10635
- process.kill(Number(fs8.readFileSync(lock, "utf8")), 0);
10636
- return false;
10637
- } catch (err) {
10638
- return !isErrnoCode(err, "EPERM", "ENOENT");
10557
+ function prepareGuestRuntimeInputs(options) {
10558
+ const originals = new Map(
10559
+ [...options.rewritten].map(([before, after]) => [
10560
+ path19.resolve(after),
10561
+ path19.resolve(before)
10562
+ ])
10563
+ );
10564
+ if (originals.size !== options.rewritten.size)
10565
+ throw new Error("ambiguous rewritten runtime input");
10566
+ const recordedArchives = new Set(
10567
+ options.products.flatMap(
10568
+ ({ product, root }) => product.artifacts.flatMap(
10569
+ (artifact) => artifact.kind === "archive" ? [path19.resolve(root, artifact.path)] : []
10570
+ )
10571
+ )
10572
+ );
10573
+ const archives = [];
10574
+ for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
10575
+ const original = originals.get(file) ?? file;
10576
+ if (!recordedArchives.has(original)) continue;
10577
+ const members = readArMembers(fs9.readFileSync(file));
10578
+ if (new Set(members.map((member) => member.name)).size === members.length) continue;
10579
+ archives.push(
10580
+ aliasGuestArchive({
10581
+ archive: file,
10582
+ directory: path19.join(options.directory, `archive-${archives.length}`),
10583
+ llvmAr: options.llvmAr
10584
+ })
10585
+ );
10639
10586
  }
10640
- }
10641
- async function installVerifiedTarballLocked(tarball, presentAtStart) {
10642
- const { url, digest, destDir, installedMarker, label, signal } = tarball;
10643
- signal?.throwIfAborted();
10644
- const downloadDir = fs8.mkdtempSync(path19.join(os2.tmpdir(), "runtime-delivery-download-"));
10645
- const archivePath = path19.join(downloadDir, "archive");
10646
- const tmpDir = fs8.mkdtempSync(
10647
- path19.join(path19.dirname(destDir), `.installing-${path19.basename(destDir)}-`)
10587
+ const args = aliasGuestLinkArguments(options.args, archives);
10588
+ const selected = discoverGuestLinkInputs({
10589
+ args,
10590
+ directory: options.directory,
10591
+ wasmLd: options.wasmLd,
10592
+ objects: options.discoveryObjects
10593
+ });
10594
+ const closure = guestRuntimeProductsForInputs({
10595
+ products: options.products,
10596
+ selected: originalGuestArchiveSelections(selected, archives),
10597
+ rewritten: options.rewritten,
10598
+ sdk: options.sdk,
10599
+ firstImage: options.firstImage,
10600
+ containingImage: options.containingImage,
10601
+ framework: options.framework
10602
+ });
10603
+ const aliasSources = new Set(
10604
+ archives.map(
10605
+ (archive) => originals.get(path19.resolve(archive.source)) ?? path19.resolve(archive.source)
10606
+ )
10648
10607
  );
10649
- try {
10650
- for (let attempt = 1; ; attempt++) {
10651
- await downloadToFile(url, archivePath, signal);
10652
- const actual = await digestFile(
10653
- archivePath,
10654
- digest.algorithm,
10655
- digest.encoding,
10656
- signal
10657
- );
10658
- if (actual === digest.value) break;
10659
- if (attempt >= 2) {
10660
- throw new Error(
10661
- `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
10608
+ const sdkProducts = {
10609
+ products: options.products,
10610
+ images: closure.images,
10611
+ containingImages: closure.containingImages,
10612
+ linkedArchives: closure.linkedArchives.filter(
10613
+ (archive) => !aliasSources.has(path19.resolve(archive))
10614
+ )
10615
+ };
10616
+ const archiveArtifacts = guestAliasedSdkArchiveArtifacts({
10617
+ products: options.products,
10618
+ archives,
10619
+ selected,
10620
+ rewritten: options.rewritten,
10621
+ images: new Map([...closure.images, ...closure.containingImages])
10622
+ });
10623
+ return { args, selected, archives, sdkProducts, archiveArtifacts };
10624
+ }
10625
+ function selectedGuestSymbolInputs(plan, selected) {
10626
+ const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
10627
+ const archives = /* @__PURE__ */ new Map();
10628
+ const symbols = /* @__PURE__ */ new Set();
10629
+ const hostImports = /* @__PURE__ */ new Set();
10630
+ const tags = /* @__PURE__ */ new Set();
10631
+ const definitions = /* @__PURE__ */ new Set();
10632
+ const owners = /* @__PURE__ */ new Map();
10633
+ const weakReferences = /* @__PURE__ */ new Map();
10634
+ const weakDefinitions = /* @__PURE__ */ new Map();
10635
+ const definitionObjects = /* @__PURE__ */ new Map();
10636
+ for (const item of selected) {
10637
+ const artifact = artifacts.get(item.artifact);
10638
+ if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
10639
+ let bytes;
10640
+ let name2 = item.artifact;
10641
+ if (item.member === null) bytes = fs9.readFileSync(item.artifact);
10642
+ else {
10643
+ let members = archives.get(item.artifact);
10644
+ if (!members) {
10645
+ members = Map.groupBy(
10646
+ readArMembers(fs9.readFileSync(item.artifact)),
10647
+ (member) => member.name
10662
10648
  );
10649
+ archives.set(item.artifact, members);
10663
10650
  }
10651
+ const matching = members.get(item.member) ?? [];
10652
+ if (matching.length !== 1)
10653
+ throw new Error(
10654
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
10655
+ );
10656
+ bytes = matching[0].bytes;
10657
+ name2 += `(${item.member})`;
10664
10658
  }
10665
- const { pathname } = new URL(url);
10666
- if (pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir, signal);
10667
- else
10668
- await extractTarball(
10669
- archivePath,
10670
- pathname.endsWith(".tar.zst"),
10671
- tmpDir,
10672
- tarball.stripComponents ?? 0,
10673
- signal
10659
+ if (owners.has(name2)) throw new Error(`duplicate selected symbol input ${name2}`);
10660
+ owners.set(name2, selectedGuestInputImage(artifact, item.member));
10661
+ const names = guestWasmSymbols(bytes);
10662
+ weakReferences.set(name2, new Set(names.weakUndefined));
10663
+ weakDefinitions.set(name2, new Set(names.weakDefined));
10664
+ for (const symbol of names.undefined) symbols.add(symbol);
10665
+ for (const symbol of names.hostImports) hostImports.add(symbol);
10666
+ for (const symbol of names.tags) tags.add(symbol);
10667
+ for (const symbol of names.defined) {
10668
+ definitions.add(symbol);
10669
+ const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10670
+ objects.add(name2);
10671
+ definitionObjects.set(symbol, objects);
10672
+ }
10673
+ }
10674
+ return {
10675
+ symbols: [...symbols].filter((symbol) => !tags.has(symbol)),
10676
+ definitions: [...definitions].filter((symbol) => !tags.has(symbol)),
10677
+ hostImports,
10678
+ owners,
10679
+ weakReferences,
10680
+ weakDefinitions,
10681
+ definitionObjects
10682
+ };
10683
+ }
10684
+ function verifyGuestSymbolScopes(options) {
10685
+ const symbols = [...new Set(options.symbols)];
10686
+ const requested = new Set(symbols);
10687
+ if (symbols.some((symbol) => !symbol || symbol.includes("\0") || symbol.includes("\n")))
10688
+ throw new Error("invalid traced guest symbol");
10689
+ if (!symbols.length) return { bindings: [], directBindings: [] };
10690
+ fs9.mkdirSync(options.directory, { recursive: true });
10691
+ const response = path19.join(options.directory, "scope-trace.rsp");
10692
+ const output = path19.join(options.directory, "scope-trace.wasm");
10693
+ const args = [
10694
+ ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
10695
+ ...options.objects,
10696
+ ...symbols.map((symbol) => `--trace-symbol=${symbol}`)
10697
+ ];
10698
+ fs9.writeFileSync(response, args.map((arg) => JSON.stringify(arg)).join(" "));
10699
+ const tracePath = path19.join(options.directory, "scope-trace.txt");
10700
+ const traceOutput = fs9.openSync(tracePath, "w");
10701
+ try {
10702
+ execFileSync7(options.wasmLd, [`@${response}`], {
10703
+ stdio: ["ignore", traceOutput, "pipe"]
10704
+ });
10705
+ } finally {
10706
+ fs9.closeSync(traceOutput);
10707
+ }
10708
+ const records = /* @__PURE__ */ new Map();
10709
+ const consume = (line) => {
10710
+ const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
10711
+ if (!match) return;
10712
+ const [, object2, kind, symbol] = match;
10713
+ if (!requested.has(symbol)) return;
10714
+ if (options.hostImports.has(symbol)) return;
10715
+ const record = records.get(symbol) ?? {
10716
+ references: /* @__PURE__ */ new Map(),
10717
+ providers: /* @__PURE__ */ new Map(),
10718
+ physicalModule: false
10719
+ };
10720
+ if (object2 === "<internal>") {
10721
+ if (kind === "definition of") record.physicalModule = true;
10722
+ } else {
10723
+ const image = options.owners.get(object2);
10724
+ if (image === void 0)
10725
+ throw new Error(`traced guest object has no owner ${object2}`);
10726
+ (kind === "reference to" ? record.references : record.providers).set(
10727
+ object2,
10728
+ image
10674
10729
  );
10675
- signal?.throwIfAborted();
10676
- if (!fs8.existsSync(path19.join(tmpDir, installedMarker))) {
10677
- throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
10678
10730
  }
10679
- await tarball.verify?.(tmpDir);
10680
- signal?.throwIfAborted();
10681
- try {
10682
- fs8.renameSync(tmpDir, destDir);
10683
- } catch (err) {
10684
- if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
10685
- if (!presentAtStart && fs8.existsSync(path19.join(destDir, installedMarker))) {
10686
- await tarball.verify?.(destDir);
10687
- return;
10688
- }
10689
- const aside = `${tmpDir}-replaced`;
10690
- try {
10691
- fs8.renameSync(destDir, aside);
10692
- } catch (moveErr) {
10693
- if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
10694
- }
10695
- try {
10696
- fs8.renameSync(tmpDir, destDir);
10697
- } catch (landErr) {
10698
- if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !fs8.existsSync(path19.join(destDir, installedMarker))) {
10699
- throw landErr;
10700
- }
10701
- await tarball.verify?.(destDir);
10702
- } finally {
10703
- fs8.rmSync(aside, { recursive: true, force: true });
10731
+ records.set(symbol, record);
10732
+ };
10733
+ const traceInput = fs9.openSync(tracePath, "r");
10734
+ try {
10735
+ const decoder = new StringDecoder("utf8");
10736
+ const buffer = Buffer.allocUnsafe(64 * 1024);
10737
+ let pending = "";
10738
+ let count;
10739
+ while ((count = fs9.readSync(traceInput, buffer, 0, buffer.length, null)) > 0) {
10740
+ pending += decoder.write(buffer.subarray(0, count));
10741
+ let end;
10742
+ while ((end = pending.indexOf("\n")) !== -1) {
10743
+ consume(pending.slice(0, end));
10744
+ pending = pending.slice(end + 1);
10704
10745
  }
10705
10746
  }
10747
+ consume(pending + decoder.end());
10706
10748
  } finally {
10707
- fs8.rmSync(tmpDir, { recursive: true, force: true });
10708
- fs8.rmSync(downloadDir, { recursive: true, force: true });
10709
- }
10710
- }
10711
- function isErrnoCode(err, ...codes) {
10712
- return err instanceof Error && "code" in err && codes.includes(String(err.code));
10713
- }
10714
- var DownloadHttpError = class extends Error {
10715
- constructor(status, statusText, url) {
10716
- super(`download failed: ${status} ${statusText} (${url})`);
10717
- __publicField(this, "retryable");
10718
- this.retryable = status < 400 || status >= 500 || status === 408 || status === 429;
10749
+ fs9.closeSync(traceInput);
10719
10750
  }
10720
- };
10721
- async function waitRetryDelay(ms, signal) {
10722
- signal?.throwIfAborted();
10723
- await new Promise((resolve, reject) => {
10724
- const onAbort = () => {
10725
- clearTimeout(timer);
10726
- const reason = signal?.reason;
10727
- reject(
10728
- reason instanceof Error ? reason : new Error("Download canceled", { cause: reason })
10729
- );
10730
- };
10731
- const timer = setTimeout(() => {
10732
- signal?.removeEventListener("abort", onAbort);
10733
- resolve();
10734
- }, ms);
10735
- signal?.addEventListener("abort", onAbort, { once: true });
10736
- });
10737
- }
10738
- async function downloadToFile(url, destPath, signal) {
10739
- fs8.mkdirSync(path19.dirname(destPath), { recursive: true });
10740
- const tmp = `${destPath}.partial`;
10741
- for (let attempt = 1; attempt <= 4; attempt++) {
10742
- signal?.throwIfAborted();
10743
- let reader2;
10744
- let handle;
10745
- let completed = false;
10746
- try {
10747
- const res = await fetch(url, { signal });
10748
- if (!res.ok || !res.body) {
10749
- throw new DownloadHttpError(res.status, res.statusText, url);
10751
+ const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]));
10752
+ const result = [];
10753
+ const directBindings = [];
10754
+ for (const symbol of symbols) {
10755
+ const record = records.get(symbol);
10756
+ if (!record || !record.references.size) continue;
10757
+ if (!record.providers.size && options.hostImports.has(symbol)) continue;
10758
+ const startupReferences = [...record.references].filter(
10759
+ ([object2]) => options.startupObjects.has(object2) && options.weakReferences.get(object2)?.has(symbol)
10760
+ );
10761
+ const otherReferences = [...record.references].filter(
10762
+ ([object2]) => !startupReferences.some(([startup]) => startup === object2)
10763
+ );
10764
+ for (const [, caller] of startupReferences)
10765
+ if (!callers.has(caller))
10766
+ throw new Error(`guest image has no caller scope ${caller}`);
10767
+ if (startupReferences.length && !record.physicalModule) {
10768
+ const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10769
+ if (candidates.size > 1 || record.providers.size > 1)
10770
+ throw new Error(`ambiguous startup provider ${symbol}`);
10771
+ if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object2) => !candidates.has(object2)))
10772
+ throw new Error(`unproven startup provider ${symbol}`);
10773
+ if (record.providers.size === 1) {
10774
+ const [providerObject, providerImage] = [...record.providers][0];
10775
+ if (options.weakDefinitions.get(providerObject)?.has(symbol))
10776
+ throw new Error(`weak startup provider ${symbol}`);
10777
+ for (const [object2] of startupReferences)
10778
+ directBindings.push({ object: object2, symbol, providerObject, providerImage });
10750
10779
  }
10751
- reader2 = res.body.getReader();
10752
- handle = await fs8.promises.open(tmp, "w");
10753
- let written = 0;
10754
- for (; ; ) {
10755
- signal?.throwIfAborted();
10756
- const { done, value } = await reader2.read();
10757
- if (done) break;
10758
- let offset = 0;
10759
- while (offset < value.byteLength) {
10760
- const { bytesWritten } = await handle.write(
10761
- value,
10762
- offset,
10763
- value.byteLength - offset
10764
- );
10765
- offset += bytesWritten;
10766
- }
10767
- written += value.byteLength;
10780
+ if (!otherReferences.length) continue;
10781
+ }
10782
+ if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
10783
+ (object2) => options.weakReferences.get(object2)?.has(symbol)
10784
+ ))
10785
+ continue;
10786
+ const providerImages = new Set(record.providers.values());
10787
+ const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
10788
+ (object2) => {
10789
+ const image = options.owners.get(object2);
10790
+ return image === void 0 ? [] : [{ image, weak: !!options.weakDefinitions.get(object2)?.has(symbol) }];
10768
10791
  }
10769
- await handle.close();
10770
- handle = void 0;
10771
- if (!res.headers.get("content-encoding")) {
10772
- const header = res.headers.get("content-length");
10773
- const expected = header ? Number(header) : Number.NaN;
10774
- if (Number.isFinite(expected) && expected > 0 && written !== expected) {
10775
- throw new Error(`incomplete download (${written}/${expected} bytes): ${url}`);
10776
- }
10792
+ );
10793
+ const copyImages = new Set(copies.map((copy) => copy.image));
10794
+ const strongImages = new Set(
10795
+ copies.filter((copy) => !copy.weak).map((copy) => copy.image)
10796
+ );
10797
+ const interposed = !record.physicalModule && copyImages.size > 1 && strongImages.size <= 1;
10798
+ const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
10799
+ if (!providerCount) continue;
10800
+ if (providerCount !== 1)
10801
+ throw new Error(`guest symbol has ambiguous provider ${symbol}`);
10802
+ const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
10803
+ for (const [object2, caller] of scopedReferences) {
10804
+ const scope = callers.get(caller);
10805
+ if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
10806
+ if (record.physicalModule) {
10807
+ result.push({ symbol, caller, provider: { kind: "physical-module" } });
10808
+ continue;
10777
10809
  }
10778
- signal?.throwIfAborted();
10779
- fs8.renameSync(tmp, destPath);
10780
- completed = true;
10781
- return;
10782
- } catch (err) {
10783
- if (handle) await handle.close().catch(() => {
10784
- });
10785
- if (reader2 && !completed) await reader2.cancel().catch(() => {
10786
- });
10787
- try {
10788
- fs8.unlinkSync(tmp);
10789
- } catch {
10810
+ const provider = interposed ? [caller, ...scope].find((image) => copyImages.has(image)) ?? [...strongImages][0] ?? [...providerImages][0] : [...providerImages][0];
10811
+ if (provider === void 0)
10812
+ throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
10813
+ if (caller === provider) continue;
10814
+ if ([...options.definitionObjects.get(symbol) ?? []].some(
10815
+ (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
10816
+ ))
10817
+ continue;
10818
+ if (!scope.includes(provider)) {
10819
+ const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10820
+ const traced = [...record.providers.keys()];
10821
+ const strongTraced = traced.filter(
10822
+ (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10823
+ );
10824
+ const providers = strongTraced.length === 1 ? strongTraced : traced;
10825
+ if (options.weakReferences.get(object2)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
10826
+ continue;
10827
+ const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
10828
+ (definer) => options.weakDefinitions.get(definer)?.has(symbol)
10829
+ );
10830
+ const strongCandidates = [...candidates].filter(
10831
+ (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10832
+ );
10833
+ const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
10834
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
10835
+ // scope, the root image and its dependency closure, as in elf.
10836
+ provider === 0 || callers.get(0)?.includes(provider) || !options.weakReferences.get(object2)?.has(symbol) && options.frameworkProviders.get(object2)?.has(providers[0]))))
10837
+ throw new Error(
10838
+ `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
10839
+ );
10840
+ directBindings.push({
10841
+ object: object2,
10842
+ symbol,
10843
+ providerObject: providers[0],
10844
+ providerImage: provider
10845
+ });
10846
+ continue;
10790
10847
  }
10791
- const nonRetryable = err instanceof DownloadHttpError && !err.retryable;
10792
- if (signal?.aborted || nonRetryable || attempt === 4) throw err;
10793
- await waitRetryDelay(250 * attempt, signal);
10848
+ result.push({ symbol, caller, provider: { kind: "image", image: provider } });
10794
10849
  }
10795
10850
  }
10851
+ return { bindings: result, directBindings };
10796
10852
  }
10797
- async function digestFile(filePath, algorithm, encoding, signal) {
10798
- const hash = crypto.createHash(algorithm);
10799
- await pipeline2(fs8.createReadStream(filePath), hash, { signal });
10800
- return hash.digest(encoding);
10801
- }
10802
- function extractZip(zipPath, destDir, signal) {
10803
- return runExtractor("ditto", ["-x", "-k", zipPath, destDir], signal);
10804
- }
10805
- async function extractTarball(tarPath, zstd, destDir, stripComponents, signal) {
10806
- const args = [zstd ? "-xf" : "-xzf", "-"];
10807
- if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
10808
- if (zstd) {
10809
- const decoder = zlib2.createZstdDecompress({
10810
- params: { [zlib2.constants.ZSTD_d_windowLogMax]: 30 }
10811
- });
10812
- await runExtractor("tar", ["--ignore-zeros", ...args], signal, {
10813
- cwd: destDir,
10814
- stdin: (stdin) => pipeline2(fs8.createReadStream(tarPath), decoder, stdin, { signal })
10815
- });
10816
- return;
10817
- }
10818
- const archive = fs8.openSync(tarPath, "r");
10819
- try {
10820
- await runExtractor("tar", args, signal, { cwd: destDir, stdin: archive });
10821
- } finally {
10822
- fs8.closeSync(archive);
10823
- }
10824
- }
10825
- async function runExtractor(command, args, signal, input) {
10826
- signal?.throwIfAborted();
10827
- const stdin = input?.stdin;
10828
- const stdio = [
10829
- typeof stdin === "function" ? "pipe" : stdin ?? "ignore",
10830
- "inherit",
10831
- "inherit"
10832
- ];
10833
- const child = spawn3(command, args, {
10834
- cwd: input?.cwd,
10835
- stdio,
10836
- detached: process.platform !== "win32"
10837
- });
10838
- const fed = typeof stdin === "function" && child.stdin ? stdin(child.stdin) : void 0;
10839
- void fed?.catch(() => {
10840
- });
10841
- let stopping;
10842
- const abort = () => {
10843
- stopping ?? (stopping = terminateProcessGroup(child, "SIGKILL", 0));
10844
- void stopping.catch(() => {
10845
- });
10846
- };
10847
- try {
10848
- await new Promise((resolve, reject) => {
10849
- let failure;
10850
- child.on("error", (error) => {
10851
- failure = error;
10852
- });
10853
- child.on("close", (code) => {
10854
- if (signal?.aborted) {
10855
- const reason = signal.reason;
10856
- reject(
10857
- reason instanceof Error ? reason : new Error("Extraction canceled", { cause: reason })
10853
+ function linkPrunedGuestImages(options) {
10854
+ let result;
10855
+ pruneSwiftWasmLink(
10856
+ options.buildDirectory,
10857
+ options.toolchainBin,
10858
+ options.moduleRoot,
10859
+ options.staticClangTargets,
10860
+ void 0,
10861
+ (args, rewritten, sdk) => {
10862
+ if (args.some((arg) => arg === "--Map" || arg.startsWith("--Map=")))
10863
+ throw new Error("guest link already has a linker map");
10864
+ const framework = options.framework;
10865
+ const prepared = options.prepareRuntime?.(args, rewritten, sdk);
10866
+ if (prepared && options.sdkProducts !== null)
10867
+ throw new Error("guest runtime products supplied twice");
10868
+ const linkedArgs = prepared?.args ?? args;
10869
+ const sdkProducts = prepared?.sdkProducts ?? (typeof options.sdkProducts === "function" ? options.sdkProducts(args, rewritten, sdk) : options.sdkProducts);
10870
+ const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts);
10871
+ let frameworkArtifacts = [];
10872
+ const selectedObjects = prepared && new Set(
10873
+ prepared.selected.filter((item) => item.member === null).map((item) => path19.resolve(item.artifact))
10874
+ );
10875
+ const selectedFramework = framework && (!prepared || framework.product.objects.some((object2) => {
10876
+ const original = path19.resolve(framework.root, object2.path);
10877
+ const linked = path19.resolve(rewritten.get(original) ?? original);
10878
+ return selectedObjects?.has(linked) ?? false;
10879
+ }));
10880
+ if (framework && selectedFramework) {
10881
+ const image = sdkProducts?.images.get(
10882
+ frameworkRuntimeProductId(framework.product)
10883
+ );
10884
+ if (image === void 0)
10885
+ throw new Error(
10886
+ "framework objects require their declared compiler runtime image"
10858
10887
  );
10859
- } else if (failure) reject(failure);
10860
- else if (code === 0) resolve();
10861
- else reject(new Error(`${command} exited with code ${code}`));
10888
+ frameworkArtifacts = guestFrameworkLinkArtifacts(
10889
+ framework.product,
10890
+ framework.root,
10891
+ linkedArgs,
10892
+ rewritten,
10893
+ image
10894
+ );
10895
+ }
10896
+ if (sdkProducts) {
10897
+ for (const image of guestSdkProductImages(
10898
+ sdkProducts.products.map((entry) => entry.product),
10899
+ sdkProducts.images
10900
+ )) {
10901
+ const planned = sourcePlan.images.find((entry) => entry.id === image.id);
10902
+ if (!planned || planned.name !== image.name || planned.dependencies.length !== image.dependencies.length || planned.dependencies.some(
10903
+ (dependency, index) => dependency !== image.dependencies[index]
10904
+ ))
10905
+ throw new Error(`SDK image scope differs from source product ${image.name}`);
10906
+ }
10907
+ }
10908
+ const plan = remapGuestLinkPlan(
10909
+ {
10910
+ ...sourcePlan,
10911
+ artifacts: [
10912
+ ...sourcePlan.artifacts,
10913
+ ...frameworkArtifacts,
10914
+ ...sdkProducts ? guestSdkProductLinkArtifacts(
10915
+ sdkProducts.products,
10916
+ sdk,
10917
+ linkedArgs,
10918
+ sdkProducts.linkedArchives,
10919
+ rewritten,
10920
+ new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
10921
+ prepared?.selected
10922
+ ) : [],
10923
+ ...prepared?.archiveArtifacts ?? []
10924
+ ]
10925
+ },
10926
+ rewritten
10927
+ );
10928
+ let owners = /* @__PURE__ */ new Map();
10929
+ let generatedSectionOwners = /* @__PURE__ */ new Map();
10930
+ let projection = typeof options.projection === "function" ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan) : options.projection;
10931
+ if (projection && prepared) {
10932
+ const identities = new Map(projection.identities);
10933
+ for (const [before, after] of rewritten) {
10934
+ const identity = identities.get(before);
10935
+ const existing = identities.get(after);
10936
+ if (identity !== void 0 && existing !== void 0 && existing !== identity)
10937
+ throw new Error(`rewritten guest input has conflicting identity ${after}`);
10938
+ if (identity !== void 0) identities.set(after, identity);
10939
+ }
10940
+ projection = {
10941
+ ...projection,
10942
+ identities: aliasGuestLinkIdentities(identities, prepared.archives)
10943
+ };
10944
+ }
10945
+ const selected = linkCompleteGuestImages({
10946
+ plan,
10947
+ args: [...linkedArgs, `--Map=${options.mapPath}`],
10948
+ directory: options.linkDirectory,
10949
+ wasmLd: path19.join(options.toolchainBin, "wasm-ld"),
10950
+ clang: path19.join(options.toolchainBin, "clang"),
10951
+ llvmAr: path19.join(options.toolchainBin, "llvm-ar"),
10952
+ ledgerDataImage: options.ledgerDataImage,
10953
+ projection,
10954
+ resolvePlan: options.resolvePlan,
10955
+ onLinkedOwners: (value) => {
10956
+ owners = value;
10957
+ },
10958
+ onLinkedSections: (value) => {
10959
+ generatedSectionOwners = value;
10960
+ }
10862
10961
  });
10863
- signal?.addEventListener("abort", abort, { once: true });
10864
- if (signal?.aborted) abort();
10865
- });
10866
- await fed;
10867
- } finally {
10868
- signal?.removeEventListener("abort", abort);
10869
- await stopping;
10870
- }
10871
- }
10872
-
10873
- // src/binaryen.lock.json
10874
- var binaryen_lock_default = {
10875
- version: "132",
10876
- licenseSha256: "64c0d02491e16eced74826440ecd2bcf7722d37fa586faf457b2494293afbffe",
10877
- platforms: {
10878
- "linux-x64": {
10879
- asset: "x86_64-linux",
10880
- upstreamSha256: "195ddc94f9bc89f45abdabb0b9eea86023d727ba90eac8b35b80f2544fc30572",
10881
- sha256: "0396b1a540e9f97f30eb6a378d829305c218c821a0bd88c74e83d3d6923dad0b"
10882
- },
10883
- "linux-arm64": {
10884
- asset: "aarch64-linux",
10885
- upstreamSha256: "c58562417836c5d0493d89bdefc434933bdc097db641b483df86bcfa557a107f",
10886
- sha256: "25e3747f19614b0281a28b9a909ddc602b546ccdfacebc8cae2f7165665328fa"
10962
+ result = {
10963
+ selected,
10964
+ owners,
10965
+ generatedSectionOwners,
10966
+ sdk,
10967
+ mapPath: options.mapPath,
10968
+ generatedLedgerObject: path19.join(options.linkDirectory, "ledger.o")
10969
+ };
10887
10970
  },
10888
- "darwin-arm64": {
10889
- asset: "arm64-macos",
10890
- upstreamSha256: "98aad827847af7ef990ed7098d885725c8e5b5aae75073403635617ae4e259aa",
10891
- sha256: "34281566fe32df71337aaf0b60aa265dc853587d92bda0b5b1fac8aed8c2f8ab"
10892
- }
10893
- }
10894
- };
10971
+ options.resourceReferences
10972
+ );
10973
+ if (!result) throw new Error("guest link did not receive pruned inputs");
10974
+ return result;
10975
+ }
10895
10976
 
10896
- // src/home-paths.ts
10897
- import { randomUUID as randomUUID2 } from "node:crypto";
10898
- import fs9 from "node:fs";
10899
- import { homedir } from "node:os";
10977
+ // src/swift-guest-source-inputs.ts
10978
+ import { execFileSync as execFileSync8 } from "node:child_process";
10979
+ import { createHash as createHash11 } from "node:crypto";
10980
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, realpathSync as realpathSync2, writeFileSync as writeFileSync5 } from "node:fs";
10900
10981
  import path20 from "node:path";
10901
- var PEACH_HOME_ENV = "PEACH_HOME";
10902
- function ambientHomeDir() {
10903
- return path20.join(homedir(), ".peach");
10904
- }
10905
- function rnxHomeDir() {
10906
- const override = process.env[PEACH_HOME_ENV];
10907
- return override && override.length > 0 ? path20.resolve(override) : ambientHomeDir();
10908
- }
10909
- function cacheDir() {
10910
- return path20.join(rnxHomeDir(), "cache");
10911
- }
10912
- var DAEMON_LOCKFILE_MAX_BYTES = 16 * 1024;
10913
10982
 
10914
- // src/wasm-narrow-boundary.ts
10915
- var I64 = 126;
10916
- var VALUE_TYPES = /* @__PURE__ */ new Map([
10917
- [127, "i32"],
10918
- [I64, "i64"],
10919
- [125, "f32"],
10920
- [124, "f64"],
10921
- [123, "v128"],
10922
- [112, "funcref"],
10923
- [111, "externref"]
10924
- ]);
10925
- var GUEST = "guest";
10926
- var BOUNDARY = "boundary";
10927
- var WIDE = "$wide.";
10928
- var NARROW = "$narrow.";
10929
- function encodeNumber2(value) {
10930
- const bytes = [];
10931
- for (let rest = value; ; ) {
10932
- const byte = rest % 128;
10933
- rest = Math.floor(rest / 128);
10934
- if (rest === 0) return [...bytes, byte];
10935
- bytes.push(byte | 128);
10983
+ // src/forked-script-contract.ts
10984
+ var PEACH_FORKED_SCRIPT_ENV = "PEACH_RUNS_FORKED_SCRIPTS";
10985
+
10986
+ // src/swift-guest-source-inputs.ts
10987
+ function clangIrLinkOptions(ir) {
10988
+ const list = /^!llvm\.linker\.options = !\{([^\n]*)\}$/m.exec(ir);
10989
+ if (!list) {
10990
+ if (/^!llvm\.linker\.options\s*=/m.test(ir))
10991
+ throw new Error("invalid clang link metadata list");
10992
+ return [];
10993
+ }
10994
+ const ids = list[1].split(",").map((item) => item.trim());
10995
+ if (ids.length === 1 && ids[0] === "") return [];
10996
+ const result = [];
10997
+ for (const id of ids) {
10998
+ if (!/^!\d+$/.test(id)) throw new Error(`invalid clang link metadata ${id}`);
10999
+ const node = new RegExp(`^${id} = !\\{([^\\n]*)\\}$`, "m").exec(ir);
11000
+ if (!node) throw new Error(`missing clang link metadata ${id}`);
11001
+ const parts = node[1].split(/,\s*(?=!")/);
11002
+ for (const part of parts) {
11003
+ const value = /^!"((?:[^"\\]|\\[0-9A-Fa-f]{2})*)"$/.exec(part.trim());
11004
+ if (!value) throw new Error(`invalid clang link option ${part}`);
11005
+ const decoded = value[1].replace(
11006
+ /\\([0-9A-Fa-f]{2})/g,
11007
+ (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))
11008
+ );
11009
+ const flag = Buffer.from(decoded, "latin1").toString("utf8");
11010
+ if (!flag || flag.includes("\0")) throw new Error("invalid empty clang link option");
11011
+ result.push(flag);
11012
+ }
10936
11013
  }
11014
+ return result;
10937
11015
  }
10938
- function encodeName(name2) {
10939
- const bytes = [...Buffer.from(name2)];
10940
- return [...encodeNumber2(bytes.length), ...bytes];
11016
+ var CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
11017
+ var PARALLEL_REPLAY = `
11018
+ const { spawn } = require('node:child_process')
11019
+ const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
11020
+ let next = 0
11021
+ const run = () => {
11022
+ if (next >= commands.length) return Promise.resolve()
11023
+ const [file, ...args] = commands[next++]
11024
+ return new Promise((resolve, reject) => {
11025
+ const child = spawn(file, args, { stdio: 'inherit' })
11026
+ child.on('error', reject)
11027
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
11028
+ }).then(run)
10941
11029
  }
10942
- function reader(bytes, start, end) {
10943
- let at = start;
10944
- const number3 = () => {
10945
- let value = 0;
10946
- for (let shift = 0; ; shift += 7) {
10947
- if (at >= end || shift > 63) throw new Error("invalid wasm integer");
10948
- const byte = bytes[at++];
10949
- value += (byte & 127) * 2 ** shift;
10950
- if (!(byte & 128)) return value;
11030
+ const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
11031
+ Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
11032
+ console.error(error.message)
11033
+ process.exit(1)
11034
+ })
11035
+ `;
11036
+ function sourceGuestClangLinkOptions(options) {
11037
+ const wanted = new Set(options.objects.map((file) => path20.resolve(file)));
11038
+ const commands = /* @__PURE__ */ new Map();
11039
+ let tool = "";
11040
+ let outputs = [];
11041
+ for (const line of readFileSync12(
11042
+ path20.join(options.buildDirectory, ".build", "release.yaml"),
11043
+ "utf8"
11044
+ ).split("\n")) {
11045
+ if (line.startsWith(' "') && line.endsWith(":")) {
11046
+ tool = "";
11047
+ outputs = [];
11048
+ continue;
11049
+ }
11050
+ if (line.startsWith(" tool: ")) tool = line.slice(10).trim();
11051
+ if (line.startsWith(" outputs: ")) {
11052
+ const value2 = JSON.parse(line.slice(13));
11053
+ if (!Array.isArray(value2) || !value2.every((item) => typeof item === "string"))
11054
+ throw new Error("invalid build command outputs");
11055
+ outputs = value2;
11056
+ }
11057
+ if (!line.startsWith(" args: ") || !outputs.some((file) => wanted.has(path20.resolve(file))))
11058
+ continue;
11059
+ const value = JSON.parse(line.slice(10));
11060
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
11061
+ throw new Error("invalid build command arguments");
11062
+ for (const output of outputs) {
11063
+ const file = path20.resolve(output);
11064
+ if (!wanted.has(file)) continue;
11065
+ if (commands.has(file)) throw new Error(`ambiguous source object producer ${file}`);
11066
+ commands.set(file, { tool, args: value });
10951
11067
  }
10952
- };
10953
- return {
10954
- number: number3,
10955
- byte: () => {
10956
- if (at >= end) throw new Error("truncated wasm section");
10957
- return bytes[at++];
10958
- },
10959
- name: () => {
10960
- const length = number3();
10961
- at += length;
10962
- if (at > end) throw new Error("truncated wasm name");
10963
- return Buffer.from(bytes.subarray(at - length, at)).toString();
10964
- },
10965
- position: () => at,
10966
- done: () => at === end
10967
- };
10968
- }
10969
- function sections(bytes) {
10970
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
10971
- throw new Error("not a wasm module");
10972
- const found = [];
10973
- for (let at = 8; at < bytes.length; ) {
10974
- const header = reader(bytes, at, bytes.length);
10975
- const id = header.byte();
10976
- const size = header.number();
10977
- const start = header.position();
10978
- found.push({ id, start, end: start + size });
10979
- at = start + size;
10980
11068
  }
10981
- return found;
10982
- }
10983
- function withSections(bytes, layout2, replacements) {
10984
- const parts = [bytes.subarray(0, 8)];
10985
- let at = 8;
10986
- for (const section of layout2) {
10987
- const body = replacements.get(section.id);
10988
- parts.push(
10989
- body ? Uint8Array.from([section.id, ...encodeNumber2(body.length), ...body]) : bytes.subarray(at, section.end)
11069
+ const replays = [];
11070
+ for (const [index, file] of [...wanted].entries()) {
11071
+ const command = commands.get(file);
11072
+ if (!command) throw new Error(`missing source object producer ${file}`);
11073
+ if (command.tool === "shell") {
11074
+ if (!command.args.length || realpathSync2(command.args[0]) !== realpathSync2(options.swiftCompiler))
11075
+ throw new Error(`unsupported source object producer ${file}`);
11076
+ continue;
11077
+ }
11078
+ const compiler = command.args[0] ? realpathSync2(command.args[0]) : "";
11079
+ if (command.tool !== "clang" || compiler !== realpathSync2(path20.join(options.toolchainBin, "clang")) && compiler !== realpathSync2(path20.join(options.buildDirectory, CLANG_TARGET_MODULE_WRAPPER)))
11080
+ throw new Error(`unsupported source object producer ${file}`);
11081
+ const args = command.args.slice(1).filter((arg) => arg !== "-c");
11082
+ const targetBuild = path20.relative(options.buildDirectory, file).split(path20.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
11083
+ const outputDirectory = path20.join(
11084
+ options.directory,
11085
+ targetBuild ?? path20.basename(path20.dirname(file))
10990
11086
  );
10991
- at = section.end;
11087
+ mkdirSync3(outputDirectory, { recursive: true });
11088
+ const output = path20.join(outputDirectory, `clang-link-${index}.ll`);
11089
+ for (const flag of ["-o", "-MF"]) {
11090
+ const index2 = args.lastIndexOf(flag);
11091
+ if (index2 < 0 || index2 + 1 >= args.length)
11092
+ throw new Error(`missing clang ${flag} for ${file}`);
11093
+ args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
11094
+ }
11095
+ replays.push({
11096
+ file,
11097
+ compiler: command.args[0],
11098
+ args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
11099
+ output
11100
+ });
10992
11101
  }
10993
- return Buffer.concat(parts);
10994
- }
10995
- var quoted = (name2) => `"${[...Buffer.from(name2)].map((byte) => `\\${byte.toString(16).padStart(2, "0")}`).join("")}"`;
10996
- var signature = (types, keyword, narrow) => types.length === 0 ? "" : ` (${keyword} ${types.map((type) => {
10997
- const name2 = VALUE_TYPES.get(narrow && type === I64 ? 127 : type);
10998
- if (!name2) throw new Error(`unsupported wasm boundary type ${type}`);
10999
- return name2;
11000
- }).join(" ")})`;
11001
- var wide = (type) => type.parameters.includes(I64) || type.results.includes(I64);
11002
- function narrowWasmBoundary(bytes) {
11003
- const layout2 = sections(bytes);
11004
- const section = (id) => {
11005
- const found = layout2.find((entry) => entry.id === id);
11006
- return found && reader(bytes, found.start, found.end);
11007
- };
11008
- const types = [];
11009
- const typeSection = section(1);
11010
- if (typeSection) {
11011
- for (let count = typeSection.number(); count > 0; count--) {
11012
- if (typeSection.byte() !== 96) throw new Error("unsupported wasm type");
11013
- const values = () => Array.from({ length: typeSection.number() }, () => typeSection.byte());
11014
- types.push({ parameters: values(), results: values() });
11102
+ const plan = path20.join(options.directory, "clang-link-replays.json");
11103
+ writeFileSync5(
11104
+ plan,
11105
+ JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
11106
+ );
11107
+ const script = path20.join(options.directory, "clang-link-replay.cjs");
11108
+ writeFileSync5(script, PARALLEL_REPLAY);
11109
+ execFileSync8(process.execPath, [script], {
11110
+ stdio: "inherit",
11111
+ env: {
11112
+ ...process.env,
11113
+ [PEACH_FORKED_SCRIPT_ENV]: "1",
11114
+ PEACH_CLANG_REPLAYS: plan,
11115
+ PEACH_CLANG_JOBS: String(options.jobs)
11116
+ }
11117
+ });
11118
+ const result = /* @__PURE__ */ new Map();
11119
+ for (const { file, output } of replays) {
11120
+ const flags = clangIrLinkOptions(readFileSync12(output, "utf8"));
11121
+ for (let index = 0; index < flags.length; index++) {
11122
+ const flag = flags[index];
11123
+ if (flag === "-framework" || flag === "-l" || flag === "--library") {
11124
+ const name2 = flags[++index];
11125
+ if (!name2 || name2.startsWith("-"))
11126
+ throw new Error(`missing clang link name after ${flag}`);
11127
+ } else if (!/^(-l.+|--library=.+)$/.test(flag)) {
11128
+ throw new Error(`unsupported clang link option ${flag}`);
11129
+ }
11015
11130
  }
11131
+ result.set(file, flags);
11016
11132
  }
11017
- const typeAt = (index) => {
11018
- const type = types[index];
11019
- if (!type) throw new Error("invalid wasm type index");
11020
- return type;
11021
- };
11022
- const thunks = [];
11023
- const functionTypes = [];
11024
- const importBody = [];
11025
- const importSection = section(2);
11026
- if (importSection) {
11027
- const count = importSection.number();
11028
- importBody.push(...encodeNumber2(count));
11029
- for (let index = 0; index < count; index++) {
11030
- const module = importSection.name();
11031
- const name2 = importSection.name();
11032
- const start = importSection.position();
11033
- const kind = importSection.byte();
11034
- const limits = () => {
11035
- const flags = importSection.number();
11036
- importSection.number();
11037
- if (flags & 1) importSection.number();
11038
- };
11039
- let type;
11040
- if (kind === 0) {
11041
- type = typeAt(importSection.number());
11042
- functionTypes.push(type);
11043
- } else if (kind === 1) {
11044
- importSection.byte();
11045
- limits();
11046
- } else if (kind === 2) limits();
11047
- else if (kind === 3) {
11048
- importSection.byte();
11049
- importSection.byte();
11050
- } else if (kind === 4) {
11051
- importSection.byte();
11052
- importSection.number();
11053
- } else throw new Error("unsupported wasm import");
11054
- const scalar64 = (parameter) => module === "wasi_snapshot_preview1" && (!name2.startsWith("peach_") || name2 === "peach_fs_path_birthtime_set" && parameter === 2) || module === "peach" && name2 === "hw_memsize" && parameter === null || module === "peach_notify" && name2 === "set" && parameter === 1;
11055
- const parameters = type?.parameters.map(
11056
- (value, index2) => value === I64 && !scalar64(index2) ? 127 : value
11133
+ return result;
11134
+ }
11135
+ function sourceGuestInputIdentities(graph, buildDirectory, objects) {
11136
+ const producers = /* @__PURE__ */ new Map();
11137
+ for (const target of graph.targets)
11138
+ if (target.sourceTarget !== null)
11139
+ producers.set(
11140
+ target.sourceTarget,
11141
+ producers.has(target.sourceTarget) ? null : target.id
11057
11142
  );
11058
- const results = type?.results.map(
11059
- (value) => value === I64 && !scalar64(null) ? 127 : value
11143
+ const identities = /* @__PURE__ */ new Map();
11144
+ for (const object2 of objects) {
11145
+ const target = producers.get(object2.sourceTarget);
11146
+ if (target === null || target === void 0)
11147
+ throw new Error(`ambiguous source producer ${object2.sourceTarget}`);
11148
+ if (object2.kind === "archive") {
11149
+ identities.set(
11150
+ object2.path,
11151
+ JSON.stringify([
11152
+ "source",
11153
+ target,
11154
+ `libraries/lib${libraryArchiveTarget(object2.path)}.a`
11155
+ ])
11060
11156
  );
11061
- if (type && parameters && results && (parameters.some((value, index2) => value !== type.parameters[index2]) || results.some((value, index2) => value !== type.results[index2]))) {
11062
- if (type.results.length > 1)
11063
- throw new Error(`import ${module}.${name2} returns several values`);
11064
- const id = thunks.length;
11065
- const call = `(call $host${id}${type.parameters.map(
11066
- (value, at) => value !== parameters[at] ? ` (i32.wrap_i64 (local.get ${at}))` : ` (local.get ${at})`
11067
- ).join("")})`;
11068
- thunks.push(
11069
- `(import ${quoted(module)} ${quoted(name2)} (func $host${id}${signature(parameters, "param", false)}${signature(results, "result", false)}))`,
11070
- `(func (export "${NARROW}${id}")${signature(type.parameters, "param", false)}${signature(type.results, "result", false)} ${type.results[0] !== results[0] ? `(i64.extend_i32_u ${call})` : call})`
11071
- );
11072
- importBody.push(...encodeName(BOUNDARY), ...encodeName(`${NARROW}${id}`));
11073
- } else importBody.push(...encodeName(module), ...encodeName(name2));
11074
- importBody.push(...bytes.subarray(start, importSection.position()));
11157
+ continue;
11075
11158
  }
11076
- if (!importSection.done()) throw new Error("invalid wasm imports");
11159
+ const relative = path20.relative(buildDirectory, object2.path).split(path20.sep);
11160
+ if (!relative[0]?.endsWith(".build") || relative.length < 2)
11161
+ throw new Error(`source object is outside its producer ${object2.path}`);
11162
+ identities.set(object2.path, JSON.stringify(["source", target, relative.join("/")]));
11077
11163
  }
11078
- const functionSection = section(3);
11079
- if (functionSection)
11080
- for (let count = functionSection.number(); count > 0; count--)
11081
- functionTypes.push(typeAt(functionSection.number()));
11082
- const exportBody = [];
11083
- const exportSection = section(7);
11084
- if (exportSection) {
11085
- const count = exportSection.number();
11086
- exportBody.push(...encodeNumber2(count));
11087
- for (let index = 0; index < count; index++) {
11088
- const name2 = exportSection.name();
11089
- const kind = exportSection.byte();
11090
- const target = exportSection.number();
11091
- const type = kind === 0 ? functionTypes[target] : void 0;
11092
- if (kind === 0 && !type) throw new Error("invalid wasm export");
11093
- if (type && wide(type)) {
11094
- if (type.results.length > 1)
11095
- throw new Error(`export ${name2} returns several values`);
11096
- const id = thunks.length;
11097
- const call = `(call $guest${id}${type.parameters.map(
11098
- (value, at) => value === I64 ? ` (i64.extend_i32_u (local.get ${at}))` : ` (local.get ${at})`
11099
- ).join("")})`;
11100
- thunks.push(
11101
- `(import "${GUEST}" "${WIDE}${id}" (func $guest${id}${signature(type.parameters, "param", false)}${signature(type.results, "result", false)}))`,
11102
- `(func (export ${quoted(name2)})${signature(type.parameters, "param", true)}${signature(type.results, "result", true)} ${type.results[0] === I64 ? `(i32.wrap_i64 ${call})` : call})`
11103
- );
11104
- exportBody.push(...encodeName(`${WIDE}${id}`));
11105
- } else exportBody.push(...encodeName(name2));
11106
- exportBody.push(kind, ...encodeNumber2(target));
11164
+ return identities;
11165
+ }
11166
+ function sourceGuestRuntimeLinks(options) {
11167
+ const aliases = /* @__PURE__ */ new Map();
11168
+ const artifacts = /* @__PURE__ */ new Map();
11169
+ const frameworkAliases = /* @__PURE__ */ new Map();
11170
+ const sdkAliases = /* @__PURE__ */ new Map();
11171
+ for (const { product, root } of options.products) {
11172
+ for (const alias of product.frameworkAliases) {
11173
+ if (product.linkOwnership !== "image")
11174
+ throw new Error(`framework namespace has no image owner ${product.id}`);
11175
+ const previous = sdkAliases.get(alias.name);
11176
+ if (previous) {
11177
+ if (previous.product !== product.id || previous.moduleMap !== alias.moduleMap || previous.sha256 !== alias.moduleMapSha256)
11178
+ throw new Error(`ambiguous declared framework ${alias.name}`);
11179
+ continue;
11180
+ }
11181
+ const directory = path20.resolve(options.sdk.root);
11182
+ const file = path20.resolve(directory, alias.moduleMap);
11183
+ if (!file.startsWith(directory + path20.sep))
11184
+ throw new Error(`invalid framework module map ${alias.moduleMap}`);
11185
+ if (createHash11("sha256").update(readFileSync12(file)).digest("hex") !== alias.moduleMapSha256)
11186
+ throw new Error(`framework module map changed ${alias.moduleMap}`);
11187
+ sdkAliases.set(alias.name, {
11188
+ product: product.id,
11189
+ moduleMap: alias.moduleMap,
11190
+ sha256: alias.moduleMapSha256
11191
+ });
11192
+ frameworkAliases.set(alias.name, { kind: "sdk", product: product.id });
11193
+ }
11194
+ for (const artifact of product.artifacts) {
11195
+ const file = path20.resolve(root, artifact.path);
11196
+ const prior = artifacts.get(file);
11197
+ artifacts.set(file, prior === void 0 || prior === product.id ? product.id : null);
11198
+ }
11199
+ for (const name2 of product.linkNames) {
11200
+ const prior = aliases.get(name2);
11201
+ if (prior !== void 0 && prior !== product.id)
11202
+ throw new Error(`ambiguous declared runtime link name ${name2}`);
11203
+ aliases.set(name2, product.id);
11107
11204
  }
11108
- if (!exportSection.done()) throw new Error("invalid wasm exports");
11109
- }
11110
- if (thunks.length === 0) return void 0;
11111
- const imports = thunks.filter((line) => line.startsWith("(import"));
11112
- const functions = thunks.filter((line) => !line.startsWith("(import"));
11113
- return {
11114
- module: withSections(
11115
- bytes,
11116
- layout2,
11117
- /* @__PURE__ */ new Map([
11118
- [2, importBody],
11119
- [7, exportBody]
11120
- ])
11121
- ),
11122
- thunks: `(module
11123
- ${[...imports, ...functions].join("\n")}
11124
- )
11125
- `
11126
- };
11127
- }
11128
- var NARROW_MERGE_NAMES = { guest: GUEST, boundary: BOUNDARY };
11129
- function dropBoundaryExports(bytes) {
11130
- const layout2 = sections(bytes);
11131
- const found = layout2.find((entry) => entry.id === 7);
11132
- if (!found) throw new Error("merged module has no exports");
11133
- const exportSection = reader(bytes, found.start, found.end);
11134
- const kept = [];
11135
- for (let count = exportSection.number(); count > 0; count--) {
11136
- const name2 = exportSection.name();
11137
- const kind = exportSection.byte();
11138
- const target = exportSection.number();
11139
- if (!name2.startsWith(WIDE) && !name2.startsWith(NARROW))
11140
- kept.push([...encodeName(name2), kind, ...encodeNumber2(target)]);
11141
11205
  }
11142
- return withSections(
11143
- bytes,
11144
- layout2,
11145
- /* @__PURE__ */ new Map([[7, [...encodeNumber2(kept.length), ...kept.flat()]]])
11206
+ const frameworkId = frameworkRuntimeProductId(options.framework.product);
11207
+ const owners = options.products.filter(({ product }) => product.id === frameworkId);
11208
+ if (owners.length !== 1 || owners[0].product.linkOwnership !== "image" || path20.resolve(owners[0].root) !== path20.resolve(options.framework.root))
11209
+ throw new Error(`missing or ambiguous packaged image ${frameworkId}`);
11210
+ const targets = new Map(
11211
+ options.framework.product.targets.map((target) => [target.name, target])
11146
11212
  );
11147
- }
11148
-
11149
- // src/wasm-optimize.ts
11150
- var FEATURES = [
11151
- "memory64",
11152
- "threads",
11153
- "bulk-memory",
11154
- "bulk-memory-opt",
11155
- "call-indirect-overlong",
11156
- "exception-handling",
11157
- "multivalue",
11158
- "mutable-globals",
11159
- "nontrapping-float-to-int",
11160
- "reference-types",
11161
- "sign-ext"
11162
- ];
11163
- var KEEP_WASM_NAMES = process.env.PEACH_SWIFT_NAMES === "1";
11164
- var LOWERING = ["--memory64-lowering", "--table64-lowering"];
11165
- var BINARYEN_VERSION = binaryen_lock_default.version;
11166
- var runBinaryen = promisify2(execFile2);
11167
- var WASM_LOWER_IDENTITY = `binaryen ${BINARYEN_VERSION} narrow ${LOWERING.join(" ")} ${FEATURES.join(",")} unoptimized-names`;
11168
- var BINARYEN_RELEASES = new Map(Object.entries(binaryen_lock_default.platforms));
11169
- async function runWasmOpt(file, output, optimize, skipPasses, binary) {
11170
- const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES);
11171
- const requestedCores = Number(process.env.BINARYEN_CORES);
11172
- const environment = { ...process.env };
11173
- if (Number.isInteger(admittedCores) && admittedCores > 0)
11174
- environment.BINARYEN_CORES = String(
11175
- Number.isInteger(requestedCores) && requestedCores > 0 ? Math.min(admittedCores, requestedCores) : admittedCores
11176
- );
11177
- const features = FEATURES.map((feature) => `--enable-${feature}`);
11178
- const names = optimize && !KEEP_WASM_NAMES ? [] : ["-g"];
11179
- const narrowed = narrowWasmBoundary(readFileSync12(file));
11180
- const merged = `${output}.narrowed`;
11181
- if (narrowed) {
11182
- const guest = `${output}.guest`;
11183
- const thunks = `${output}.thunks.wat`;
11184
- writeFileSync5(guest, narrowed.module);
11185
- writeFileSync5(thunks, narrowed.thunks);
11186
- await runBinaryen(
11187
- join2(dirname(binary), "wasm-merge"),
11188
- [
11189
- ...features,
11190
- ...names,
11191
- guest,
11192
- NARROW_MERGE_NAMES.guest,
11193
- thunks,
11194
- NARROW_MERGE_NAMES.boundary,
11195
- "-o",
11196
- merged
11197
- ],
11198
- { env: environment }
11199
- );
11200
- writeFileSync5(merged, dropBoundaryExports(readFileSync12(merged)));
11201
- rmSync4(guest);
11202
- rmSync4(thunks);
11213
+ if (targets.size !== options.framework.product.targets.length)
11214
+ throw new Error("ambiguous packaged framework target");
11215
+ const objectTargets = new Set(
11216
+ options.framework.product.objects.map((object2) => object2.target)
11217
+ );
11218
+ const closure = (names) => {
11219
+ const linked = /* @__PURE__ */ new Set();
11220
+ const visit = (name2) => {
11221
+ if (linked.has(name2)) return;
11222
+ const target = targets.get(name2);
11223
+ if (!target) throw new Error(`unknown packaged framework target ${name2}`);
11224
+ linked.add(name2);
11225
+ for (const dependency of target.dependencies) visit(dependency);
11226
+ };
11227
+ for (const name2 of names) visit(name2);
11228
+ return [...linked];
11229
+ };
11230
+ for (const alias of options.framework.product.frameworkAliases) {
11231
+ if (frameworkAliases.has(alias.name))
11232
+ throw new Error(`ambiguous declared framework ${alias.name}`);
11233
+ if (alias.wasmSdkId !== options.sdk.wasmSdkId || alias.wasmSdkChecksum !== options.sdk.wasmSdkChecksum)
11234
+ throw new Error(`framework SDK identity differs for ${alias.name}`);
11235
+ if (!alias.targets.length || alias.targets.some((target) => !targets.has(target) || !objectTargets.has(target)))
11236
+ throw new Error(`framework target ownership differs for ${alias.name}`);
11237
+ const root = path20.resolve(options.framework.root);
11238
+ const map = path20.resolve(root, alias.moduleMap);
11239
+ if (!map.startsWith(root + path20.sep))
11240
+ throw new Error(`invalid framework module map ${alias.moduleMap}`);
11241
+ if (createHash11("sha256").update(readFileSync12(map)).digest("hex") !== alias.moduleMapSha256)
11242
+ throw new Error(`framework module map changed ${alias.moduleMap}`);
11243
+ frameworkAliases.set(alias.name, { kind: "package", targets: closure(alias.targets) });
11203
11244
  }
11204
- try {
11205
- await runBinaryen(
11206
- binary,
11207
- [
11208
- ...LOWERING,
11209
- ...optimize ? ["-Oz"] : [],
11210
- ...names,
11211
- ...skipPasses.flatMap((pass) => ["--skip-pass", pass]),
11212
- ...features,
11213
- narrowed ? merged : file,
11214
- "-o",
11215
- output
11216
- ],
11217
- { env: environment, maxBuffer: Infinity }
11245
+ for (const name2 of objectTargets)
11246
+ if (!frameworkAliases.has(name2) && targets.has(name2))
11247
+ frameworkAliases.set(name2, { kind: "package", targets: closure([name2]) });
11248
+ const result = /* @__PURE__ */ new Map();
11249
+ const frameworkRequests = /* @__PURE__ */ new Map();
11250
+ for (const image of options.images) {
11251
+ if (result.has(image.id)) throw new Error(`duplicate source image ${image.id}`);
11252
+ const response = path20.join(options.directory, `image-${image.id}-autolink.rsp`);
11253
+ writeFileSync5(
11254
+ response,
11255
+ image.objects.map((file) => JSON.stringify(file)).join("\n") + "\n"
11218
11256
  );
11219
- } finally {
11220
- if (narrowed) rmSync4(merged);
11257
+ const autolink = image.objects.length ? execFileSync8(
11258
+ path20.join(options.toolchainBin, "swift-autolink-extract"),
11259
+ [`@${response}`, "-o", "-"],
11260
+ { encoding: "utf8" }
11261
+ ).split("\n").map((line) => line.trim()).filter((line) => line.length > 0) : [];
11262
+ const links = [];
11263
+ const requests = [];
11264
+ const optionGroups = [
11265
+ { object: null, flags: image.linkerFlags, autoLinked: false },
11266
+ { object: null, flags: autolink, autoLinked: true },
11267
+ ...image.clangLinkOptions.map((options2) => ({ ...options2, autoLinked: true }))
11268
+ ];
11269
+ for (const { object: object2, flags, autoLinked } of optionGroups) {
11270
+ for (let index = 0; index < flags.length; index++) {
11271
+ const flag = flags[index];
11272
+ const artifact = artifacts.get(flag);
11273
+ if (artifact === null)
11274
+ throw new Error(`ambiguous declared runtime artifact ${flag}`);
11275
+ if (artifact !== void 0) {
11276
+ if (!links.includes(artifact)) links.push(artifact);
11277
+ continue;
11278
+ }
11279
+ if (path20.isAbsolute(flag) && flag.endsWith(".a"))
11280
+ throw new Error(
11281
+ `source image ${image.id} has unresolved runtime artifact ${flag}`
11282
+ );
11283
+ if (flag === "-framework") {
11284
+ const name3 = flags[++index];
11285
+ const provider = name3 && frameworkAliases.get(name3);
11286
+ if (!provider && name3 && autoLinked) continue;
11287
+ if (!provider)
11288
+ throw new Error(
11289
+ `source image ${image.id} has unresolved framework linkage ${name3}`
11290
+ );
11291
+ requests.push({ object: object2, provider });
11292
+ continue;
11293
+ }
11294
+ if (flag.startsWith("-weak") || flag.startsWith("-reexport") || flag.startsWith("-upward") || flag.startsWith("-lazy") || flag.startsWith("-Wl,"))
11295
+ throw new Error(
11296
+ `source image ${image.id} has unsupported runtime scope flag ${flag}`
11297
+ );
11298
+ const name2 = flag === "-l" || flag === "--library" ? flags[++index] : flag.startsWith("-l") ? flag.slice(2) : flag.startsWith("--library=") ? flag.slice("--library=".length) : null;
11299
+ if (name2 === null) continue;
11300
+ const product = name2 === void 0 ? void 0 : aliases.get(name2);
11301
+ if (product === void 0)
11302
+ throw new Error(`source image ${image.id} has unresolved runtime link ${name2}`);
11303
+ if (!links.includes(product)) links.push(product);
11304
+ }
11305
+ }
11306
+ result.set(image.id, links);
11307
+ frameworkRequests.set(image.id, requests);
11221
11308
  }
11309
+ return { links: result, frameworkRequests };
11222
11310
  }
11223
- async function installWasmOpt() {
11224
- const platform = `${process.platform}-${process.arch}`;
11225
- const release = BINARYEN_RELEASES.get(platform);
11226
- if (!release) throw new Error(`no pinned Binaryen release for ${platform}`);
11227
- const destDir = join2(rnxHomeDir(), "tools", "binaryen", BINARYEN_VERSION, platform);
11228
- const binary = join2(destDir, "bin", "wasm-opt");
11229
- if (!existsSync2(binary))
11230
- await installVerifiedTarball({
11231
- url: `https://r2.rnxsim.com/peach/binaryen/${release.sha256}/${platform}.tar.gz`,
11232
- digest: { algorithm: "sha256", encoding: "hex", value: release.sha256 },
11233
- destDir,
11234
- installedMarker: "bin/wasm-opt",
11235
- label: `Binaryen ${BINARYEN_VERSION}`
11236
- });
11237
- return binary;
11238
- }
11239
- async function lowerWasm(file, output, options) {
11240
- await runWasmOpt(
11241
- file,
11242
- output,
11243
- options.optimize,
11244
- options.skipPasses ?? [],
11245
- await installWasmOpt()
11311
+ function logicalGuestLinkOptions(args, identities, roots) {
11312
+ const orderedRoots = [...roots].sort(
11313
+ (left, right) => right.path.length - left.path.length
11246
11314
  );
11315
+ const logicalPath = (file) => {
11316
+ const direct = identities.get(file);
11317
+ if (direct !== void 0) return direct;
11318
+ if (/\.(?:o|obj|a)$/.test(file))
11319
+ throw new Error(`link input has no logical identity ${file}`);
11320
+ for (const root of orderedRoots) {
11321
+ const relative = path20.relative(root.path, file);
11322
+ if (relative !== ".." && !relative.startsWith(`..${path20.sep}`) && !path20.isAbsolute(relative))
11323
+ return `${root.identity}/${relative.split(path20.sep).join("/")}`;
11324
+ }
11325
+ throw new Error(`link option has no logical path identity ${file}`);
11326
+ };
11327
+ const output = [];
11328
+ for (let index = 0; index < args.length; index++) {
11329
+ const arg = args[index];
11330
+ if (arg === "-o" || arg === "--output" || arg === "--Map") {
11331
+ index++;
11332
+ continue;
11333
+ }
11334
+ if (arg.startsWith("--output=") || arg.startsWith("--Map=")) continue;
11335
+ if (arg === "-L" || arg === "--library-path") {
11336
+ output.push(arg, logicalPath(args[++index]));
11337
+ continue;
11338
+ }
11339
+ if (arg.startsWith("-L")) output.push(`-L${logicalPath(arg.slice(2))}`);
11340
+ else if (arg.startsWith("--library-path="))
11341
+ output.push(`--library-path=${logicalPath(arg.slice("--library-path=".length))}`);
11342
+ else if (path20.isAbsolute(arg)) output.push(logicalPath(arg));
11343
+ else if (/^[^=]+=\//.test(arg)) {
11344
+ const equals = arg.indexOf("=");
11345
+ output.push(arg.slice(0, equals + 1) + logicalPath(arg.slice(equals + 1)));
11346
+ } else output.push(identities.get(arg) ?? arg);
11347
+ }
11348
+ return output;
11247
11349
  }
11248
11350
 
11249
11351
  // src/swift-guest-compile.ts
@@ -12983,13 +13085,10 @@ function swiftDistributionAt(root) {
12983
13085
  return parseSwiftDistributionManifest(JSON.parse(readFileSync18(file, "utf8")));
12984
13086
  }
12985
13087
  var REACH_STAGED_FRAMEWORKS = /* @__PURE__ */ new Set(["React"]);
12986
- function swiftModuleInterface(moduleRoot, name2, interfaceRoot) {
13088
+ function swiftModuleInterface(moduleRoot, name2) {
12987
13089
  if (REACH_STAGED_FRAMEWORKS.has(name2)) return null;
12988
13090
  if (swiftDistributionAt(moduleRoot)) {
12989
- const file = path30.join(
12990
- interfaceRoot ?? path30.join(moduleRoot, "modules"),
12991
- `${name2}-Swift.h`
12992
- );
13091
+ const file = path30.join(moduleRoot, "modules", `${name2}-Swift.h`);
12993
13092
  if (!existsSync7(file)) return null;
12994
13093
  const header = clangInterfaceHeader(readFileSync18(file, "utf8"));
12995
13094
  return { declared: swiftInterfaceDeclarations(header), header };
@@ -13951,7 +14050,7 @@ var darwinRecordsRegion = (quoted2) => quoted2.length ? ["-Wl,--start-lib", ...q
13951
14050
  var REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
13952
14051
  var MULTI_MANIFEST_VERSION = 72;
13953
14052
  var SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
13954
- var compilerSourceDigest = true ? "4a6e02699924195639b15c5cdfd8852b5f17fb2ffacb8f9f964ef3daeee8b9dc" : swiftCompilerSourceDigest(import.meta.dirname);
14053
+ var compilerSourceDigest = true ? "f691ad9847363fc601dda32d460b473efaac6c30948a278f162a896afa1df816" : swiftCompilerSourceDigest(import.meta.dirname);
13955
14054
  function swiftArtifactHash(input, release, moduleRoot) {
13956
14055
  const hash = createHash15("sha256");
13957
14056
  hash.update(`swift-compile
@@ -16683,6 +16782,10 @@ ${swiftProjectFilesProblems(input.projectFiles).join("\n")}`
16683
16782
  includeDirectory: path30.join(layout2.root, includes),
16684
16783
  sources: units.map(([file]) => file.slice(prefix.length)),
16685
16784
  lateSources: late.map(([file]) => file.slice(prefix.length)),
16785
+ exclude: [
16786
+ ...late.map(([file]) => file.slice(prefix.length)),
16787
+ ...entries.filter(([file]) => /\.(?:inc|inl|ipp|def)$/.test(file)).map(([file]) => file.slice(prefix.length))
16788
+ ],
16686
16789
  ...late.length > 0 ? {
16687
16790
  late: {
16688
16791
  name: `${target.name}SwiftImplementation`,
@@ -17245,6 +17348,7 @@ module ${moduleName}.Swift {
17245
17348
  "explicit=",
17246
17349
  "prev=",
17247
17350
  "cxx=",
17351
+ "plainCxx=",
17248
17352
  "cxxModules=",
17249
17353
  'for arg in "$@"; do',
17250
17354
  " case $arg in -fmodule-name=*) explicit=1 ;; esac",
@@ -17263,17 +17367,24 @@ module ${moduleName}.Swift {
17263
17367
  " fi",
17264
17368
  " prev=$arg",
17265
17369
  " case $arg in",
17266
- " *.mm|*.cpp|*.cc|*.cxx) cxx=1 ;;",
17370
+ " *.mm) cxx=1 ;;",
17371
+ " *.cpp|*.cc|*.cxx) cxx=1; plainCxx=1 ;;",
17267
17372
  " -fno-cxx-modules) cxxModules=off ;;",
17268
17373
  " -fcxx-modules) cxxModules=on ;;",
17269
17374
  " esac",
17270
17375
  "done",
17271
17376
  // apple clang claims the toolset's cache path in a c++ unit whose modules
17272
- // are off; this clang reports it unused, which -Werror turns into a failure
17377
+ // are off; this clang reports it unused and can still import explicit
17378
+ // swiftpm umbrella maps from inside a namespace in plain c++.
17273
17379
  'if [ -n "$cxx" ] && [ "$cxxModules" = off ]; then',
17274
17380
  ' for arg in "$@"; do',
17275
17381
  " shift",
17276
- ' case $arg in -fmodules-cache-path=*) ;; *) set -- "$@" "$arg" ;; esac',
17382
+ " case $arg in",
17383
+ " -fmodules-cache-path=*) ;;",
17384
+ " -fmodule-map-file=*/.build/*/*.build/module.modulemap)",
17385
+ ' [ -n "$plainCxx" ] || set -- "$@" "$arg" ;;',
17386
+ ' *) set -- "$@" "$arg" ;;',
17387
+ " esac",
17277
17388
  " done",
17278
17389
  "fi",
17279
17390
  'if [ -n "$name" ] && [ -z "$explicit" ]; then',
@@ -18886,8 +18997,15 @@ function compileSwiftProjectOnce(input, options) {
18886
18997
  }
18887
18998
 
18888
18999
  export {
19000
+ privateSwiftRelease,
19001
+ registerSwiftHostCompiler,
19002
+ swiftToolchainBin,
19003
+ swiftEnvironment,
18889
19004
  NATIVE_GRAPH_SDK_VERSION,
19005
+ runtimeDir,
18890
19006
  cacheDir,
19007
+ readActiveRuntime,
19008
+ parseSwiftDistributionLock,
18891
19009
  brotliCompressQ11,
18892
19010
  brotliCompressQ4,
18893
19011
  swiftIcuAsset,