peachsim 0.1.2589 → 0.1.2590

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 (137) 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 +1172 -446
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-6FUOY6FX.mjs → acorn-65FNEARV.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-EAIFG4MQ.mjs → chunk-2GUB5OLB.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-FQQ2DMXS.mjs → chunk-462CWTWI.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-L3OSVIGA.mjs → chunk-4VCRUQ36.mjs} +1178 -452
  30. package/dist-lib/esm-chunks/{chunk-5QWQDXXD.mjs → chunk-5GNGHM5B.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-JLOJZF2Y.mjs → chunk-ADKUIQXX.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-M4KUWGU3.mjs → chunk-BZS5SIYK.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-47K4QPVA.mjs → chunk-EFKDUMB5.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-I22LAVD5.mjs → chunk-GBD26EBV.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-CRIYVOMB.mjs → chunk-HZTK7TP5.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-5EFD2VBY.mjs → chunk-JG4AANWA.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-FMWEI6OI.mjs → chunk-N2II5SRJ.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-33SCXU3Y.mjs → chunk-NZY4GOG5.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-KFHCRS5K.mjs → chunk-OZJ66CXY.mjs} +2 -2
  40. package/dist-lib/esm-chunks/{chunk-464CBA5U.mjs → chunk-RGC2JNCL.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-57FFWABF.mjs → chunk-SLPXTLBK.mjs} +5 -5
  42. package/dist-lib/esm-chunks/{chunk-Y4PV4HZB.mjs → chunk-SRFKOU76.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-3VNUC4DT.mjs → chunk-V5TTEXYO.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-MKSOJCRT.mjs → chunk-WPDY5IAD.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-WQ73RKJY.mjs → chunk-WYDRQRJL.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-BSAAJR25.mjs → chunk-X2EKFONU.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-PUBH3EXI.mjs → chunk-XE3VHAU2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-XTKKROVU.mjs → chunk-YPPH6F77.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-T5QIJTEV.mjs → metro-layout-parser-CRI3GMCM.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-AWTZHPDM.mjs → swift-package-prebuilt-5XDZ2HZZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-MGTJTVKU.mjs → swift-sdk-app-module-6H3G6AXD.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-JABGF3ZR.mjs → swift-sdk-image-WAC7GG2R.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-RJRJ3EFU.mjs → swift-sdk-image-producer-B3L27QTG.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1171 -445
  55. package/dist-lib/expo-swift-metadata.cjs +1 -1
  56. package/dist-lib/expo-swift-metadata.mjs +7 -7
  57. package/dist-lib/home-paths.cjs +1 -1
  58. package/dist-lib/host/bridge-host.cjs +1200 -469
  59. package/dist-lib/host/fetch-proxy-handler.cjs +4 -4
  60. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  61. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  62. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  63. package/dist-lib/host/websocket-proxy.cjs +1 -1
  64. package/dist-lib/index.cjs +1 -1
  65. package/dist-lib/kotlin-host.cjs +1 -1
  66. package/dist-lib/menu.cjs +1 -1
  67. package/dist-lib/menu.mjs +3 -3
  68. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  69. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  70. package/dist-lib/metro-production-bundle.cjs +1 -1
  71. package/dist-lib/metro-production-bundle.mjs +4 -4
  72. package/dist-lib/native-app-identity-project.cjs +2 -2
  73. package/dist-lib/native-app-identity-project.mjs +16 -16
  74. package/dist-lib/native-app-identity.cjs +1 -1
  75. package/dist-lib/native-app-identity.mjs +6 -6
  76. package/dist-lib/native-firebase-metadata.cjs +1 -1
  77. package/dist-lib/native-firebase-metadata.mjs +3 -3
  78. package/dist-lib/pdfium-raster.cjs +1 -1
  79. package/dist-lib/pdfium-raster.mjs +2 -2
  80. package/dist-lib/plist.cjs +1 -1
  81. package/dist-lib/plist.mjs +3 -3
  82. package/dist-lib/profiles.cjs +1 -1
  83. package/dist-lib/public-brand.cjs +1 -1
  84. package/dist-lib/public-origins-lib-esm.json +81 -81
  85. package/dist-lib/public-origins-lib.json +69 -69
  86. package/dist-lib/react-native-host-modules.cjs +1 -1
  87. package/dist-lib/react-native-host-modules.mjs +2 -2
  88. package/dist-lib/reap-browser.cjs +1 -1
  89. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  90. package/dist-lib/sdk.cjs +1 -1
  91. package/dist-lib/sdk.mjs +8 -8
  92. package/dist-lib/skills.cjs +1202 -471
  93. package/dist-lib/swift-compile.cjs +1168 -442
  94. package/dist-lib/swift-compile.mjs +10 -10
  95. package/dist-lib/swift-package.cjs +1 -1
  96. package/dist-lib/swift-package.mjs +3 -3
  97. package/dist-lib/swift-submit.cjs +1 -1
  98. package/dist-lib/swift-submit.mjs +6 -6
  99. package/dist-lib/swift-svg-raster.cjs +1 -1
  100. package/dist-lib/swift-svg-raster.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +1 -1
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/kotlin/sdk.tar.gz +0 -0
  126. package/package.json +1 -1
  127. package/src/swift-guest-compile.ts +2 -2
  128. package/src/swift-guest-dyld-table.ts +9 -2
  129. package/src/swift-guest-image-ledger.ts +403 -208
  130. package/src/swift-guest-link.ts +255 -113
  131. package/src/swift-guest-linked-spans.ts +217 -28
  132. package/src/swift-guest-manifest.ts +24 -13
  133. package/src/swift-guest-projection-storage.ts +6 -8
  134. package/src/swift-guest-projection.ts +7 -6
  135. package/src/swift-sdk-image-map.ts +137 -35
  136. package/src/swift-wasm-prune.ts +263 -85
  137. package/src/swiftGuestImageContract.ts +1 -1
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2589 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2590 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  let __sootsim_import_meta_url = '', __sootsim_import_meta_dirname = '', __sootsim_import_meta_filename = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; __sootsim_import_meta_dirname = __dirname; __sootsim_import_meta_filename = __filename; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
@@ -35538,13 +35538,13 @@ var init_swift_standin_digest = __esm({
35538
35538
  STANDIN_DIGEST_ENTRYPOINTS = ["swift-standins.ts", "swift-objc-compile.ts"];
35539
35539
  SPECIFIER = /from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
35540
35540
  standinSourceDigest = (srcDir = __sootsim_import_meta_dirname) => sourceClosureDigest(srcDir, STANDIN_DIGEST_ENTRYPOINTS);
35541
- STANDIN_SOURCE_DIGEST = true ? "b4ec01293af51e43890fb5aa52c9dc6d240c73b8fe722cdaff952457b08d94ff" : standinSourceDigest();
35541
+ STANDIN_SOURCE_DIGEST = true ? "a3bcdfe9c9957355a59c2c26155470c89a2abb30907aeeaaf1de8463aa74fc8c" : standinSourceDigest();
35542
35542
  }
35543
35543
  });
35544
35544
 
35545
35545
  // src/expo-native-compiler-digest.ts
35546
35546
  function expoNativeCompilerDigestValue() {
35547
- return true ? "bc9bf63858735336bd46e9b34db5ced39d682f7200bbbc3eafbf5470dae0018f" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
35547
+ return true ? "a8b60651de79588c6c5143dd2545ccd8e3b858acd992f46b35ba3de883118ac5" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
35548
35548
  }
35549
35549
  var import_node_crypto12;
35550
35550
  var init_expo_native_compiler_digest = __esm({
@@ -58919,24 +58919,56 @@ function layout(bytes, readData = true, requireExports = true) {
58919
58919
  const code = sections.get(10);
58920
58920
  if (code) {
58921
58921
  let pos = code[0];
58922
- let count;
58923
- [count, pos] = number(bytes, pos);
58922
+ const codeStart = code[0];
58923
+ const codeEnd = code[1];
58924
+ let count = 0;
58925
+ {
58926
+ let shift = 0;
58927
+ for (; ; ) {
58928
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
58929
+ const byte = bytes[pos++];
58930
+ count += (byte & 127) * 2 ** shift;
58931
+ if (!(byte & 128)) break;
58932
+ shift += 7;
58933
+ }
58934
+ }
58924
58935
  for (let i = 0; i < count; i++) {
58925
58936
  const prefix = pos;
58926
- let size2;
58927
- [size2, pos] = number(bytes, pos);
58928
- functionsByCodeOffset.set(prefix - code[0], imports2 + i);
58937
+ let size2 = 0;
58938
+ const b0 = bytes[pos++];
58939
+ if (b0 < 128) {
58940
+ size2 = b0;
58941
+ } else {
58942
+ size2 = b0 & 127;
58943
+ let shift = 7;
58944
+ for (; ; ) {
58945
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
58946
+ const byte = bytes[pos++];
58947
+ size2 += (byte & 127) * 2 ** shift;
58948
+ if (!(byte & 128)) break;
58949
+ shift += 7;
58950
+ }
58951
+ }
58952
+ functionsByCodeOffset.set(prefix - codeStart, imports2 + i);
58929
58953
  if (imports2 + i === startFunction) startup = bytes.subarray(pos, pos + size2);
58930
58954
  pos += size2;
58931
- if (pos > code[1]) throw new Error("invalid wasm code");
58955
+ if (pos > codeEnd) throw new Error("invalid wasm code");
58932
58956
  }
58933
- if (pos !== code[1]) throw new Error("invalid wasm code section");
58957
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
58934
58958
  }
58935
58959
  const functionsByTableSlot = /* @__PURE__ */ new Map();
58936
58960
  const elements = sections.get(9);
58937
58961
  if (elements) {
58938
58962
  let pos = elements[0];
58963
+ const elemEnd = elements[1];
58939
58964
  const read = () => {
58965
+ if (pos < elemEnd) {
58966
+ const b0 = bytes[pos];
58967
+ if (b0 < 128) {
58968
+ pos++;
58969
+ return b0;
58970
+ }
58971
+ }
58940
58972
  const [value, next] = number(bytes, pos);
58941
58973
  pos = next;
58942
58974
  return value;
@@ -58966,7 +58998,7 @@ function layout(bytes, readData = true, requireExports = true) {
58966
58998
  functionsByTableSlot.set(slot, read());
58967
58999
  }
58968
59000
  }
58969
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
59001
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
58970
59002
  }
58971
59003
  const data = [];
58972
59004
  const passive = /* @__PURE__ */ new Map();
@@ -59031,36 +59063,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
59031
59063
  length: segment2.bytes.length
59032
59064
  }));
59033
59065
  }
59034
- function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
59066
+ function isMapSpace(code) {
59067
+ return code === 32 || code >= 9 && code <= 13;
59068
+ }
59069
+ function isMapHex(code) {
59070
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
59071
+ }
59072
+ function mapHexDigit(code) {
59073
+ return code <= 57 ? code - 48 : code - 87;
59074
+ }
59075
+ function* stringLines(text7) {
59076
+ let start = 0;
59077
+ for (let end = text7.indexOf("\n"); end !== -1; end = text7.indexOf("\n", start)) {
59078
+ yield text7.slice(start, end);
59079
+ start = end + 1;
59080
+ }
59081
+ yield text7.slice(start);
59082
+ }
59083
+ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
59035
59084
  const unchanged = before === after;
59036
59085
  const original = layout(before, !unchanged, !importsLayout);
59037
59086
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
59087
+ const collectSymbols = extra?.collectSymbols;
59088
+ const trackedObject = extra?.trackedObject;
59089
+ const trackedObjectOwner = extra?.trackedObjectOwner;
59090
+ const trackedLinearSpans = extra?.trackedLinearSpans;
59091
+ const hasSectionOwners = sectionOwners.size > 0;
59038
59092
  let codeOffset;
59039
59093
  let outputSection = "";
59040
59094
  const codeOwners = /* @__PURE__ */ new Map();
59041
59095
  const pieces = [];
59042
- for (const line of typeof map2 === "string" ? map2.split("\n") : map2) {
59043
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
59044
- if (!match) continue;
59045
- const [, address, offset, size2, indent2, source] = match;
59046
- if (address === "-" && indent2 === " ") {
59047
- outputSection = source;
59048
- if (source === "CODE") codeOffset = parseInt(offset, 16);
59096
+ const lines = typeof map2 === "string" ? stringLines(map2) : map2;
59097
+ for (const line of lines) {
59098
+ const lineLen = line.length;
59099
+ let pos = 0;
59100
+ let onlySpaces = true;
59101
+ while (pos < lineLen) {
59102
+ const ch = line.charCodeAt(pos);
59103
+ if (!isMapSpace(ch)) break;
59104
+ if (ch !== 32) onlySpaces = false;
59105
+ pos++;
59106
+ }
59107
+ const leadingSpaces = pos;
59108
+ if (pos >= lineLen) continue;
59109
+ const addrStart = pos;
59110
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
59111
+ const addrEnd = pos;
59112
+ if (pos >= lineLen) continue;
59113
+ const s1 = pos;
59114
+ while (pos < lineLen) {
59115
+ const ch = line.charCodeAt(pos);
59116
+ if (!isMapSpace(ch)) break;
59117
+ if (ch !== 32) onlySpaces = false;
59118
+ pos++;
59119
+ }
59120
+ if (pos === s1 || pos >= lineLen) continue;
59121
+ const offStart = pos;
59122
+ let offsetVal = 0;
59123
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
59124
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
59125
+ }
59126
+ if (pos === offStart || pos >= lineLen) continue;
59127
+ const s2 = pos;
59128
+ while (pos < lineLen) {
59129
+ const ch = line.charCodeAt(pos);
59130
+ if (!isMapSpace(ch)) break;
59131
+ if (ch !== 32) onlySpaces = false;
59132
+ pos++;
59133
+ }
59134
+ if (pos === s2 || pos >= lineLen) continue;
59135
+ const sizeStart = pos;
59136
+ let sizeVal = 0;
59137
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
59138
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
59139
+ }
59140
+ if (pos === sizeStart || pos >= lineLen) continue;
59141
+ const indentStart = pos;
59142
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
59143
+ const indentLen = pos - indentStart;
59144
+ if (indentLen === 0 || pos >= lineLen) continue;
59145
+ const firstCh = line.charCodeAt(pos);
59146
+ if (isMapSpace(firstCh)) continue;
59147
+ const sourceStart = pos;
59148
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
59149
+ let symEnd = sourceStart + 1;
59150
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
59151
+ collectSymbols.add(line.slice(sourceStart, symEnd));
59152
+ }
59153
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
59154
+ if (isDash && indentLen === 1) {
59155
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
59156
+ outputSection = line.slice(sourceStart);
59157
+ if (outputSection === "CODE") codeOffset = offsetVal;
59049
59158
  continue;
59050
59159
  }
59051
- const separator = source.indexOf(":(");
59160
+ if (sizeVal === 0) continue;
59161
+ const separator = line.indexOf(":(", sourceStart);
59052
59162
  if (separator < 0) continue;
59053
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
59054
- const length = parseInt(size2, 16);
59055
- if (!length) continue;
59056
- if (address !== "-") {
59057
- if (outputSection === "DATA")
59058
- pieces.push({ image, address: parseInt(address, 16), length });
59163
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
59164
+ let hasLineSep = false;
59165
+ for (let i = sourceStart; i < lineLen; i++) {
59166
+ const ch = line.charCodeAt(i);
59167
+ if (ch === 8232 || ch === 8233) {
59168
+ hasLineSep = true;
59169
+ break;
59170
+ }
59171
+ }
59172
+ if (hasLineSep) continue;
59173
+ const objectPath = line.slice(sourceStart, separator);
59174
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
59175
+ if (image === void 0) image = owners.get(objectPath);
59176
+ if (!isDash) {
59177
+ if (outputSection === "DATA") {
59178
+ let addressVal = 0;
59179
+ let allHex = true;
59180
+ for (let i = addrStart; i < addrEnd; i++) {
59181
+ const ch = line.charCodeAt(i);
59182
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
59183
+ else {
59184
+ allHex = false;
59185
+ break;
59186
+ }
59187
+ }
59188
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
59189
+ pieces.push({
59190
+ image,
59191
+ address: addressVal,
59192
+ length: sizeVal,
59193
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
59194
+ });
59195
+ }
59059
59196
  continue;
59060
59197
  }
59061
59198
  if (image === void 0 || outputSection !== "CODE") continue;
59062
59199
  if (codeOffset === void 0) throw new Error("link map has no code section");
59063
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
59200
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
59064
59201
  if (index === void 0) throw new Error("link map function has no wasm body");
59065
59202
  const existing = codeOwners.get(index);
59066
59203
  if (existing !== void 0 && existing !== image)
@@ -59069,12 +59206,23 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
59069
59206
  }
59070
59207
  pieces.sort((a, b) => a.address - b.address);
59071
59208
  const spans = [];
59072
- for (const [index, { image, address, length }] of pieces.entries()) {
59073
- if (image === void 0) continue;
59209
+ for (let index = 0; index < pieces.length; index++) {
59210
+ const piece = pieces[index];
59211
+ const { image, address, length, tracked } = piece;
59212
+ if (image === void 0 && !tracked) continue;
59074
59213
  let next = index + 1;
59075
59214
  while (next < pieces.length && pieces[next].address < address + length) next++;
59076
59215
  const end = pieces[next]?.address ?? address + length;
59077
- spans.push({ image, space: "linear-memory", address, length: end - address });
59216
+ const spanLength = end - address;
59217
+ if (image !== void 0)
59218
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
59219
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
59220
+ trackedLinearSpans.push({
59221
+ image: trackedObjectOwner,
59222
+ space: "linear-memory",
59223
+ address,
59224
+ length: spanLength
59225
+ });
59078
59226
  }
59079
59227
  const optimizedOwners = /* @__PURE__ */ new Map();
59080
59228
  const dataAt = (module2, start, length) => {
@@ -59113,7 +59261,7 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
59113
59261
  throw new Error(`optimization changed linked data at ${span.address}`);
59114
59262
  }
59115
59263
  let previous;
59116
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
59264
+ for (const span of spans) {
59117
59265
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
59118
59266
  throw new Error("linked data belongs to multiple images");
59119
59267
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -59295,6 +59443,20 @@ var init_swift_guest_linked_spans = __esm({
59295
59443
  });
59296
59444
 
59297
59445
  // src/swift-sdk-image-map.ts
59446
+ function isHexChar(code) {
59447
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
59448
+ }
59449
+ function hexDigit(code) {
59450
+ return code <= 57 ? code - 48 : code - 87;
59451
+ }
59452
+ function hasLineBreak(line, from) {
59453
+ if (line.indexOf("\r", from) >= 0) return true;
59454
+ for (let i = from; i < line.length; i++) {
59455
+ const ch = line.charCodeAt(i);
59456
+ if (ch === 8232 || ch === 8233) return true;
59457
+ }
59458
+ return false;
59459
+ }
59298
59460
  function readWasmLinkMap(file, partition) {
59299
59461
  const segments = /* @__PURE__ */ new Map();
59300
59462
  const data = [];
@@ -59302,48 +59464,117 @@ function readWasmLinkMap(file, partition) {
59302
59464
  let kind = "";
59303
59465
  let segment2 = "";
59304
59466
  let previous;
59305
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
59306
59467
  for (const line of guestLinkLines(file)) {
59307
- const symbol2 = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
59308
- if (symbol2) {
59309
- previous?.symbols.push({
59310
- name: symbol2[3],
59311
- address: hex(symbol2[1]),
59312
- size: parseInt(symbol2[2], 16)
59313
- });
59314
- continue;
59468
+ const length = line.length;
59469
+ let pos = 0;
59470
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
59471
+ if (pos >= length) continue;
59472
+ const leadingSpaces = pos;
59473
+ let address = -1;
59474
+ if (line.charCodeAt(pos) === 45) {
59475
+ pos++;
59476
+ } else {
59477
+ const start = pos;
59478
+ let value = 0;
59479
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
59480
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
59481
+ }
59482
+ if (pos === start) continue;
59483
+ address = value;
59315
59484
  }
59316
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
59317
- if (output) {
59318
- kind = output[1];
59485
+ const s1 = pos;
59486
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
59487
+ if (pos === s1 || pos >= length) continue;
59488
+ const offStart = pos;
59489
+ let offset = 0;
59490
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
59491
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
59492
+ }
59493
+ if (pos === offStart) continue;
59494
+ const s2 = pos;
59495
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
59496
+ if (pos === s2 || pos >= length) continue;
59497
+ const sizeStart = pos;
59498
+ let size2 = 0;
59499
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
59500
+ size2 = size2 * 16 + hexDigit(line.charCodeAt(pos++));
59501
+ }
59502
+ if (pos === sizeStart || pos >= length) continue;
59503
+ const indentStart = pos;
59504
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
59505
+ const indent2 = pos - indentStart;
59506
+ if (indent2 === 0 || pos >= length) continue;
59507
+ if (indent2 === 17) {
59508
+ if (previous) {
59509
+ const first = line.charCodeAt(pos);
59510
+ if (first > 32 && !hasLineBreak(line, pos)) {
59511
+ previous.symbols.push({
59512
+ name: line.slice(pos),
59513
+ address,
59514
+ size: size2
59515
+ });
59516
+ }
59517
+ }
59319
59518
  continue;
59320
59519
  }
59321
- if (kind === "DATA") {
59322
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
59323
- if (top) {
59324
- segment2 = top[3];
59325
- segments.set(segment2, { address: hex(top[1]), size: parseInt(top[2], 16) });
59326
- continue;
59520
+ if (indent2 === 1) {
59521
+ let hasWhitespace = false;
59522
+ for (let i = pos; i < length; i++) {
59523
+ const ch = line.charCodeAt(i);
59524
+ if (ch <= 32) {
59525
+ hasWhitespace = true;
59526
+ break;
59527
+ }
59327
59528
  }
59529
+ if (hasWhitespace) continue;
59530
+ if (address < 0 && leadingSpaces > 0) {
59531
+ kind = line.slice(pos);
59532
+ } else if (kind === "DATA" && address >= 0) {
59533
+ segment2 = line.slice(pos);
59534
+ segments.set(segment2, { address, size: size2 });
59535
+ }
59536
+ continue;
59537
+ }
59538
+ if (indent2 === 9 && (kind === "DATA" || kind === "CODE")) {
59539
+ const first = line.charCodeAt(pos);
59540
+ if (first !== 47 && first !== 60) continue;
59541
+ if (hasLineBreak(line, pos)) continue;
59542
+ const name3 = line.slice(pos);
59543
+ let filePath = name3;
59544
+ let section2 = "";
59545
+ if (name3.charCodeAt(name3.length - 1) === 41) {
59546
+ const splitAt = name3.indexOf(":(");
59547
+ if (splitAt >= 0) {
59548
+ filePath = name3.slice(0, splitAt);
59549
+ section2 = name3.slice(splitAt + 2, -1);
59550
+ }
59551
+ }
59552
+ let objectName;
59553
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
59554
+ const open = filePath.lastIndexOf("(");
59555
+ if (open >= 0 && open + 1 < filePath.length - 1) {
59556
+ const close = filePath.indexOf(")", open + 1);
59557
+ if (close === filePath.length - 1) {
59558
+ objectName = filePath.slice(open + 1, -1);
59559
+ }
59560
+ }
59561
+ }
59562
+ if (objectName === void 0) objectName = (0, import_node_path56.basename)(filePath);
59563
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
59564
+ objectName = objectName.replace(/^lib\w*?__/, "");
59565
+ }
59566
+ previous = {
59567
+ inputFile: filePath,
59568
+ segment: segment2,
59569
+ address,
59570
+ offset,
59571
+ size: size2,
59572
+ object: objectName,
59573
+ section: section2,
59574
+ symbols: []
59575
+ };
59576
+ (kind === "DATA" ? data : code).push(previous);
59328
59577
  }
59329
- if (kind !== "DATA" && kind !== "CODE") continue;
59330
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
59331
- if (!input) continue;
59332
- const name3 = input[4];
59333
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
59334
- const path189 = split ? split[1] : name3;
59335
- const member = /\(([^()]+)\)$/.exec(path189);
59336
- previous = {
59337
- inputFile: path189,
59338
- segment: segment2,
59339
- address: hex(input[1]),
59340
- offset: parseInt(input[2], 16),
59341
- size: parseInt(input[3], 16),
59342
- object: (member ? member[1] : (0, import_node_path56.basename)(path189)).replace(/^lib\w*?__/, ""),
59343
- section: split ? split[2] : "",
59344
- symbols: []
59345
- };
59346
- (kind === "DATA" ? data : code).push(previous);
59347
59578
  }
59348
59579
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
59349
59580
  }
@@ -60489,6 +60720,7 @@ function patchSwiftrtObject(src) {
60489
60720
  return buf;
60490
60721
  }
60491
60722
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60723
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
60492
60724
  let pos = 8;
60493
60725
  let numImportFuncs = 0;
60494
60726
  let importsDlsym = false;
@@ -60524,10 +60756,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60524
60756
  let [cnt, cp] = readULEB2(buf, p);
60525
60757
  for (let i = 0; i < cnt; i++) {
60526
60758
  const [mLen, m2] = readULEB2(buf, cp);
60527
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
60759
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
60528
60760
  cp = m2 + mLen;
60529
60761
  const [fLen, f2] = readULEB2(buf, cp);
60530
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
60762
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
60531
60763
  cp = f2 + fLen;
60532
60764
  const kind = buf[cp++];
60533
60765
  if (kind === 0) {
@@ -60607,7 +60839,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60607
60839
  }
60608
60840
  } else if (id === 0) {
60609
60841
  const [nLen, np] = readULEB2(buf, p);
60610
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
60842
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
60611
60843
  const cp = np + nLen;
60612
60844
  if (name3 === "linking") {
60613
60845
  let [, lp] = readULEB2(buf, cp);
@@ -60620,7 +60852,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60620
60852
  let cur = p2;
60621
60853
  for (let i = 0; i < cnt; i++) {
60622
60854
  const [sLen, s2] = readULEB2(buf, cur);
60623
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
60855
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
60624
60856
  cur = s2 + sLen;
60625
60857
  const [, s3] = readULEB2(buf, cur);
60626
60858
  const [fl, s4] = readULEB2(buf, s3);
@@ -60660,7 +60892,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60660
60892
  let sName = "";
60661
60893
  if (!isUndef || isExplicitName) {
60662
60894
  const [sLen, c4] = readULEB2(buf, cur);
60663
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
60895
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
60664
60896
  cur = c4 + sLen;
60665
60897
  } else if (kind === 0) {
60666
60898
  sName = importFuncNames[el] ?? "";
@@ -60676,7 +60908,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60676
60908
  symNames.push(sName);
60677
60909
  } else if (kind === 1) {
60678
60910
  const [sLen, c3] = readULEB2(buf, cur);
60679
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
60911
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
60680
60912
  cur = c3 + sLen;
60681
60913
  if (!isUndef) {
60682
60914
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -60791,9 +61023,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
60791
61023
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
60792
61024
  let ownerSymIdx = -1;
60793
61025
  const topList = segTopSyms.get(lo);
60794
- if (topList) {
60795
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
60796
- if (owner) ownerSymIdx = owner.symIdx;
61026
+ if (topList && topList.length > 0) {
61027
+ let tLo = 0;
61028
+ let tHi = topList.length - 1;
61029
+ while (tLo <= tHi) {
61030
+ const tMid = tLo + tHi >> 1;
61031
+ const top = topList[tMid];
61032
+ if (offInSeg < top.off) {
61033
+ tHi = tMid - 1;
61034
+ } else if (offInSeg >= top.end) {
61035
+ tLo = tMid + 1;
61036
+ } else {
61037
+ ownerSymIdx = top.symIdx;
61038
+ break;
61039
+ }
61040
+ }
60797
61041
  }
60798
61042
  if (ownerSymIdx !== -1) {
60799
61043
  let list2 = symDataRelocs.get(ownerSymIdx);
@@ -61048,54 +61292,151 @@ function localizeDefinedWasmSymbols(bytes, names) {
61048
61292
  return output;
61049
61293
  }
61050
61294
  function guestWasmSymbols(bytes) {
61051
- const object8 = parseWasmObjectBytes("", bytes, false);
61295
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
61296
+ let cur = 8;
61297
+ const readU = () => {
61298
+ const b0 = bytes[cur++];
61299
+ if (b0 < 128) return b0;
61300
+ let res = b0 & 127;
61301
+ let shift = 7;
61302
+ while (true) {
61303
+ const byte = bytes[cur++];
61304
+ res |= (byte & 127) << shift;
61305
+ if ((byte & 128) === 0) return res;
61306
+ shift += 7;
61307
+ }
61308
+ };
61309
+ let importsDlsym = false;
61310
+ const importFuncNames = [];
61311
+ const importFuncModules = [];
61312
+ const importGlobalNames = [];
61313
+ const importTableNames = [];
61314
+ const importEventNames = [];
61315
+ const undefinedSyms = /* @__PURE__ */ new Set();
61316
+ const tags = /* @__PURE__ */ new Set();
61317
+ const globals = /* @__PURE__ */ new Set();
61318
+ const hostImports = /* @__PURE__ */ new Set();
61319
+ const weakUndefined = /* @__PURE__ */ new Set();
61320
+ const defined = /* @__PURE__ */ new Set();
61321
+ const weakDefined = /* @__PURE__ */ new Set();
61322
+ while (cur < bytes.length) {
61323
+ const id = bytes[cur++];
61324
+ const sz = readU();
61325
+ const end = cur + sz;
61326
+ if (id === 2) {
61327
+ const cnt = readU();
61328
+ for (let i = 0; i < cnt; i++) {
61329
+ const mLen = readU();
61330
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
61331
+ cur += mLen;
61332
+ const fLen = readU();
61333
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
61334
+ cur += fLen;
61335
+ const kind = bytes[cur++];
61336
+ if (kind === 0) {
61337
+ readU();
61338
+ importFuncNames.push(fName);
61339
+ importFuncModules.push(mName);
61340
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
61341
+ } else if (kind === 1) {
61342
+ cur++;
61343
+ const fl = readU();
61344
+ readU();
61345
+ if (fl & 1) readU();
61346
+ importTableNames.push(fName);
61347
+ } else if (kind === 2) {
61348
+ const fl = readU();
61349
+ readU();
61350
+ if (fl & 1) readU();
61351
+ } else if (kind === 3) {
61352
+ cur += 2;
61353
+ importGlobalNames.push(fName);
61354
+ } else if (kind === 4) {
61355
+ cur++;
61356
+ readU();
61357
+ importEventNames.push(fName);
61358
+ }
61359
+ }
61360
+ } else if (id === 0) {
61361
+ const nLen = readU();
61362
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
61363
+ cur += nLen;
61364
+ readU();
61365
+ while (cur < end) {
61366
+ const subId = bytes[cur++];
61367
+ const subLen = readU();
61368
+ const subEnd = cur + subLen;
61369
+ if (subId === 8) {
61370
+ const cnt = readU();
61371
+ for (let i = 0; i < cnt; i++) {
61372
+ const kind = bytes[cur++];
61373
+ const fl = readU();
61374
+ const isUndef = (fl & 16) !== 0;
61375
+ const isExplicitName = (fl & 64) !== 0;
61376
+ let sName = "";
61377
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
61378
+ const el = readU();
61379
+ if (!isUndef || isExplicitName) {
61380
+ const sLen = readU();
61381
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
61382
+ cur += sLen;
61383
+ } else if (kind === 0) {
61384
+ sName = importFuncNames[el] ?? "";
61385
+ } else if (kind === 2) {
61386
+ sName = importGlobalNames[el] ?? "";
61387
+ } else if (kind === 4) {
61388
+ sName = importEventNames[el] ?? "";
61389
+ } else if (kind === 5) {
61390
+ sName = importTableNames[el] ?? "";
61391
+ }
61392
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
61393
+ hostImports.add(sName);
61394
+ } else if (kind === 1) {
61395
+ const sLen = readU();
61396
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
61397
+ cur += sLen;
61398
+ if (!isUndef) {
61399
+ readU();
61400
+ readU();
61401
+ readU();
61402
+ }
61403
+ } else if (kind === 3) {
61404
+ readU();
61405
+ }
61406
+ if (sName) {
61407
+ if (isUndef) {
61408
+ undefinedSyms.add(sName);
61409
+ if ((fl & 19) === 17) weakUndefined.add(sName);
61410
+ } else if ((fl & 3) !== 2) {
61411
+ defined.add(sName);
61412
+ if ((fl & 19) === 1) weakDefined.add(sName);
61413
+ }
61414
+ if (kind === 4) tags.add(sName);
61415
+ else if (kind === 2 || kind === 5) globals.add(sName);
61416
+ }
61417
+ }
61418
+ break;
61419
+ }
61420
+ cur = subEnd;
61421
+ }
61422
+ break;
61423
+ }
61424
+ }
61425
+ cur = end;
61426
+ }
61052
61427
  return {
61053
- importsDlsym: object8.importsDlsym,
61054
- undefined: [
61055
- ...new Set(
61056
- object8.symNames.filter(
61057
- (name3, index) => name3 && (object8.symFlags[index] & 16) !== 0
61058
- )
61059
- )
61060
- ],
61428
+ importsDlsym,
61429
+ undefined: [...undefinedSyms],
61061
61430
  // a wasm tag is one module entity unified by name across the link, as the
61062
61431
  // main module owns it for dynamic images, so no image scope applies.
61063
- tags: [
61064
- ...new Set(
61065
- object8.symNames.filter((name3, index) => name3 && object8.symKind[index] === 4)
61066
- )
61067
- ],
61068
- globals: [
61069
- ...new Set(
61070
- object8.symNames.filter(
61071
- (name3, index) => name3 && (object8.symKind[index] === 2 || object8.symKind[index] === 5)
61072
- )
61073
- )
61074
- ],
61432
+ tags: [...tags],
61433
+ globals: [...globals],
61075
61434
  // an undefined function imported from a module other than env is supplied
61076
61435
  // by the host, whatever linker symbol names it.
61077
- hostImports: [...object8.hostImportNames],
61078
- weakUndefined: [
61079
- ...new Set(
61080
- object8.symNames.filter(
61081
- (name3, index) => name3 && (object8.symFlags[index] & 19) === 17
61082
- )
61083
- )
61084
- ],
61085
- defined: [
61086
- ...new Set(
61087
- object8.symNames.filter(
61088
- (name3, index) => name3 && (object8.symFlags[index] & 16) === 0 && (object8.symFlags[index] & 3) !== 2
61089
- )
61090
- )
61091
- ],
61092
- weakDefined: [
61093
- ...new Set(
61094
- object8.symNames.filter(
61095
- (name3, index) => name3 && (object8.symFlags[index] & 19) === 1
61096
- )
61097
- )
61098
- ]
61436
+ hostImports: [...hostImports],
61437
+ weakUndefined: [...weakUndefined],
61438
+ defined: [...defined],
61439
+ weakDefined: [...weakDefined]
61099
61440
  };
61100
61441
  }
61101
61442
  function sdkObjectName(archive, member, ordinal) {
@@ -61612,9 +61953,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
61612
61953
  for (const entry of waiting) tryActivateConformance(entry);
61613
61954
  }
61614
61955
  };
61956
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
61615
61957
  const checkProtocolTrigger = (rawSymName) => {
61616
61958
  if (!rawSymName) return;
61617
61959
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
61960
+ if (checkedProtocolTriggers.has(sName)) return;
61961
+ checkedProtocolTriggers.add(sName);
61618
61962
  if (knownProtocols.has(sName)) {
61619
61963
  markProtocolLive(sName);
61620
61964
  return;
@@ -61647,6 +61991,43 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
61647
61991
  }
61648
61992
  }
61649
61993
  };
61994
+ const typeIndexes = /* @__PURE__ */ new Map();
61995
+ const getTypeIndex = (obj) => {
61996
+ let idx = typeIndexes.get(obj);
61997
+ if (idx) return idx;
61998
+ const mnByPrefix = /* @__PURE__ */ new Map();
61999
+ for (let i = 0; i < obj.symNames.length; i++) {
62000
+ const name3 = obj.symNames[i];
62001
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
62002
+ const pref = name3.slice(0, -2);
62003
+ let list2 = mnByPrefix.get(pref);
62004
+ if (!list2) mnByPrefix.set(pref, list2 = []);
62005
+ list2.push(i);
62006
+ }
62007
+ }
62008
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
62009
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
62010
+ let list2 = objcRegByPrefix.get(p);
62011
+ if (!list2) objcRegByPrefix.set(p, list2 = []);
62012
+ list2.push(lf);
62013
+ }
62014
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
62015
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
62016
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
62017
+ let list2 = objcClassByPrefix.get(p);
62018
+ if (!list2) objcClassByPrefix.set(p, list2 = []);
62019
+ list2.push(classSym.slice("._OBJC_CLASS_".length));
62020
+ }
62021
+ let minPrefLen = Infinity;
62022
+ let maxPrefLen = 0;
62023
+ for (const p of obj.typePrefixesInObj) {
62024
+ if (p.length < minPrefLen) minPrefLen = p.length;
62025
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
62026
+ }
62027
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
62028
+ typeIndexes.set(obj, idx);
62029
+ return idx;
62030
+ };
61650
62031
  const markTypeLive = (obj, pref) => {
61651
62032
  const set2 = liveTypes.get(obj);
61652
62033
  if (set2.has(pref)) return;
@@ -61660,22 +62041,10 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
61660
62041
  const outer = pref.slice(0, n);
61661
62042
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
61662
62043
  }
61663
- const mnName = `${pref}Mn`;
61664
- for (let i = 0; i < obj.symNames.length; i++) {
61665
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
61666
- activateSymbolInObj(obj, i);
61667
- }
61668
- }
61669
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
61670
- if (p === pref) {
61671
- markFuncLive(obj, lf);
61672
- }
61673
- }
61674
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
61675
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
61676
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
61677
- }
61678
- }
62044
+ const idx = getTypeIndex(obj);
62045
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
62046
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
62047
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
61679
62048
  };
61680
62049
  const checkTypeTrigger = (obj, rawSymName) => {
61681
62050
  if (!rawSymName) return;
@@ -61700,11 +62069,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
61700
62069
  }
61701
62070
  }
61702
62071
  }
61703
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
61704
- for (const pref of obj.typePrefixesInObj) {
61705
- if (sName.startsWith(pref)) {
61706
- markTypeLive(obj, pref);
61707
- }
62072
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
62073
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
62074
+ const hi = Math.min(sName.length, maxPrefLen);
62075
+ for (let n = minPrefLen; n <= hi; n++) {
62076
+ const cand = sName.slice(0, n);
62077
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
61708
62078
  }
61709
62079
  }
61710
62080
  };
@@ -61797,7 +62167,8 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
61797
62167
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
61798
62168
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
61799
62169
  for (const name3 of obj.symNames) {
61800
- const loaded4 = name3?.match(/^_c_(\w+)__load$/)?.[1];
62170
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
62171
+ const loaded4 = name3.match(/^_c_(\w+)__load$/)?.[1];
61801
62172
  if (!loaded4) continue;
61802
62173
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded4}`);
61803
62174
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -61945,14 +62316,30 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
61945
62316
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
61946
62317
  const range3 = obj.segPayloadRanges[segIdx];
61947
62318
  if (!range3) return;
62319
+ const [rangeStart, rangeEnd] = range3;
62320
+ if (rangeEnd - rangeStart < 4) return;
61948
62321
  let bytes = objectBytes.get(obj);
61949
62322
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs58.default.readFileSync(obj.file));
61950
- const text7 = bytes.toString("latin1", range3[0], range3[1]);
61951
- for (const match of text7.matchAll(/So(\d+)/g)) {
61952
- const start = match.index + 2 + match[1].length;
61953
- const length = Number(match[1]);
61954
- if (text7[start + length] !== "C") continue;
61955
- const symbol2 = `._OBJC_CLASS_${text7.slice(start, start + length)}`;
62323
+ let pos = rangeStart;
62324
+ while (pos < rangeEnd - 3) {
62325
+ const at = bytes.indexOf("So", pos);
62326
+ if (at < 0 || at >= rangeEnd - 2) break;
62327
+ let digitEnd = at + 2;
62328
+ let length = 0;
62329
+ while (digitEnd < rangeEnd) {
62330
+ const ch = bytes[digitEnd];
62331
+ if (ch < 48 || ch > 57) break;
62332
+ length = length * 10 + (ch - 48);
62333
+ digitEnd++;
62334
+ }
62335
+ if (digitEnd === at + 2) {
62336
+ pos = at + 2;
62337
+ continue;
62338
+ }
62339
+ pos = digitEnd;
62340
+ const nameEnd = digitEnd + length;
62341
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
62342
+ const symbol2 = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
61956
62343
  for (const provider of lazyProviders.get(symbol2) ?? []) {
61957
62344
  eagerDynamicObjects.add(provider);
61958
62345
  extractObject(provider);
@@ -63046,6 +63433,10 @@ var init_nativeDyldTableContract = __esm({
63046
63433
 
63047
63434
  // src/swift-guest-image-ledger.ts
63048
63435
  function readNumber(bytes, position) {
63436
+ if (position < bytes.length) {
63437
+ const first = bytes[position];
63438
+ if (first < 128) return [first, position + 1];
63439
+ }
63049
63440
  let value = 0;
63050
63441
  let shift = 0;
63051
63442
  for (; ; ) {
@@ -63057,6 +63448,7 @@ function readNumber(bytes, position) {
63057
63448
  }
63058
63449
  }
63059
63450
  function encodeNumber(value) {
63451
+ if (value < 128) return Buffer.from([value]);
63060
63452
  const bytes = [];
63061
63453
  do {
63062
63454
  let byte = value % 128;
@@ -63078,6 +63470,9 @@ function encodedString(value) {
63078
63470
  const bytes = Buffer.from(value);
63079
63471
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
63080
63472
  }
63473
+ function isWasmMagic(bytes) {
63474
+ return bytes.length >= 8 && bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115 && bytes[3] === 109 && bytes[4] === 1 && bytes[5] === 0 && bytes[6] === 0 && bytes[7] === 0;
63475
+ }
63081
63476
  function llvmType(value) {
63082
63477
  switch (value) {
63083
63478
  case 127:
@@ -63093,11 +63488,12 @@ function llvmType(value) {
63093
63488
  }
63094
63489
  }
63095
63490
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options2 = {}) {
63096
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
63097
- throw new Error("expected wasm object");
63491
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
63492
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
63098
63493
  const { sdkLookupOnly, sdkProduct } = options2;
63099
63494
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
63100
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
63495
+ const rewrite = binding !== void 0;
63496
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
63101
63497
  const types2 = [];
63102
63498
  const functionTypes = [];
63103
63499
  const definitions = [];
@@ -63111,45 +63507,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63111
63507
  const usedSymbols = /* @__PURE__ */ new Set();
63112
63508
  let position = 8;
63113
63509
  while (position < bytes.length) {
63510
+ const headerStart2 = position;
63114
63511
  const id = bytes[position++];
63115
- const [size2, start] = readNumber(bytes, position);
63512
+ let size2 = 0;
63513
+ if (position < bytes.length && bytes[position] < 128) {
63514
+ size2 = bytes[position++];
63515
+ } else {
63516
+ const [val, next] = readNumber(bytes, position);
63517
+ size2 = val;
63518
+ position = next;
63519
+ }
63520
+ const start = position;
63116
63521
  const end = start + size2;
63117
63522
  if (end > bytes.length) throw new Error("invalid wasm section");
63118
63523
  position = end;
63119
- if (!sections && id > 3) continue;
63120
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size2);
63121
- let offset = 0;
63524
+ if (id > 3) {
63525
+ if (sections) sections.push(bytes.subarray(headerStart2, end));
63526
+ continue;
63527
+ }
63528
+ let offset = start;
63122
63529
  const number4 = () => {
63123
- const [value, next] = readNumber(section2, offset);
63124
- offset = next;
63125
- return value;
63530
+ if (offset < end) {
63531
+ const first = bytes[offset];
63532
+ if (first < 128) {
63533
+ offset++;
63534
+ return first;
63535
+ }
63536
+ }
63537
+ let value = 0;
63538
+ let shift = 0;
63539
+ for (; ; ) {
63540
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
63541
+ const byte = bytes[offset++];
63542
+ value += (byte & 127) * 2 ** shift;
63543
+ if (!(byte & 128)) return value;
63544
+ shift += 7;
63545
+ }
63126
63546
  };
63127
63547
  const string8 = () => {
63128
- const [value, next] = readString(section2, offset);
63129
- offset = next;
63548
+ const length = number4();
63549
+ const strEnd = offset + length;
63550
+ if (strEnd > end) throw new Error("invalid wasm string");
63551
+ const value = rawBuf.toString("utf8", offset, strEnd);
63552
+ offset = strEnd;
63130
63553
  return value;
63131
63554
  };
63555
+ let rewrittenSection;
63132
63556
  if (id === 1) {
63133
63557
  const count = number4();
63134
63558
  for (let i = 0; i < count; i++) {
63135
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
63559
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
63136
63560
  const parameterCount = number4();
63137
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
63138
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
63139
- offset += parameterCount;
63561
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
63562
+ const parameters = new Array(parameterCount);
63563
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
63140
63564
  const resultCount = number4();
63141
- const results = [...section2.subarray(offset, offset + resultCount)];
63142
- if (results.length !== resultCount) throw new Error("invalid wasm type");
63143
- offset += resultCount;
63565
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
63566
+ const results = new Array(resultCount);
63567
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
63144
63568
  types2.push({ parameters, results });
63145
63569
  }
63146
63570
  } else if (id === 2) {
63147
63571
  const count = number4();
63148
- const imports2 = sections ? [encodeNumber(count)] : void 0;
63572
+ const importWriter = rewrite ? new ByteWriter(size2 + 64) : void 0;
63573
+ importWriter?.uleb(count);
63149
63574
  for (let i = 0; i < count; i++) {
63150
63575
  const module2 = string8();
63151
63576
  const name3 = string8();
63152
- const kind = section2[offset++];
63577
+ const kind = bytes[offset++];
63153
63578
  const typeStart = offset;
63154
63579
  let functionType2 = -1;
63155
63580
  if (kind === 0) {
@@ -63157,7 +63582,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63157
63582
  functionTypes.push(functionType2);
63158
63583
  functionImportNames.push(name3);
63159
63584
  } else if (kind === 1) {
63160
- const referenceType = section2[offset++];
63585
+ const referenceType = bytes[offset++];
63161
63586
  if (referenceType !== 112 && referenceType !== 111)
63162
63587
  throw new Error("unsupported table type");
63163
63588
  const flags = number4();
@@ -63176,11 +63601,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63176
63601
  } else throw new Error("unsupported wasm import");
63177
63602
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
63178
63603
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
63179
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
63180
- if (module2 === "env" && kind === 0 && names.has(name3)) {
63181
- const type = types2[functionType2];
63182
- if (!type) throw new Error(`missing import type for ${name3}`);
63183
- functionImports.set(name3, type);
63604
+ if (!rewrite) {
63605
+ if (module2 === "env" && names.has(name3)) {
63606
+ usedSymbols.add(name3);
63607
+ if (kind === 0) {
63608
+ const type = types2[functionType2];
63609
+ if (!type) throw new Error(`missing import type for ${name3}`);
63610
+ functionImports.set(name3, type);
63611
+ }
63612
+ }
63184
63613
  }
63185
63614
  if (isDlsym || isDlerror) {
63186
63615
  const type = types2[functionType2];
@@ -63190,17 +63619,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63190
63619
  }
63191
63620
  if (isDlsym) usesDlsym = true;
63192
63621
  if (isDlerror) usesDlerror = true;
63193
- imports2?.push(
63194
- encodedString(module2),
63195
- encodedString(
63196
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
63197
- ),
63198
- Buffer.from([kind]),
63199
- section2.subarray(typeStart, offset)
63200
- );
63622
+ if (importWriter && binding) {
63623
+ importWriter.string(module2);
63624
+ importWriter.string(
63625
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
63626
+ );
63627
+ importWriter.byte(kind);
63628
+ importWriter.bytes(bytes, typeStart, offset);
63629
+ }
63201
63630
  }
63202
- if (offset !== section2.length) throw new Error("invalid wasm import section");
63203
- if (imports2) section2 = Buffer.concat(imports2);
63631
+ if (offset !== end) throw new Error("invalid wasm import section");
63632
+ if (importWriter) rewrittenSection = importWriter.finish();
63204
63633
  } else if (id === 3) {
63205
63634
  const count = number4();
63206
63635
  for (let i = 0; i < count; i++) functionTypes.push(number4());
@@ -63209,43 +63638,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63209
63638
  if (sectionName === "linking") {
63210
63639
  const version2 = number4();
63211
63640
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
63212
- const subsections = [];
63641
+ const subsections = rewrite ? [] : void 0;
63213
63642
  let objcLoader;
63214
- while (offset < section2.length) {
63215
- const kind = section2[offset++];
63643
+ while (offset < end) {
63644
+ const kind = bytes[offset++];
63216
63645
  const length = number4();
63217
63646
  const stop2 = offset + length;
63218
- if (stop2 > section2.length) throw new Error("invalid linking subsection");
63219
- let content = section2.subarray(offset, stop2);
63220
- if (kind === 7 && !sdkLookupOnly) {
63221
- const groups = [];
63647
+ if (stop2 > end) throw new Error("invalid linking subsection");
63648
+ const contentStart = offset;
63649
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
63650
+ const comdatWriter = new ByteWriter(length + 64);
63222
63651
  const count = number4();
63223
- groups.push(encodeNumber(count));
63652
+ comdatWriter.uleb(count);
63224
63653
  for (let i = 0; i < count; i++) {
63225
63654
  const group = string8();
63226
63655
  const begin = offset;
63227
63656
  number4();
63228
63657
  const members2 = number4();
63229
63658
  for (let member = 0; member < members2 * 2; member++) number4();
63230
- groups.push(
63231
- encodedString(
63232
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
63233
- ),
63234
- section2.subarray(begin, offset)
63659
+ comdatWriter.string(
63660
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
63235
63661
  );
63662
+ comdatWriter.bytes(bytes, begin, offset);
63236
63663
  }
63237
63664
  if (offset !== stop2) throw new Error("invalid comdat subsection");
63238
- content = Buffer.concat(groups);
63239
- }
63240
- if (kind === 8) {
63241
- const entries2 = [];
63242
- const extraEntries = [];
63665
+ const buf = comdatWriter.finish();
63666
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
63667
+ } else if (kind === 8) {
63668
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
63669
+ let extraWriter;
63243
63670
  const count = number4();
63244
- entries2.push(encodeNumber(count));
63245
63671
  let added = 0;
63246
63672
  for (let i = 0; i < count; i++) {
63247
63673
  const begin = offset;
63248
- const symbolKind = section2[offset++];
63674
+ const symbolKind = bytes[offset++];
63249
63675
  const flags = number4();
63250
63676
  const flagsEnd = offset;
63251
63677
  let index = -1;
@@ -63273,25 +63699,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63273
63699
  }
63274
63700
  } else if (symbolKind === 3) number4();
63275
63701
  else throw new Error("unsupported wasm symbol kind");
63276
- if (symbolKind === 0)
63702
+ if (!rewrite && symbolKind === 0)
63277
63703
  functionSymbols[i] = name3 || functionImportNames[index];
63278
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
63704
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
63279
63705
  objcLoader = i;
63280
63706
  }
63281
63707
  const alias = names.get(name3);
63282
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
63283
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
63284
- entries2.push(
63285
- section2.subarray(begin, nameStart),
63286
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
63287
- section2.subarray(nameEnd, offset)
63288
- );
63289
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
63290
- entries2.push(
63291
- section2.subarray(begin, nameStart),
63292
- encodedString(binding(name3)),
63293
- section2.subarray(nameEnd, offset)
63294
- );
63708
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
63709
+ usedSymbols.add(name3);
63710
+ if (entryWriter && binding) {
63711
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
63712
+ entryWriter.bytes(bytes, begin, nameStart);
63713
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
63714
+ entryWriter.bytes(bytes, nameEnd, offset);
63715
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
63716
+ entryWriter.bytes(bytes, begin, nameStart);
63717
+ entryWriter.string(binding(name3));
63718
+ entryWriter.bytes(bytes, nameEnd, offset);
63719
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
63720
+ if (symbolKind !== 0 && symbolKind !== 1)
63721
+ throw new Error(`unsupported symbol ${name3}`);
63722
+ if (preserveCanonical.has(name3)) {
63723
+ entryWriter.bytes(bytes, begin, offset);
63724
+ extraWriter ??= new ByteWriter(256);
63725
+ extraWriter.byte(bytes[begin]);
63726
+ extraWriter.uleb(flags & ~32);
63727
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
63728
+ extraWriter.string(alias);
63729
+ extraWriter.bytes(bytes, nameEnd, offset);
63730
+ added++;
63731
+ } else {
63732
+ entryWriter.bytes(bytes, begin, nameStart);
63733
+ entryWriter.string(alias);
63734
+ entryWriter.bytes(bytes, nameEnd, offset);
63735
+ }
63736
+ } else {
63737
+ entryWriter.bytes(bytes, begin, offset);
63738
+ }
63295
63739
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
63296
63740
  if (symbolKind !== 0 && symbolKind !== 1)
63297
63741
  throw new Error(`unsupported symbol ${name3}`);
@@ -63305,63 +63749,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63305
63749
  hidden: (flags & 4) !== 0,
63306
63750
  type
63307
63751
  });
63308
- if (preserveCanonical.has(name3)) {
63309
- entries2.push(section2.subarray(begin, offset));
63310
- extraEntries.push(
63311
- section2.subarray(begin, begin + 1),
63312
- encodeNumber(flags & ~32),
63313
- section2.subarray(flagsEnd, nameStart),
63314
- encodedString(alias),
63315
- section2.subarray(nameEnd, offset)
63316
- );
63317
- added++;
63318
- } else {
63319
- entries2.push(
63320
- section2.subarray(begin, nameStart),
63321
- encodedString(alias),
63322
- section2.subarray(nameEnd, offset)
63323
- );
63324
- }
63325
- } else entries2.push(section2.subarray(begin, offset));
63752
+ }
63326
63753
  }
63327
63754
  if (offset !== stop2) throw new Error("invalid symbol subsection");
63328
- entries2[0] = encodeNumber(count + added);
63329
- content = Buffer.concat([...entries2, ...extraEntries]);
63755
+ if (entryWriter) {
63756
+ const countBytes = encodeNumber(count + added);
63757
+ const entryBuf = entryWriter.finish();
63758
+ if (extraWriter) {
63759
+ const extraBuf = extraWriter.finish();
63760
+ subsections.push({
63761
+ kind,
63762
+ parts: [countBytes, entryBuf, extraBuf],
63763
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
63764
+ });
63765
+ } else {
63766
+ subsections.push({
63767
+ kind,
63768
+ parts: [countBytes, entryBuf],
63769
+ byteLength: countBytes.length + entryBuf.length
63770
+ });
63771
+ }
63772
+ }
63773
+ } else if (subsections) {
63774
+ subsections.push({
63775
+ kind,
63776
+ parts: [bytes.subarray(contentStart, stop2)],
63777
+ byteLength: length
63778
+ });
63330
63779
  }
63331
63780
  offset = stop2;
63332
- subsections.push({ kind, content });
63333
- }
63334
- const parts2 = [encodedString(sectionName), encodeNumber(version2)];
63335
- for (const subsection of subsections) {
63336
- let content = subsection.content;
63337
- if (subsection.kind === 6 && objcLoader !== void 0) {
63338
- const [count, entriesStart] = readNumber(content, 0);
63339
- const entries2 = [content.subarray(0, entriesStart)];
63340
- let entryStart = entriesStart;
63341
- for (let i = 0; i < count; i++) {
63342
- const [, symbolStart] = readNumber(content, entryStart);
63343
- const [symbol2, entryEnd] = readNumber(content, symbolStart);
63344
- if (symbol2 === objcLoader) entries2.push(encodeNumber(1));
63345
- entries2.push(
63346
- content.subarray(
63347
- symbol2 === objcLoader ? symbolStart : entryStart,
63348
- entryEnd
63349
- )
63350
- );
63351
- entryStart = entryEnd;
63781
+ }
63782
+ if (subsections) {
63783
+ const linkingWriter = new ByteWriter(size2 + 128);
63784
+ linkingWriter.string(sectionName);
63785
+ linkingWriter.uleb(version2);
63786
+ for (const subsection of subsections) {
63787
+ if (subsection.kind === 6 && objcLoader !== void 0) {
63788
+ const content = subsection.parts[0];
63789
+ const [count, entriesStart] = readNumber(content, 0);
63790
+ const initWriter = new ByteWriter(content.length + 16);
63791
+ initWriter.bytes(content, 0, entriesStart);
63792
+ let entryStart = entriesStart;
63793
+ for (let i = 0; i < count; i++) {
63794
+ const [, symbolStart] = readNumber(content, entryStart);
63795
+ const [symbol2, entryEnd] = readNumber(content, symbolStart);
63796
+ if (symbol2 === objcLoader) {
63797
+ initWriter.uleb(1);
63798
+ initWriter.bytes(content, symbolStart, entryEnd);
63799
+ } else {
63800
+ initWriter.bytes(content, entryStart, entryEnd);
63801
+ }
63802
+ entryStart = entryEnd;
63803
+ }
63804
+ if (entryStart !== content.length)
63805
+ throw new Error("invalid init functions subsection");
63806
+ const initBuf = initWriter.finish();
63807
+ linkingWriter.byte(subsection.kind);
63808
+ linkingWriter.uleb(initBuf.length);
63809
+ linkingWriter.bytes(initBuf);
63810
+ } else {
63811
+ linkingWriter.byte(subsection.kind);
63812
+ linkingWriter.uleb(subsection.byteLength);
63813
+ for (const part of subsection.parts) linkingWriter.bytes(part);
63352
63814
  }
63353
- if (entryStart !== content.length)
63354
- throw new Error("invalid init functions subsection");
63355
- content = Buffer.concat(entries2);
63356
- }
63357
- parts2.push(
63358
- Buffer.from([subsection.kind]),
63359
- encodeNumber(content.length),
63360
- content
63361
- );
63815
+ }
63816
+ rewrittenSection = linkingWriter.finish();
63362
63817
  }
63363
- section2 = Buffer.concat(parts2);
63364
- } else if (!sections && sectionName.startsWith("reloc.")) {
63818
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
63365
63819
  number4();
63366
63820
  for (let count = number4(); count > 0; count--) {
63367
63821
  const type = number4();
@@ -63371,18 +63825,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
63371
63825
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
63372
63826
  addressTaken.add(name3);
63373
63827
  }
63374
- if (offset !== section2.length)
63375
- throw new Error(`invalid relocation section ${sectionName}`);
63828
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
63829
+ }
63830
+ }
63831
+ if (sections) {
63832
+ if (rewrittenSection) {
63833
+ sections.push(
63834
+ Buffer.from([id]),
63835
+ encodeNumber(rewrittenSection.length),
63836
+ rewrittenSection
63837
+ );
63838
+ } else {
63839
+ sections.push(bytes.subarray(headerStart2, end));
63376
63840
  }
63377
63841
  }
63378
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
63379
63842
  }
63380
63843
  return {
63381
63844
  bytes: sections ? Buffer.concat(sections) : bytes,
63382
63845
  definitions,
63383
63846
  functionImports,
63384
63847
  usesDlsym,
63385
- usedSymbols: [...usedSymbols],
63848
+ usedSymbols,
63386
63849
  addressTaken: [...addressTaken]
63387
63850
  };
63388
63851
  }
@@ -63471,36 +63934,51 @@ function createGuestImageLedger(input) {
63471
63934
  }
63472
63935
  }
63473
63936
  }
63474
- const nameBytes = /* @__PURE__ */ new Map();
63475
- for (const definition2 of definitions)
63476
- if (!nameBytes.has(definition2.name))
63477
- nameBytes.set(definition2.name, Buffer.from(definition2.name));
63478
- definitions.sort(
63479
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
63480
- );
63937
+ let hasNonAscii = false;
63938
+ for (const definition2 of definitions) {
63939
+ const s = definition2.name;
63940
+ for (let i = 0; i < s.length; i++) {
63941
+ if (s.charCodeAt(i) > 127) {
63942
+ hasNonAscii = true;
63943
+ break;
63944
+ }
63945
+ }
63946
+ if (hasNonAscii) break;
63947
+ }
63948
+ if (hasNonAscii) {
63949
+ const nameBytes = /* @__PURE__ */ new Map();
63950
+ for (const definition2 of definitions)
63951
+ if (!nameBytes.has(definition2.name))
63952
+ nameBytes.set(definition2.name, Buffer.from(definition2.name));
63953
+ definitions.sort(
63954
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
63955
+ );
63956
+ } else {
63957
+ definitions.sort(
63958
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
63959
+ );
63960
+ }
63481
63961
  const preserveCanonical = /* @__PURE__ */ new Set();
63482
63962
  const definitionsByName = Map.groupBy(definitions, (definition2) => definition2.name);
63483
- for (const name3 of input.symbols) {
63963
+ if (symbolIndices.has("__cxa_throw")) {
63964
+ const name3 = "__cxa_throw";
63484
63965
  const matching2 = definitionsByName.get(name3) ?? [];
63485
- if (new Set(matching2.map((definition2) => definition2.image)).size < 2 || !matching2.some((definition2) => definition2.weak))
63486
- continue;
63487
- const weak = matching2.filter((definition2) => definition2.weak);
63488
- const strong = matching2.filter((definition2) => !definition2.weak);
63489
- if (name3 !== "__cxa_throw") continue;
63490
- if (weak.length !== 1 || strong.length !== 1)
63491
- throw new Error(`unsupported weak interposition for ${name3}`);
63492
- const [local] = weak;
63493
- const [runtime] = strong;
63494
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
63495
- throw new Error(`incompatible weak interposition for ${name3}`);
63496
- for (const caller of input.callers) {
63497
- const uses = caller.image === local.image || units.some(
63498
- (unit2) => unit2.image === caller.image && unit2.usedSymbols.includes(name3)
63499
- );
63500
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
63501
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
63966
+ if (new Set(matching2.map((definition2) => definition2.image)).size >= 2 && matching2.some((definition2) => definition2.weak)) {
63967
+ const weak = matching2.filter((definition2) => definition2.weak);
63968
+ const strong = matching2.filter((definition2) => !definition2.weak);
63969
+ if (weak.length !== 1 || strong.length !== 1)
63970
+ throw new Error(`unsupported weak interposition for ${name3}`);
63971
+ const [local] = weak;
63972
+ const [runtime] = strong;
63973
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
63974
+ throw new Error(`incompatible weak interposition for ${name3}`);
63975
+ for (const caller of input.callers) {
63976
+ const uses = caller.image === local.image || units.some((unit2) => unit2.image === caller.image && unit2.usedSymbols.has(name3));
63977
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
63978
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
63979
+ }
63980
+ preserveCanonical.add(name3);
63502
63981
  }
63503
- preserveCanonical.add(name3);
63504
63982
  }
63505
63983
  for (const name3 of [
63506
63984
  "dlsym",
@@ -63512,40 +63990,76 @@ function createGuestImageLedger(input) {
63512
63990
  ])
63513
63991
  preserveCanonical.add(name3);
63514
63992
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
63515
- const bindingsByImage = /* @__PURE__ */ new Map();
63516
- const definitionsByImage = Map.groupBy(definitions, (definition2) => definition2.image);
63993
+ const imageAliases = /* @__PURE__ */ new Map();
63994
+ const imageWeakNames = /* @__PURE__ */ new Map();
63995
+ const singleOwnerByName = /* @__PURE__ */ new Map();
63996
+ for (const definition2 of definitions) {
63997
+ let aliases = imageAliases.get(definition2.image);
63998
+ if (!aliases) imageAliases.set(definition2.image, aliases = /* @__PURE__ */ new Map());
63999
+ const existing = aliases.get(definition2.name);
64000
+ if (existing === void 0) {
64001
+ aliases.set(definition2.name, definition2.alias);
64002
+ if (definition2.weak) {
64003
+ let weak = imageWeakNames.get(definition2.image);
64004
+ if (!weak) imageWeakNames.set(definition2.image, weak = /* @__PURE__ */ new Set());
64005
+ weak.add(definition2.name);
64006
+ }
64007
+ const owner = singleOwnerByName.get(definition2.name);
64008
+ if (owner === void 0)
64009
+ singleOwnerByName.set(definition2.name, {
64010
+ image: definition2.image,
64011
+ alias: definition2.alias
64012
+ });
64013
+ else if (owner !== null && owner.image !== definition2.image)
64014
+ singleOwnerByName.set(definition2.name, null);
64015
+ } else if (!definition2.weak && imageWeakNames.get(definition2.image)?.has(definition2.name)) {
64016
+ aliases.set(definition2.name, definition2.alias);
64017
+ imageWeakNames.get(definition2.image).delete(definition2.name);
64018
+ const owner = singleOwnerByName.get(definition2.name);
64019
+ if (owner && owner.image === definition2.image) owner.alias = definition2.alias;
64020
+ }
64021
+ }
64022
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
63517
64023
  for (const caller of input.callers) {
63518
- const bindings = /* @__PURE__ */ new Map();
63519
- const seen = /* @__PURE__ */ new Map();
63520
64024
  const scope2 = [caller.image, ...caller.next];
63521
64025
  if (input.systemImage !== void 0 && !scope2.includes(input.systemImage))
63522
64026
  scope2.push(input.systemImage);
63523
- for (const image of scope2)
63524
- for (const definition2 of definitionsByImage.get(image) ?? []) {
63525
- const previous = seen.get(definition2.name);
63526
- if (previous?.image === definition2.image) {
63527
- if (previous.weak && !definition2.weak) {
63528
- seen.set(definition2.name, definition2);
63529
- if (!preserveCanonical.has(definition2.name))
63530
- bindings.set(definition2.name, definition2.alias);
63531
- }
63532
- continue;
63533
- }
63534
- if (!previous) {
63535
- seen.set(definition2.name, definition2);
63536
- if (!preserveCanonical.has(definition2.name))
63537
- bindings.set(definition2.name, definition2.alias);
64027
+ const scopeSet = new Set(scope2);
64028
+ const scopeMaps = [];
64029
+ const seenImages = /* @__PURE__ */ new Set();
64030
+ for (const image of scope2) {
64031
+ if (seenImages.has(image)) continue;
64032
+ seenImages.add(image);
64033
+ const aliases = imageAliases.get(image);
64034
+ if (aliases) scopeMaps.push(aliases);
64035
+ }
64036
+ const cache = /* @__PURE__ */ new Map();
64037
+ sharedLookupByImage.set(caller.image, (name3) => {
64038
+ if (preserveCanonical.has(name3)) return void 0;
64039
+ const single = singleOwnerByName.get(name3);
64040
+ if (single === void 0) return void 0;
64041
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
64042
+ const hit = cache.get(name3);
64043
+ if (hit !== void 0) return hit ?? void 0;
64044
+ for (const aliases of scopeMaps) {
64045
+ const alias = aliases.get(name3);
64046
+ if (alias !== void 0) {
64047
+ cache.set(name3, alias);
64048
+ return alias;
63538
64049
  }
63539
64050
  }
63540
- bindingsByImage.set(caller.image, bindings);
64051
+ cache.set(name3, null);
64052
+ return void 0;
64053
+ });
63541
64054
  }
63542
64055
  const startup = /* @__PURE__ */ new Map();
64056
+ const unitsByPath = new Map(units.map((unit2) => [unit2.object.path, unit2]));
63543
64057
  for (const binding of input.directBindings ?? []) {
63544
- const unit2 = units.find(({ object: object8 }) => object8.path === binding.object);
64058
+ const unit2 = unitsByPath.get(binding.object);
63545
64059
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
63546
64060
  (definition2) => definition2.object === binding.providerObject && definition2.image === binding.providerImage
63547
64061
  );
63548
- if (!unit2 || !unit2.usedSymbols.includes(binding.symbol) || matches.length !== 1)
64062
+ if (!unit2 || !unit2.usedSymbols.has(binding.symbol) || matches.length !== 1)
63549
64063
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
63550
64064
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
63551
64065
  if (bindings.has(binding.symbol))
@@ -63586,11 +64100,11 @@ function createGuestImageLedger(input) {
63586
64100
  }
63587
64101
  }
63588
64102
  const objects = units.map(({ image, object: object8, aliases, functionImports }) => {
63589
- const shared = bindingsByImage.get(image);
64103
+ const shared = sharedLookupByImage.get(image);
63590
64104
  const own2 = startup.get(object8.path);
63591
64105
  const bindings = new Map(own2);
63592
64106
  const weak = input.sdkWeakReferences?.get(object8.path);
63593
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
64107
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
63594
64108
  for (const [name3, type] of functionImports) {
63595
64109
  const alias = binding(name3);
63596
64110
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -63855,7 +64369,7 @@ function nameGuestImageAliases(wasm, symbols) {
63855
64369
  }
63856
64370
  return Buffer.concat(parts2);
63857
64371
  }
63858
- var import_node_crypto32, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
64372
+ var import_node_crypto32, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
63859
64373
  var init_swift_guest_image_ledger = __esm({
63860
64374
  "src/swift-guest-image-ledger.ts"() {
63861
64375
  "use strict";
@@ -63863,6 +64377,57 @@ var init_swift_guest_image_ledger = __esm({
63863
64377
  init_nativeWasmContract();
63864
64378
  init_swift_sdk_image_wasm();
63865
64379
  init_swiftSdkLinkContract();
64380
+ ByteWriter = class {
64381
+ buf;
64382
+ pos = 0;
64383
+ constructor(initialCapacity = 256) {
64384
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
64385
+ }
64386
+ ensure(extra) {
64387
+ const needed = this.pos + extra;
64388
+ if (needed <= this.buf.length) return;
64389
+ let next = this.buf.length * 2;
64390
+ while (next < needed) next *= 2;
64391
+ const grown = Buffer.allocUnsafe(next);
64392
+ this.buf.copy(grown, 0, 0, this.pos);
64393
+ this.buf = grown;
64394
+ }
64395
+ byte(value) {
64396
+ this.ensure(1);
64397
+ this.buf[this.pos++] = value;
64398
+ }
64399
+ uleb(value) {
64400
+ this.ensure(10);
64401
+ let pos = this.pos;
64402
+ const buf = this.buf;
64403
+ do {
64404
+ let byte = value % 128;
64405
+ value = Math.floor(value / 128);
64406
+ if (value) byte |= 128;
64407
+ buf[pos++] = byte;
64408
+ } while (value);
64409
+ this.pos = pos;
64410
+ }
64411
+ bytes(source, start = 0, end = source.length) {
64412
+ const len = end - start;
64413
+ if (len <= 0) return;
64414
+ this.ensure(len);
64415
+ this.buf.set(source.subarray(start, end), this.pos);
64416
+ this.pos += len;
64417
+ }
64418
+ string(value) {
64419
+ const len = Buffer.byteLength(value, "utf8");
64420
+ this.uleb(len);
64421
+ if (len > 0) {
64422
+ this.ensure(len);
64423
+ this.buf.write(value, this.pos, len, "utf8");
64424
+ this.pos += len;
64425
+ }
64426
+ }
64427
+ finish() {
64428
+ return this.buf.subarray(0, this.pos);
64429
+ }
64430
+ };
63866
64431
  OBJC_INIT_RECORD = ".objc_init";
63867
64432
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
63868
64433
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -64480,8 +65045,11 @@ function moveGuestDyldTable(map2, wasm, symbols, bindingValues = /* @__PURE__ */
64480
65045
  function guestDyldValueRange(map2) {
64481
65046
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
64482
65047
  let found2;
64483
- for (const line of map2.split("\n")) {
64484
- if (!line.endsWith(suffix)) continue;
65048
+ for (let at = map2.indexOf(suffix); at !== -1; at = map2.indexOf(suffix, at + suffix.length)) {
65049
+ const lineEnd = at + suffix.length;
65050
+ if (lineEnd < map2.length && map2.charCodeAt(lineEnd) !== 10) continue;
65051
+ const lineStart = map2.lastIndexOf("\n", at) + 1;
65052
+ const line = map2.slice(lineStart, lineEnd);
64485
65053
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
64486
65054
  if (!match) throw new Error("unreadable dyld values map line");
64487
65055
  if (found2) throw new Error("link map has several dyld value sections");
@@ -64534,7 +65102,7 @@ var init_swift_guest_link_plan = __esm({
64534
65102
  });
64535
65103
 
64536
65104
  // src/swift-guest-manifest.ts
64537
- function selectedGuestManifestInputs(plan, selection, identities) {
65105
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
64538
65106
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
64539
65107
  const archives = /* @__PURE__ */ new Map();
64540
65108
  const images = /* @__PURE__ */ new Map();
@@ -64545,19 +65113,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
64545
65113
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
64546
65114
  let bytes;
64547
65115
  let memberIdentity = null;
64548
- if (item.member === null) bytes = (0, import_node_fs60.readFileSync)(item.artifact);
64549
- else {
64550
- let members2 = archives.get(item.artifact);
64551
- if (!members2) {
64552
- members2 = readArMembers((0, import_node_fs60.readFileSync)(item.artifact));
64553
- archives.set(item.artifact, members2);
65116
+ if (item.member === null) {
65117
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs60.readFileSync)(item.artifact);
65118
+ } else {
65119
+ if (readSelected) {
65120
+ bytes = readSelected(item);
65121
+ } else {
65122
+ let members2 = archives.get(item.artifact);
65123
+ if (!members2) {
65124
+ members2 = /* @__PURE__ */ new Map();
65125
+ for (const member of readArMembers((0, import_node_fs60.readFileSync)(item.artifact))) {
65126
+ let list2 = members2.get(member.name);
65127
+ if (!list2) members2.set(member.name, list2 = []);
65128
+ list2.push(member.bytes);
65129
+ }
65130
+ archives.set(item.artifact, members2);
65131
+ }
65132
+ const matching2 = members2.get(item.member);
65133
+ if (!matching2 || matching2.length !== 1)
65134
+ throw new Error(
65135
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
65136
+ );
65137
+ bytes = matching2[0];
64554
65138
  }
64555
- const matching2 = members2.filter((member) => member.name === item.member);
64556
- if (matching2.length !== 1)
64557
- throw new Error(
64558
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
64559
- );
64560
- bytes = matching2[0].bytes;
64561
65139
  const origin = artifact.memberOrigins?.get(item.member);
64562
65140
  if (artifact.memberOrigins && !origin)
64563
65141
  throw new Error(
@@ -64649,7 +65227,7 @@ var init_swift_guest_manifest = __esm({
64649
65227
  function isSwiftGuestImageManifest(value) {
64650
65228
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
64651
65229
  const text7 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
64652
- const name3 = (value2) => text7(value2) && new TextEncoder().encode(value2).length <= 16;
65230
+ const name3 = (value2) => text7(value2) && Buffer.byteLength(value2, "utf8") <= 16;
64653
65231
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
64654
65232
  if (!isRecord(value) || value.version !== 1 || !text7(value.id) || !text7(value.installName) || value.resourceBundlePath !== void 0 && !isSwiftBundlePath(value.resourceBundlePath) || value.fileType !== "executable" && value.fileType !== "dylib" || !isRecord(value.target) || value.target.triple !== SWIFT_WASM_TRIPLE || value.target.pointerWidth !== 64 || value.target.byteOrder !== "little" || value.target.cpuType !== -1 || value.target.cpuSubtype !== 0 || typeof value.inputsSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.inputsSha256) || value.uuid !== value.inputsSha256.slice(0, 32) || !isRecord(value.buildVersion) || !uint(value.buildVersion.platform, 4294967295) || !version2(value.buildVersion.minimum) || !version2(value.buildVersion.sdk) || !Array.isArray(value.regions))
64655
65233
  return false;
@@ -64963,27 +65541,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
64963
65541
  function finalizeGuestProjectionStorage(options2) {
64964
65542
  const owner = options2.owners.get(options2.projectionObject);
64965
65543
  if (owner === void 0) throw new Error("guest projection object has no image owner");
65544
+ const ranges = [];
64966
65545
  const spans = guestLinkedSpans(
64967
65546
  options2.map,
64968
65547
  options2.linked,
64969
65548
  options2.optimized,
64970
65549
  options2.owners,
64971
65550
  options2.sectionOwners,
64972
- options2.sdkSpans !== void 0
65551
+ options2.sdkSpans !== void 0,
65552
+ {
65553
+ trackedObject: options2.projectionObject,
65554
+ trackedObjectOwner: owner,
65555
+ trackedLinearSpans: ranges
65556
+ }
64973
65557
  );
64974
65558
  const images = planGuestProjectionRegions(
64975
65559
  options2.reserved.images,
64976
65560
  options2.reserved.capacities,
64977
65561
  options2.sdkSpans ? [...spans, ...options2.sdkSpans] : spans
64978
65562
  );
64979
- const ranges = guestLinkedSpans(
64980
- options2.map,
64981
- options2.linked,
64982
- options2.optimized,
64983
- /* @__PURE__ */ new Map([[options2.projectionObject, owner]]),
64984
- void 0,
64985
- options2.sdkSpans !== void 0
64986
- ).filter((span) => span.space === "linear-memory");
64987
65563
  const result = Buffer.from(options2.optimized);
64988
65564
  const data = guestWasmDataSegments(options2.optimized, options2.sdkSpans === void 0);
64989
65565
  const locations = /* @__PURE__ */ new Map();
@@ -66051,7 +66627,7 @@ function occurrences(plan, args) {
66051
66627
  throw new Error("guest plan does not match linker inputs");
66052
66628
  return found2;
66053
66629
  }
66054
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
66630
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
66055
66631
  const rows = whyExtract.trimEnd().split("\n");
66056
66632
  if (rows.shift() !== "reference extracted symbol")
66057
66633
  throw new Error("invalid wasm-ld extraction report");
@@ -66066,8 +66642,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
66066
66642
  for (const file of extracted)
66067
66643
  if (!traced.has(file))
66068
66644
  throw new Error(`extracted guest input is absent from link trace ${file}`);
66645
+ const foundOccurrences = occurrences(plan, args);
66646
+ const archivePaths = /* @__PURE__ */ new Set();
66647
+ for (const { artifact } of foundOccurrences)
66648
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
66649
+ const tracedMembers = /* @__PURE__ */ new Map();
66650
+ if (archivePaths.size > 0) {
66651
+ const archivePrefixes = [...archivePaths].map(
66652
+ (archivePath) => [archivePath, `${archivePath}(`]
66653
+ );
66654
+ for (const item of traced) {
66655
+ if (!item.endsWith(")")) continue;
66656
+ const open = item.lastIndexOf("(");
66657
+ if (open > 0) {
66658
+ const archivePath = item.slice(0, open);
66659
+ if (archivePaths.has(archivePath)) {
66660
+ let list2 = tracedMembers.get(archivePath);
66661
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
66662
+ list2.push(item.slice(open + 1, -1));
66663
+ continue;
66664
+ }
66665
+ }
66666
+ for (const [archivePath, prefix] of archivePrefixes) {
66667
+ if (item.startsWith(prefix)) {
66668
+ let list2 = tracedMembers.get(archivePath);
66669
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
66670
+ list2.push(item.slice(prefix.length, -1));
66671
+ }
66672
+ }
66673
+ }
66674
+ }
66069
66675
  const result = [];
66070
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
66676
+ for (const { artifact, lazy, whole } of foundOccurrences) {
66071
66677
  if (artifact.kind === "object") {
66072
66678
  if (!lazy && !traced.has(artifact.path))
66073
66679
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -66075,15 +66681,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
66075
66681
  result.push({ artifact: artifact.path, member: null });
66076
66682
  continue;
66077
66683
  }
66078
- const prefix = `${artifact.path}(`;
66079
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
66080
- const members2 = readArMembers(import_node_fs63.default.readFileSync(artifact.path));
66684
+ const names = tracedMembers.get(artifact.path) ?? [];
66685
+ const nameSet = new Set(names);
66686
+ let members2 = archiveCache?.get(artifact.path);
66687
+ if (!members2) {
66688
+ members2 = readArMembers(import_node_fs63.default.readFileSync(artifact.path));
66689
+ archiveCache?.set(artifact.path, members2);
66690
+ }
66691
+ const memberCounts = /* @__PURE__ */ new Map();
66081
66692
  for (const member of members2) {
66082
- if (whole || names.includes(member.name))
66693
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
66694
+ if (whole || nameSet.has(member.name))
66083
66695
  result.push({ artifact: artifact.path, member: member.name });
66084
66696
  }
66085
66697
  for (const name3 of names)
66086
- if (members2.filter((member) => member.name === name3).length !== 1)
66698
+ if (memberCounts.get(name3) !== 1)
66087
66699
  throw new Error(
66088
66700
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
66089
66701
  );
@@ -66160,14 +66772,25 @@ function linkGuestImages(options2) {
66160
66772
  }
66161
66773
  const archives = /* @__PURE__ */ new Map();
66162
66774
  const memberBytes = /* @__PURE__ */ new Map();
66775
+ const objectBytes = /* @__PURE__ */ new Map();
66163
66776
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
66164
66777
  const providerSymbol = "__peach_dlsym_from_image";
66165
66778
  const readSelected = (item) => {
66166
- if (item.member === null) return import_node_fs63.default.readFileSync(item.artifact);
66779
+ if (item.member === null) {
66780
+ let bytes = objectBytes.get(item.artifact);
66781
+ if (!bytes) {
66782
+ bytes = import_node_fs63.default.readFileSync(item.artifact);
66783
+ objectBytes.set(item.artifact, bytes);
66784
+ }
66785
+ return bytes;
66786
+ }
66167
66787
  let byName2 = memberBytes.get(item.artifact);
66168
66788
  if (!byName2) {
66169
- const members2 = readArMembers(import_node_fs63.default.readFileSync(item.artifact));
66170
- archives.set(item.artifact, members2);
66789
+ let members2 = archives.get(item.artifact);
66790
+ if (!members2) {
66791
+ members2 = readArMembers(import_node_fs63.default.readFileSync(item.artifact));
66792
+ archives.set(item.artifact, members2);
66793
+ }
66171
66794
  byName2 = /* @__PURE__ */ new Map();
66172
66795
  for (const member of members2)
66173
66796
  if (!byName2.has(member.name))
@@ -66191,7 +66814,13 @@ function linkGuestImages(options2) {
66191
66814
  `--why-extract=${whyPath}`,
66192
66815
  `--Map=${mapPath}`
66193
66816
  ]);
66194
- return selectedGuestLinkInputs(plan, args, import_node_fs63.default.readFileSync(whyPath, "utf8"), trace);
66817
+ return selectedGuestLinkInputs(
66818
+ plan,
66819
+ args,
66820
+ import_node_fs63.default.readFileSync(whyPath, "utf8"),
66821
+ trace,
66822
+ archives
66823
+ );
66195
66824
  };
66196
66825
  const needsProvider = (item) => {
66197
66826
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -66231,7 +66860,7 @@ function linkGuestImages(options2) {
66231
66860
  )
66232
66861
  ]);
66233
66862
  const originalOwnership = identity2(plan);
66234
- const resolved = options2.resolvePlan(selected, plan);
66863
+ const resolved = options2.resolvePlan(selected, plan, readSelected);
66235
66864
  if (identity2(resolved) !== originalOwnership)
66236
66865
  throw new Error("resolved guest scopes changed input ownership");
66237
66866
  plan = resolved;
@@ -66285,6 +66914,7 @@ function linkGuestImages(options2) {
66285
66914
  }
66286
66915
  }
66287
66916
  let discoveryRegions;
66917
+ let liveSymbols;
66288
66918
  if (discoveryProjection && options2.projection) {
66289
66919
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options2.projection.image]]);
66290
66920
  for (const item of selected)
@@ -66293,10 +66923,15 @@ function linkGuestImages(options2) {
66293
66923
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
66294
66924
  );
66295
66925
  const wasm = import_node_fs63.default.readFileSync(discovery);
66926
+ liveSymbols = /* @__PURE__ */ new Set();
66296
66927
  discoveryRegions = guestProjectionRegionCounts(
66297
66928
  plan.images.length,
66298
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
66929
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
66930
+ collectSymbols: liveSymbols
66931
+ })
66299
66932
  );
66933
+ } else {
66934
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
66300
66935
  }
66301
66936
  const ledger = createGuestImageLedger({
66302
66937
  images: plan.images.map((image) => ({
@@ -66305,7 +66940,7 @@ function linkGuestImages(options2) {
66305
66940
  })),
66306
66941
  callers: plan.callers,
66307
66942
  symbols: plan.symbols,
66308
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
66943
+ liveSymbols,
66309
66944
  commandLineSymbols: commandLineSymbols(args),
66310
66945
  directBindings: plan.directBindings,
66311
66946
  registerAppTables: sdkCallers !== void 0,
@@ -66437,7 +67072,8 @@ function linkGuestImages(options2) {
66437
67072
  const selectedInputs = selectedGuestManifestInputs(
66438
67073
  plan,
66439
67074
  selected,
66440
- projection.identities
67075
+ projection.identities,
67076
+ readSelected
66441
67077
  );
66442
67078
  const images = projection.images.map(
66443
67079
  (image) => createGuestImageManifest({
@@ -66447,6 +67083,9 @@ function linkGuestImages(options2) {
66447
67083
  regions: []
66448
67084
  })
66449
67085
  );
67086
+ objectBytes.clear();
67087
+ memberBytes.clear();
67088
+ archives.clear();
66450
67089
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
66451
67090
  const regionsBefore = discoveryRegions;
66452
67091
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs63.default.readFileSync(ledgerObject)], 0);
@@ -66540,10 +67179,47 @@ ${changed2.join("\n")}`
66540
67179
  }
66541
67180
  function linkedMapSymbols(lines) {
66542
67181
  const names = /* @__PURE__ */ new Set();
66543
- const symbol2 = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
66544
67182
  for (const line of lines) {
66545
- const match = symbol2.exec(line);
66546
- if (match) names.add(match[1]);
67183
+ const length = line.length;
67184
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
67185
+ let pos = 1;
67186
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
67187
+ const c1 = pos;
67188
+ while (pos < length) {
67189
+ const ch = line.charCodeAt(pos);
67190
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
67191
+ pos++;
67192
+ }
67193
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
67194
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
67195
+ const c2 = pos;
67196
+ while (pos < length) {
67197
+ const ch = line.charCodeAt(pos);
67198
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
67199
+ pos++;
67200
+ }
67201
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
67202
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
67203
+ const c3 = pos;
67204
+ while (pos < length) {
67205
+ const ch = line.charCodeAt(pos);
67206
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
67207
+ pos++;
67208
+ }
67209
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
67210
+ const sStart = pos;
67211
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
67212
+ if (pos - sStart < 9 || pos >= length) continue;
67213
+ const first = line.charCodeAt(pos);
67214
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
67215
+ continue;
67216
+ let end = pos + 1;
67217
+ while (end < length) {
67218
+ const ch = line.charCodeAt(end);
67219
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
67220
+ end++;
67221
+ }
67222
+ names.add(line.slice(pos, end));
66547
67223
  }
66548
67224
  return names;
66549
67225
  }
@@ -66642,7 +67318,7 @@ function discoverGuestLinkInputs(options2) {
66642
67318
  import_node_fs63.default.mkdirSync(options2.directory, { recursive: true });
66643
67319
  const why = import_node_path61.default.join(options2.directory, "preselection-why.txt");
66644
67320
  const response = import_node_path61.default.join(options2.directory, "preselection.rsp");
66645
- const output = import_node_path61.default.join(options2.directory, "preselection.wasm");
67321
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path61.default.join(options2.directory, "preselection.wasm");
66646
67322
  const flags = [
66647
67323
  ...withOutput(args, output, true),
66648
67324
  ...options2.objects,
@@ -66740,7 +67416,7 @@ function prepareGuestRuntimeInputs(options2) {
66740
67416
  });
66741
67417
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
66742
67418
  }
66743
- function selectedGuestSymbolInputs(plan, selected) {
67419
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
66744
67420
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
66745
67421
  const archives = /* @__PURE__ */ new Map();
66746
67422
  const symbols = /* @__PURE__ */ new Set();
@@ -66756,22 +67432,27 @@ function selectedGuestSymbolInputs(plan, selected) {
66756
67432
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
66757
67433
  let bytes;
66758
67434
  let name3 = item.artifact;
66759
- if (item.member === null) bytes = import_node_fs63.default.readFileSync(item.artifact);
66760
- else {
66761
- let members2 = archives.get(item.artifact);
66762
- if (!members2) {
66763
- members2 = Map.groupBy(
66764
- readArMembers(import_node_fs63.default.readFileSync(item.artifact)),
66765
- (member) => member.name
66766
- );
66767
- archives.set(item.artifact, members2);
67435
+ if (item.member === null) {
67436
+ bytes = readSelected ? readSelected(item) : import_node_fs63.default.readFileSync(item.artifact);
67437
+ } else {
67438
+ if (readSelected) {
67439
+ bytes = readSelected(item);
67440
+ } else {
67441
+ let members2 = archives.get(item.artifact);
67442
+ if (!members2) {
67443
+ members2 = Map.groupBy(
67444
+ readArMembers(import_node_fs63.default.readFileSync(item.artifact)),
67445
+ (member) => member.name
67446
+ );
67447
+ archives.set(item.artifact, members2);
67448
+ }
67449
+ const matching2 = members2.get(item.member) ?? [];
67450
+ if (matching2.length !== 1)
67451
+ throw new Error(
67452
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
67453
+ );
67454
+ bytes = matching2[0].bytes;
66768
67455
  }
66769
- const matching2 = members2.get(item.member) ?? [];
66770
- if (matching2.length !== 1)
66771
- throw new Error(
66772
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
66773
- );
66774
- bytes = matching2[0].bytes;
66775
67456
  name3 += `(${item.member})`;
66776
67457
  }
66777
67458
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -66784,9 +67465,9 @@ function selectedGuestSymbolInputs(plan, selected) {
66784
67465
  for (const symbol2 of names.tags) tags.add(symbol2);
66785
67466
  for (const symbol2 of names.defined) {
66786
67467
  definitions.add(symbol2);
66787
- const objects = definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
67468
+ let objects = definitionObjects.get(symbol2);
67469
+ if (!objects) definitionObjects.set(symbol2, objects = /* @__PURE__ */ new Set());
66788
67470
  objects.add(name3);
66789
- definitionObjects.set(symbol2, objects);
66790
67471
  }
66791
67472
  }
66792
67473
  return {
@@ -66807,7 +67488,7 @@ function verifyGuestSymbolScopes(options2) {
66807
67488
  if (!symbols.length) return { bindings: [], directBindings: [] };
66808
67489
  import_node_fs63.default.mkdirSync(options2.directory, { recursive: true });
66809
67490
  const response = import_node_path61.default.join(options2.directory, "scope-trace.rsp");
66810
- const output = import_node_path61.default.join(options2.directory, "scope-trace.wasm");
67491
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path61.default.join(options2.directory, "scope-trace.wasm");
66811
67492
  const args = [
66812
67493
  ...withOutput(normalizedGuestLinkArgs(options2.args), output, true),
66813
67494
  ...options2.objects,
@@ -66825,55 +67506,76 @@ function verifyGuestSymbolScopes(options2) {
66825
67506
  import_node_fs63.default.closeSync(traceOutput);
66826
67507
  }
66827
67508
  const records = /* @__PURE__ */ new Map();
66828
- const consume = (line) => {
66829
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
66830
- if (!match) return;
66831
- const [, object8, kind, symbol2] = match;
66832
- if (!requested.has(symbol2)) return;
66833
- if (options2.hostImports.has(symbol2)) return;
66834
- const record6 = records.get(symbol2) ?? {
66835
- references: /* @__PURE__ */ new Map(),
66836
- providers: /* @__PURE__ */ new Map(),
66837
- physicalModule: false
66838
- };
67509
+ for (const line of guestLinkLines(tracePath)) {
67510
+ const refSep = line.lastIndexOf(": reference to ");
67511
+ const defSep = line.lastIndexOf(": definition of ");
67512
+ if (refSep < 0 && defSep < 0) continue;
67513
+ const isRef = refSep > defSep;
67514
+ const sep4 = isRef ? refSep : defSep;
67515
+ const symbol2 = line.slice(sep4 + (isRef ? 15 : 16));
67516
+ if (!requested.has(symbol2) || options2.hostImports.has(symbol2)) continue;
67517
+ let record6 = records.get(symbol2);
67518
+ if (!record6) {
67519
+ record6 = {
67520
+ references: /* @__PURE__ */ new Map(),
67521
+ providers: /* @__PURE__ */ new Map(),
67522
+ physicalModule: false
67523
+ };
67524
+ records.set(symbol2, record6);
67525
+ }
67526
+ const object8 = line.slice(0, sep4);
66839
67527
  if (object8 === "<internal>") {
66840
- if (kind === "definition of") record6.physicalModule = true;
67528
+ if (!isRef) record6.physicalModule = true;
66841
67529
  } else {
66842
67530
  const image = options2.owners.get(object8);
66843
67531
  if (image === void 0)
66844
67532
  throw new Error(`traced guest object has no owner ${object8}`);
66845
- (kind === "reference to" ? record6.references : record6.providers).set(
66846
- object8,
66847
- image
66848
- );
67533
+ (isRef ? record6.references : record6.providers).set(object8, image);
66849
67534
  }
66850
- records.set(symbol2, record6);
66851
- };
66852
- for (const line of guestLinkLines(tracePath)) consume(line);
67535
+ }
66853
67536
  const callers = new Map(options2.callers.map((caller) => [caller.image, caller.next]));
67537
+ const callerSets = new Map(
67538
+ options2.callers.map((caller) => [caller.image, new Set(caller.next)])
67539
+ );
67540
+ const rootScope = callerSets.get(0);
66854
67541
  const result = [];
66855
67542
  const directBindings = [];
66856
67543
  for (const symbol2 of symbols) {
66857
67544
  const record6 = records.get(symbol2);
66858
67545
  if (!record6 || !record6.references.size) continue;
66859
67546
  if (!record6.providers.size && options2.hostImports.has(symbol2)) continue;
66860
- const startupReferences = [...record6.references].filter(
66861
- ([object8]) => options2.startupObjects.has(object8) && options2.weakReferences.get(object8)?.has(symbol2)
66862
- );
66863
- const otherReferences = [...record6.references].filter(
66864
- ([object8]) => !startupReferences.some(([startup]) => startup === object8)
66865
- );
67547
+ const startupReferences = [];
67548
+ const otherReferences = [];
67549
+ let allWeakRefs = true;
67550
+ for (const [object8, caller] of record6.references) {
67551
+ const isWeakRef = options2.weakReferences.get(object8)?.has(symbol2) === true;
67552
+ if (!isWeakRef) allWeakRefs = false;
67553
+ if (isWeakRef && options2.startupObjects.has(object8)) {
67554
+ startupReferences.push([object8, caller]);
67555
+ } else {
67556
+ otherReferences.push([object8, caller]);
67557
+ }
67558
+ }
66866
67559
  for (const [, caller] of startupReferences)
66867
67560
  if (!callers.has(caller))
66868
67561
  throw new Error(`guest image has no caller scope ${caller}`);
66869
67562
  if (startupReferences.length && !record6.physicalModule) {
66870
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
66871
- if (candidates.size > 1 || record6.providers.size > 1)
67563
+ const candidates2 = options2.definitionObjects.get(symbol2);
67564
+ const candidateSize = candidates2?.size ?? 0;
67565
+ if (candidateSize > 1 || record6.providers.size > 1)
66872
67566
  throw new Error(`ambiguous startup provider ${symbol2}`);
66873
- if (candidates.size !== record6.providers.size || [...record6.providers.keys()].some((object8) => !candidates.has(object8)))
66874
- throw new Error(`unproven startup provider ${symbol2}`);
67567
+ let unproven = candidateSize !== record6.providers.size;
67568
+ if (!unproven && candidates2) {
67569
+ for (const object8 of record6.providers.keys()) {
67570
+ if (!candidates2.has(object8)) {
67571
+ unproven = true;
67572
+ break;
67573
+ }
67574
+ }
67575
+ }
67576
+ if (unproven) throw new Error(`unproven startup provider ${symbol2}`);
66875
67577
  if (record6.providers.size === 1) {
66876
- const [providerObject, providerImage] = [...record6.providers][0];
67578
+ const [providerObject, providerImage] = record6.providers.entries().next().value;
66877
67579
  if (options2.weakDefinitions.get(providerObject)?.has(symbol2))
66878
67580
  throw new Error(`weak startup provider ${symbol2}`);
66879
67581
  for (const [object8] of startupReferences)
@@ -66881,28 +67583,34 @@ function verifyGuestSymbolScopes(options2) {
66881
67583
  }
66882
67584
  if (!otherReferences.length) continue;
66883
67585
  }
66884
- if (!record6.providers.size && !record6.physicalModule && [...record6.references.keys()].every(
66885
- (object8) => options2.weakReferences.get(object8)?.has(symbol2)
66886
- ))
66887
- continue;
67586
+ if (!record6.providers.size && !record6.physicalModule && allWeakRefs) continue;
66888
67587
  const providerImages = new Set(record6.providers.values());
66889
- const copies = [...options2.definitionObjects.get(symbol2) ?? []].flatMap(
66890
- (object8) => {
67588
+ const candidates = options2.definitionObjects.get(symbol2);
67589
+ const copyImages = /* @__PURE__ */ new Set();
67590
+ const strongImages = /* @__PURE__ */ new Set();
67591
+ let weakDefinerImages;
67592
+ if (candidates) {
67593
+ for (const object8 of candidates) {
66891
67594
  const image = options2.owners.get(object8);
66892
- return image === void 0 ? [] : [{ image, weak: !!options2.weakDefinitions.get(object8)?.has(symbol2) }];
67595
+ if (image === void 0) continue;
67596
+ copyImages.add(image);
67597
+ if (options2.weakDefinitions.get(object8)?.has(symbol2)) {
67598
+ ;
67599
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
67600
+ } else {
67601
+ strongImages.add(image);
67602
+ }
66893
67603
  }
66894
- );
66895
- const copyImages = new Set(copies.map((copy) => copy.image));
66896
- const strongImages = new Set(
66897
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
66898
- );
67604
+ }
66899
67605
  const interposed = !record6.physicalModule && copyImages.size > 1;
66900
67606
  const providerCount = interposed ? 1 : providerImages.size + Number(record6.physicalModule);
66901
67607
  if (!providerCount) continue;
66902
67608
  if (providerCount !== 1)
66903
67609
  throw new Error(`guest symbol has ambiguous provider ${symbol2}`);
66904
- const scopedReferences = record6.physicalModule ? [...record6.references] : otherReferences;
66905
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
67610
+ const scopedReferences = record6.physicalModule ? record6.references : otherReferences;
67611
+ const firstProviderImage = providerImages.values().next().value;
67612
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
67613
+ let interposedByCaller;
66906
67614
  for (const [object8, caller] of scopedReferences) {
66907
67615
  const scope2 = callers.get(caller);
66908
67616
  if (!scope2) throw new Error(`guest image has no caller scope ${caller}`);
@@ -66910,18 +67618,35 @@ function verifyGuestSymbolScopes(options2) {
66910
67618
  result.push({ symbol: symbol2, caller, provider: { kind: "physical-module" } });
66911
67619
  continue;
66912
67620
  }
66913
- const provider = interposed ? [caller, ...scope2].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
67621
+ let provider;
67622
+ if (interposed) {
67623
+ if (interposedByCaller?.has(caller)) {
67624
+ provider = interposedByCaller.get(caller);
67625
+ } else {
67626
+ if (copyImages.has(caller)) {
67627
+ provider = caller;
67628
+ } else {
67629
+ for (const image of scope2) {
67630
+ if (copyImages.has(image)) {
67631
+ provider = image;
67632
+ break;
67633
+ }
67634
+ }
67635
+ if (provider === void 0) provider = uniqueProvider;
67636
+ }
67637
+ ;
67638
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
67639
+ }
67640
+ } else {
67641
+ provider = firstProviderImage;
67642
+ }
66914
67643
  if (provider === void 0) {
66915
67644
  if (options2.weakReferences.get(object8)?.has(symbol2)) continue;
66916
67645
  throw new Error(`guest scope ${caller} omits every provider of ${symbol2}`);
66917
67646
  }
66918
67647
  if (caller === provider) continue;
66919
- if ([...options2.definitionObjects.get(symbol2) ?? []].some(
66920
- (definer) => options2.owners.get(definer) === caller && options2.weakDefinitions.get(definer)?.has(symbol2)
66921
- ))
66922
- continue;
66923
- if (!scope2.includes(provider)) {
66924
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
67648
+ if (weakDefinerImages?.has(caller)) continue;
67649
+ if (!callerSets.get(caller).has(provider)) {
66925
67650
  const traced = [...record6.providers.keys()];
66926
67651
  const strongTraced = traced.filter(
66927
67652
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
@@ -66929,16 +67654,17 @@ function verifyGuestSymbolScopes(options2) {
66929
67654
  const providers = strongTraced.length === 1 ? strongTraced : traced;
66930
67655
  if (options2.weakReferences.get(object8)?.has(symbol2) && !providers.some((provider2) => options2.systemProviders.has(provider2)))
66931
67656
  continue;
66932
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
67657
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
67658
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
66933
67659
  (definer) => options2.weakDefinitions.get(definer)?.has(symbol2)
66934
67660
  );
66935
- const strongCandidates = [...candidates].filter(
67661
+ const strongCandidates = [...candidateSet].filter(
66936
67662
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
66937
67663
  );
66938
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
66939
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
67664
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
67665
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
66940
67666
  // scope, the root image and its dependency closure, as in elf.
66941
- provider === 0 || callers.get(0)?.includes(provider) || !options2.weakReferences.get(object8)?.has(symbol2) && options2.frameworkProviders.get(object8)?.has(providers[0]))))
67667
+ provider === 0 || rootScope?.has(provider) || !options2.weakReferences.get(object8)?.has(symbol2) && options2.frameworkProviders.get(object8)?.has(providers[0]))))
66942
67668
  throw new Error(
66943
67669
  `guest scope ${caller} omits traced provider ${provider} for ${symbol2}`
66944
67670
  );
@@ -73072,9 +73798,9 @@ async function compileGuestLink(options2) {
73072
73798
  }
73073
73799
  };
73074
73800
  },
73075
- resolvePlan: (selected, plan) => {
73801
+ resolvePlan: (selected, plan, readSelected) => {
73076
73802
  if (!prepared) throw new Error("guest runtime selection is unavailable");
73077
- const scope2 = selectedGuestSymbolInputs(plan, selected);
73803
+ const scope2 = selectedGuestSymbolInputs(plan, selected, readSelected);
73078
73804
  const owners = new Map(scope2.owners);
73079
73805
  owners.set(import_node_path72.default.join(directory2, "projection-discovery.o"), 0);
73080
73806
  const providersByImage = Map.groupBy(scope2.owners, ([, image]) => image);
@@ -80750,7 +81476,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
80750
81476
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
80751
81477
  MULTI_MANIFEST_VERSION = 76;
80752
81478
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
80753
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
81479
+ compilerSourceDigest = true ? "7b91fa4405159335b5484c82700e001e4c27abf15621b724ea8af4edea693f66" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
80754
81480
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
80755
81481
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
80756
81482
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));
@@ -137794,7 +138520,7 @@ function eventBindings(name3, source) {
137794
138520
  });
137795
138521
  continue;
137796
138522
  }
137797
- const call = /emitter->(\w+)\( ?\{([^}]*)\} ?\)/.exec(body);
138523
+ const call = /emitter->(\w+)\(\s*\{([^}]*)\}\s*\)/.exec(body);
137798
138524
  if (!call) throw new Error(`${name3}: unmapped event block ${property2}`);
137799
138525
  const fields = [...call[2].matchAll(/\.(\w+) = ([^,]+)/g)].map(
137800
138526
  ([, field2, expression]) => {
@@ -137836,18 +138562,20 @@ function configuration(name3, source) {
137836
138562
  }
137837
138563
  function arrayBindings(name3, body) {
137838
138564
  const bindings = /* @__PURE__ */ new Map();
137839
- for (const [, prop, element] of body.matchAll(
137840
- /for \(const auto &item : next\.(\w+)\) \[\w+ addObject:(.*?)\];/g
138565
+ for (const [, item, prop, variable, element] of body.matchAll(
138566
+ /for \(const auto &(\w+) : next\.(\w+)\) \[(\w+) addObject:(.*?)\];/g
137841
138567
  )) {
137842
- if (element === "RCTNSStringFromString(item)") {
137843
- bindings.set(prop, []);
138568
+ if (element === `RCTNSStringFromString(${item})`) {
138569
+ bindings.set(variable, { prop, fields: [] });
137844
138570
  continue;
137845
138571
  }
137846
138572
  const fields = [
137847
- ...element.matchAll(/@"(\w+)" ?: (RCTNSStringFromString|@)\(item\.\w+\)/g)
138573
+ ...element.matchAll(
138574
+ new RegExp(`@"(\\w+)" ?: (RCTNSStringFromString|@)\\(${item}\\.\\w+\\)`, "g")
138575
+ )
137848
138576
  ].map(([, name4, kind]) => ({ name: name4, defaultValue: kind === "@" ? 0 : "" }));
137849
138577
  if (!fields.length) throw new Error(`${name3}: unmapped array ${prop}`);
137850
- bindings.set(prop, fields);
138578
+ bindings.set(variable, { prop, fields });
137851
138579
  }
137852
138580
  return bindings;
137853
138581
  }
@@ -137899,38 +138627,41 @@ function swiftGuestControls(one, names, linkedGroups) {
137899
138627
  }
137900
138628
  const withLabel = /^(\w+)With([A-Z])(\w*)$/.exec(first);
137901
138629
  const args = selector.map(({ label, expression }, index) => {
137902
- const fields = arrays.get(expression);
138630
+ const array9 = arrays.get(expression);
137903
138631
  let value;
137904
138632
  if (expression === "OneNativeStyleDictionary(next.swiftStyle)") value = "style";
137905
138633
  else if (expression === "boundedHeight")
137906
138634
  value = 'spec["boundedHeight"] as? Bool ?? false';
137907
138635
  else if (/^@"[^"]*"$/.test(expression)) value = expression.slice(1);
137908
- else if (fields?.length) {
137909
- const entries3 = fields.map(
137910
- ({ name: name4, defaultValue: defaultValue2 }) => `"${name4}": row["${name4}"].flatMap { $0 is NSNull ? nil : $0 } ?? ${JSON.stringify(defaultValue2)}`
138636
+ else if (array9?.fields.length) {
138637
+ const entries3 = array9.fields.map(
138638
+ ({ name: name4, defaultValue: defaultValue2 }) => `"${name4}": row["${name4}"] as? ${typeof defaultValue2 === "number" ? "Double" : "String"} ?? ${JSON.stringify(defaultValue2)}`
137911
138639
  ).join(", ");
137912
- value = `(spec["${expression}"] as? [Spec] ?? []).map { row in [${entries3}] }`;
137913
- } else if (fields) value = `spec["${expression}"] as? [String] ?? []`;
138640
+ value = `(spec["${array9.prop}"] as? [Spec] ?? []).map { row in [${entries3}] }`;
138641
+ } else if (array9) value = `spec["${array9.prop}"] as? [String] ?? []`;
137914
138642
  else {
137915
- const prop = /\bnext\.(\w+)/.exec(expression)?.[1];
138643
+ const prop = /\bnext\.(\w+)/.exec(expression)?.[1] ?? "";
137916
138644
  const types2 = {
137917
- string: 'String ?? ""',
137918
- boolean: "Bool ?? false",
137919
- Double: "Double ?? 0",
137920
- Int32: "Int ?? 0"
138645
+ string: ["String", ""],
138646
+ boolean: ["Bool", false],
138647
+ Double: ["Double", 0],
138648
+ Int32: ["Int", 0]
137921
138649
  };
137922
- const type = prop && props[prop]?.type;
138650
+ const field2 = props[prop];
138651
+ const type = field2?.type;
137923
138652
  if (type === "ColorValue") value = `spec["${prop}"].flatMap(oneControlColor)`;
137924
- else if (type && types2[type]) value = `spec["${prop}"] as? ${types2[type]}`;
137925
- else throw new Error(`${name3}: unmapped guest argument ${expression}`);
138653
+ else if (type && types2[type]) {
138654
+ const [swiftType, implicitDefault] = types2[type];
138655
+ value = `spec["${prop}"] as? ${swiftType} ?? ${JSON.stringify(field2.default ?? implicitDefault)}`;
138656
+ } else throw new Error(`${name3}: unmapped guest argument ${expression}`);
137926
138657
  }
137927
138658
  const argLabel = index ? label : withLabel ? withLabel[2].toLowerCase() + withLabel[3] : "";
137928
138659
  return argLabel ? argLabel + ": " + value : value;
137929
138660
  });
137930
138661
  const call = `view.${withLabel?.[1] ?? first}(${args.join(", ")})`;
137931
- const array8 = selector[0].expression;
138662
+ const array8 = arrays.get(selector[0].expression)?.prop;
137932
138663
  lines.push(
137933
- arrays.has(array8) ? ` if previous == nil || (spec["${array8}"] as? NSArray) != (previous?["${array8}"] as? NSArray) { ${call} }` : ` ${call}`
138664
+ array8 ? ` if previous == nil || (spec["${array8}"] as? NSArray) != (previous?["${array8}"] as? NSArray) { ${call} }` : ` ${call}`
137934
138665
  );
137935
138666
  }
137936
138667
  for (const { property: property2, parameters, fields, event, sync } of eventBindings(
@@ -143174,7 +143905,7 @@ var init_nitro_superset = __esm({
143174
143905
  init_nitroContract();
143175
143906
  init_swift_standin_digest();
143176
143907
  NITRO_SUPERSET_ENTRY_NAME = "superset";
143177
- NITRO_COMPILER_DIGEST = true ? "59081cf672cb2bb9c125425cd97f2df60507acfc6de96f1525f18ddca39ff000" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
143908
+ NITRO_COMPILER_DIGEST = true ? "ffe0ab1580ebcb5a184764bfb3b3650342c8644057a95423913e7078c208f318" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
143178
143909
  nitroSupersetLock = parseLock(nitro_superset_lock_default);
143179
143910
  nitroSupersetKey = (inputs2) => nativeEntryKey({ ...inputs2, compiler: NITRO_COMPILER_DIGEST });
143180
143911
  published3 = /* @__PURE__ */ new Map();