peachsim 0.1.2589 → 0.1.2591

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +1490 -534
  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-EMX4WZ72.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-33SCXU3Y.mjs → chunk-4QHHRGO4.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-Y4PV4HZB.mjs → chunk-7627LKJK.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-M4KUWGU3.mjs → chunk-AKKHSVJ4.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-MKSOJCRT.mjs → chunk-EGKH2L6J.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-5EFD2VBY.mjs → chunk-ILWFGZWW.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-57FFWABF.mjs → chunk-J676B57D.mjs} +5 -5
  33. package/dist-lib/esm-chunks/{chunk-JLOJZF2Y.mjs → chunk-JHXDM3YU.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-464CBA5U.mjs → chunk-MC6NMYWY.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-CRIYVOMB.mjs → chunk-NX23AMX4.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-EAIFG4MQ.mjs → chunk-Q4NA6PUR.mjs} +3 -3
  37. package/dist-lib/esm-chunks/{chunk-47K4QPVA.mjs → chunk-QBMFX3J2.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-FQQ2DMXS.mjs → chunk-RKQZGWX2.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-5QWQDXXD.mjs → chunk-SOAYP72T.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-XTKKROVU.mjs → chunk-TFG4LZ5T.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-KFHCRS5K.mjs → chunk-UIVXVMS5.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-BSAAJR25.mjs → chunk-UYJXLDCG.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-FMWEI6OI.mjs → chunk-VD27WNCT.mjs} +4 -4
  44. package/dist-lib/esm-chunks/{chunk-3VNUC4DT.mjs → chunk-VF5WVB3D.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-WQ73RKJY.mjs → chunk-VRVXRZI4.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-L3OSVIGA.mjs → chunk-VYZ5DC3M.mjs} +1359 -487
  47. package/dist-lib/esm-chunks/{chunk-I22LAVD5.mjs → chunk-YR6DNV76.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-PUBH3EXI.mjs → chunk-ZL5N6ENT.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-T5QIJTEV.mjs → metro-layout-parser-ANKZARNW.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-AWTZHPDM.mjs → swift-package-prebuilt-4N5CXBOZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-MGTJTVKU.mjs → swift-sdk-app-module-5IUSRXYA.mjs} +151 -67
  52. package/dist-lib/esm-chunks/{swift-sdk-image-JABGF3ZR.mjs → swift-sdk-image-7T2LMQS5.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-RJRJ3EFU.mjs → swift-sdk-image-producer-7QJ3BF6E.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1489 -533
  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 +1518 -557
  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 +1520 -559
  93. package/dist-lib/swift-compile.cjs +1486 -530
  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 +43 -10
  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 +258 -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-guest-source-inputs.ts +158 -30
  136. package/src/swift-sdk-app-module.ts +146 -59
  137. package/src/swift-sdk-image-map.ts +137 -35
  138. package/src/swift-wasm-prune.ts +263 -85
  139. 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.2591 | (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;
@@ -5712,13 +5712,13 @@ var init_swift_standin_digest = __esm({
5712
5712
  STANDIN_DIGEST_ENTRYPOINTS = ["swift-standins.ts", "swift-objc-compile.ts"];
5713
5713
  SPECIFIER = /from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
5714
5714
  standinSourceDigest = (srcDir = __sootsim_import_meta_dirname) => sourceClosureDigest(srcDir, STANDIN_DIGEST_ENTRYPOINTS);
5715
- STANDIN_SOURCE_DIGEST = true ? "b4ec01293af51e43890fb5aa52c9dc6d240c73b8fe722cdaff952457b08d94ff" : standinSourceDigest();
5715
+ STANDIN_SOURCE_DIGEST = true ? "a8f701d93728e07278999e87ca0ce8629c73067b6c4382393bfa6705a275114b" : standinSourceDigest();
5716
5716
  }
5717
5717
  });
5718
5718
 
5719
5719
  // src/expo-native-compiler-digest.ts
5720
5720
  function expoNativeCompilerDigestValue() {
5721
- return true ? "bc9bf63858735336bd46e9b34db5ced39d682f7200bbbc3eafbf5470dae0018f" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
5721
+ return true ? "fac25d497603de6d36f5104099d949e505b050f78be3ed12989ae494db25b470" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
5722
5722
  }
5723
5723
  var import_node_crypto11;
5724
5724
  var init_expo_native_compiler_digest = __esm({
@@ -36314,24 +36314,56 @@ function layout(bytes, readData = true, requireExports = true) {
36314
36314
  const code = sections.get(10);
36315
36315
  if (code) {
36316
36316
  let pos = code[0];
36317
- let count;
36318
- [count, pos] = number(bytes, pos);
36317
+ const codeStart = code[0];
36318
+ const codeEnd = code[1];
36319
+ let count = 0;
36320
+ {
36321
+ let shift = 0;
36322
+ for (; ; ) {
36323
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
36324
+ const byte = bytes[pos++];
36325
+ count += (byte & 127) * 2 ** shift;
36326
+ if (!(byte & 128)) break;
36327
+ shift += 7;
36328
+ }
36329
+ }
36319
36330
  for (let i = 0; i < count; i++) {
36320
36331
  const prefix = pos;
36321
- let size2;
36322
- [size2, pos] = number(bytes, pos);
36323
- functionsByCodeOffset.set(prefix - code[0], imports2 + i);
36332
+ let size2 = 0;
36333
+ const b0 = bytes[pos++];
36334
+ if (b0 < 128) {
36335
+ size2 = b0;
36336
+ } else {
36337
+ size2 = b0 & 127;
36338
+ let shift = 7;
36339
+ for (; ; ) {
36340
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
36341
+ const byte = bytes[pos++];
36342
+ size2 += (byte & 127) * 2 ** shift;
36343
+ if (!(byte & 128)) break;
36344
+ shift += 7;
36345
+ }
36346
+ }
36347
+ functionsByCodeOffset.set(prefix - codeStart, imports2 + i);
36324
36348
  if (imports2 + i === startFunction) startup = bytes.subarray(pos, pos + size2);
36325
36349
  pos += size2;
36326
- if (pos > code[1]) throw new Error("invalid wasm code");
36350
+ if (pos > codeEnd) throw new Error("invalid wasm code");
36327
36351
  }
36328
- if (pos !== code[1]) throw new Error("invalid wasm code section");
36352
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
36329
36353
  }
36330
36354
  const functionsByTableSlot = /* @__PURE__ */ new Map();
36331
36355
  const elements = sections.get(9);
36332
36356
  if (elements) {
36333
36357
  let pos = elements[0];
36358
+ const elemEnd = elements[1];
36334
36359
  const read = () => {
36360
+ if (pos < elemEnd) {
36361
+ const b0 = bytes[pos];
36362
+ if (b0 < 128) {
36363
+ pos++;
36364
+ return b0;
36365
+ }
36366
+ }
36335
36367
  const [value, next] = number(bytes, pos);
36336
36368
  pos = next;
36337
36369
  return value;
@@ -36361,7 +36393,7 @@ function layout(bytes, readData = true, requireExports = true) {
36361
36393
  functionsByTableSlot.set(slot, read());
36362
36394
  }
36363
36395
  }
36364
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
36396
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
36365
36397
  }
36366
36398
  const data = [];
36367
36399
  const passive = /* @__PURE__ */ new Map();
@@ -36426,36 +36458,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
36426
36458
  length: segment2.bytes.length
36427
36459
  }));
36428
36460
  }
36429
- function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
36461
+ function isMapSpace(code) {
36462
+ return code === 32 || code >= 9 && code <= 13;
36463
+ }
36464
+ function isMapHex(code) {
36465
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
36466
+ }
36467
+ function mapHexDigit(code) {
36468
+ return code <= 57 ? code - 48 : code - 87;
36469
+ }
36470
+ function* stringLines(text7) {
36471
+ let start = 0;
36472
+ for (let end = text7.indexOf("\n"); end !== -1; end = text7.indexOf("\n", start)) {
36473
+ yield text7.slice(start, end);
36474
+ start = end + 1;
36475
+ }
36476
+ yield text7.slice(start);
36477
+ }
36478
+ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
36430
36479
  const unchanged = before === after;
36431
36480
  const original = layout(before, !unchanged, !importsLayout);
36432
36481
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
36482
+ const collectSymbols = extra?.collectSymbols;
36483
+ const trackedObject = extra?.trackedObject;
36484
+ const trackedObjectOwner = extra?.trackedObjectOwner;
36485
+ const trackedLinearSpans = extra?.trackedLinearSpans;
36486
+ const hasSectionOwners = sectionOwners.size > 0;
36433
36487
  let codeOffset;
36434
36488
  let outputSection = "";
36435
36489
  const codeOwners = /* @__PURE__ */ new Map();
36436
36490
  const pieces = [];
36437
- for (const line of typeof map2 === "string" ? map2.split("\n") : map2) {
36438
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
36439
- if (!match) continue;
36440
- const [, address, offset, size2, indent2, source] = match;
36441
- if (address === "-" && indent2 === " ") {
36442
- outputSection = source;
36443
- if (source === "CODE") codeOffset = parseInt(offset, 16);
36491
+ const lines = typeof map2 === "string" ? stringLines(map2) : map2;
36492
+ for (const line of lines) {
36493
+ const lineLen = line.length;
36494
+ let pos = 0;
36495
+ let onlySpaces = true;
36496
+ while (pos < lineLen) {
36497
+ const ch = line.charCodeAt(pos);
36498
+ if (!isMapSpace(ch)) break;
36499
+ if (ch !== 32) onlySpaces = false;
36500
+ pos++;
36501
+ }
36502
+ const leadingSpaces = pos;
36503
+ if (pos >= lineLen) continue;
36504
+ const addrStart = pos;
36505
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
36506
+ const addrEnd = pos;
36507
+ if (pos >= lineLen) continue;
36508
+ const s1 = pos;
36509
+ while (pos < lineLen) {
36510
+ const ch = line.charCodeAt(pos);
36511
+ if (!isMapSpace(ch)) break;
36512
+ if (ch !== 32) onlySpaces = false;
36513
+ pos++;
36514
+ }
36515
+ if (pos === s1 || pos >= lineLen) continue;
36516
+ const offStart = pos;
36517
+ let offsetVal = 0;
36518
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
36519
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
36520
+ }
36521
+ if (pos === offStart || pos >= lineLen) continue;
36522
+ const s2 = pos;
36523
+ while (pos < lineLen) {
36524
+ const ch = line.charCodeAt(pos);
36525
+ if (!isMapSpace(ch)) break;
36526
+ if (ch !== 32) onlySpaces = false;
36527
+ pos++;
36528
+ }
36529
+ if (pos === s2 || pos >= lineLen) continue;
36530
+ const sizeStart = pos;
36531
+ let sizeVal = 0;
36532
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
36533
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
36534
+ }
36535
+ if (pos === sizeStart || pos >= lineLen) continue;
36536
+ const indentStart = pos;
36537
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
36538
+ const indentLen = pos - indentStart;
36539
+ if (indentLen === 0 || pos >= lineLen) continue;
36540
+ const firstCh = line.charCodeAt(pos);
36541
+ if (isMapSpace(firstCh)) continue;
36542
+ const sourceStart = pos;
36543
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
36544
+ let symEnd = sourceStart + 1;
36545
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
36546
+ collectSymbols.add(line.slice(sourceStart, symEnd));
36547
+ }
36548
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
36549
+ if (isDash && indentLen === 1) {
36550
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
36551
+ outputSection = line.slice(sourceStart);
36552
+ if (outputSection === "CODE") codeOffset = offsetVal;
36444
36553
  continue;
36445
36554
  }
36446
- const separator = source.indexOf(":(");
36555
+ if (sizeVal === 0) continue;
36556
+ const separator = line.indexOf(":(", sourceStart);
36447
36557
  if (separator < 0) continue;
36448
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
36449
- const length = parseInt(size2, 16);
36450
- if (!length) continue;
36451
- if (address !== "-") {
36452
- if (outputSection === "DATA")
36453
- pieces.push({ image, address: parseInt(address, 16), length });
36558
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
36559
+ let hasLineSep = false;
36560
+ for (let i = sourceStart; i < lineLen; i++) {
36561
+ const ch = line.charCodeAt(i);
36562
+ if (ch === 8232 || ch === 8233) {
36563
+ hasLineSep = true;
36564
+ break;
36565
+ }
36566
+ }
36567
+ if (hasLineSep) continue;
36568
+ const objectPath = line.slice(sourceStart, separator);
36569
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
36570
+ if (image === void 0) image = owners.get(objectPath);
36571
+ if (!isDash) {
36572
+ if (outputSection === "DATA") {
36573
+ let addressVal = 0;
36574
+ let allHex = true;
36575
+ for (let i = addrStart; i < addrEnd; i++) {
36576
+ const ch = line.charCodeAt(i);
36577
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
36578
+ else {
36579
+ allHex = false;
36580
+ break;
36581
+ }
36582
+ }
36583
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
36584
+ pieces.push({
36585
+ image,
36586
+ address: addressVal,
36587
+ length: sizeVal,
36588
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
36589
+ });
36590
+ }
36454
36591
  continue;
36455
36592
  }
36456
36593
  if (image === void 0 || outputSection !== "CODE") continue;
36457
36594
  if (codeOffset === void 0) throw new Error("link map has no code section");
36458
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
36595
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
36459
36596
  if (index === void 0) throw new Error("link map function has no wasm body");
36460
36597
  const existing = codeOwners.get(index);
36461
36598
  if (existing !== void 0 && existing !== image)
@@ -36464,12 +36601,23 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
36464
36601
  }
36465
36602
  pieces.sort((a, b) => a.address - b.address);
36466
36603
  const spans = [];
36467
- for (const [index, { image, address, length }] of pieces.entries()) {
36468
- if (image === void 0) continue;
36604
+ for (let index = 0; index < pieces.length; index++) {
36605
+ const piece = pieces[index];
36606
+ const { image, address, length, tracked } = piece;
36607
+ if (image === void 0 && !tracked) continue;
36469
36608
  let next = index + 1;
36470
36609
  while (next < pieces.length && pieces[next].address < address + length) next++;
36471
36610
  const end = pieces[next]?.address ?? address + length;
36472
- spans.push({ image, space: "linear-memory", address, length: end - address });
36611
+ const spanLength = end - address;
36612
+ if (image !== void 0)
36613
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
36614
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
36615
+ trackedLinearSpans.push({
36616
+ image: trackedObjectOwner,
36617
+ space: "linear-memory",
36618
+ address,
36619
+ length: spanLength
36620
+ });
36473
36621
  }
36474
36622
  const optimizedOwners = /* @__PURE__ */ new Map();
36475
36623
  const dataAt = (module2, start, length) => {
@@ -36508,7 +36656,7 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
36508
36656
  throw new Error(`optimization changed linked data at ${span.address}`);
36509
36657
  }
36510
36658
  let previous;
36511
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
36659
+ for (const span of spans) {
36512
36660
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
36513
36661
  throw new Error("linked data belongs to multiple images");
36514
36662
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -36690,6 +36838,20 @@ var init_swift_guest_linked_spans = __esm({
36690
36838
  });
36691
36839
 
36692
36840
  // src/swift-sdk-image-map.ts
36841
+ function isHexChar(code) {
36842
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
36843
+ }
36844
+ function hexDigit(code) {
36845
+ return code <= 57 ? code - 48 : code - 87;
36846
+ }
36847
+ function hasLineBreak(line, from) {
36848
+ if (line.indexOf("\r", from) >= 0) return true;
36849
+ for (let i = from; i < line.length; i++) {
36850
+ const ch = line.charCodeAt(i);
36851
+ if (ch === 8232 || ch === 8233) return true;
36852
+ }
36853
+ return false;
36854
+ }
36693
36855
  function readWasmLinkMap(file, partition) {
36694
36856
  const segments = /* @__PURE__ */ new Map();
36695
36857
  const data = [];
@@ -36697,48 +36859,117 @@ function readWasmLinkMap(file, partition) {
36697
36859
  let kind = "";
36698
36860
  let segment2 = "";
36699
36861
  let previous;
36700
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
36701
36862
  for (const line of guestLinkLines(file)) {
36702
- const symbol2 = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
36703
- if (symbol2) {
36704
- previous?.symbols.push({
36705
- name: symbol2[3],
36706
- address: hex(symbol2[1]),
36707
- size: parseInt(symbol2[2], 16)
36708
- });
36863
+ const length = line.length;
36864
+ let pos = 0;
36865
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36866
+ if (pos >= length) continue;
36867
+ const leadingSpaces = pos;
36868
+ let address = -1;
36869
+ if (line.charCodeAt(pos) === 45) {
36870
+ pos++;
36871
+ } else {
36872
+ const start = pos;
36873
+ let value = 0;
36874
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
36875
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
36876
+ }
36877
+ if (pos === start) continue;
36878
+ address = value;
36879
+ }
36880
+ const s1 = pos;
36881
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36882
+ if (pos === s1 || pos >= length) continue;
36883
+ const offStart = pos;
36884
+ let offset = 0;
36885
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
36886
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
36887
+ }
36888
+ if (pos === offStart) continue;
36889
+ const s2 = pos;
36890
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36891
+ if (pos === s2 || pos >= length) continue;
36892
+ const sizeStart = pos;
36893
+ let size2 = 0;
36894
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
36895
+ size2 = size2 * 16 + hexDigit(line.charCodeAt(pos++));
36896
+ }
36897
+ if (pos === sizeStart || pos >= length) continue;
36898
+ const indentStart = pos;
36899
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36900
+ const indent2 = pos - indentStart;
36901
+ if (indent2 === 0 || pos >= length) continue;
36902
+ if (indent2 === 17) {
36903
+ if (previous) {
36904
+ const first = line.charCodeAt(pos);
36905
+ if (first > 32 && !hasLineBreak(line, pos)) {
36906
+ previous.symbols.push({
36907
+ name: line.slice(pos),
36908
+ address,
36909
+ size: size2
36910
+ });
36911
+ }
36912
+ }
36709
36913
  continue;
36710
36914
  }
36711
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
36712
- if (output) {
36713
- kind = output[1];
36915
+ if (indent2 === 1) {
36916
+ let hasWhitespace = false;
36917
+ for (let i = pos; i < length; i++) {
36918
+ const ch = line.charCodeAt(i);
36919
+ if (ch <= 32) {
36920
+ hasWhitespace = true;
36921
+ break;
36922
+ }
36923
+ }
36924
+ if (hasWhitespace) continue;
36925
+ if (address < 0 && leadingSpaces > 0) {
36926
+ kind = line.slice(pos);
36927
+ } else if (kind === "DATA" && address >= 0) {
36928
+ segment2 = line.slice(pos);
36929
+ segments.set(segment2, { address, size: size2 });
36930
+ }
36714
36931
  continue;
36715
36932
  }
36716
- if (kind === "DATA") {
36717
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
36718
- if (top) {
36719
- segment2 = top[3];
36720
- segments.set(segment2, { address: hex(top[1]), size: parseInt(top[2], 16) });
36721
- continue;
36933
+ if (indent2 === 9 && (kind === "DATA" || kind === "CODE")) {
36934
+ const first = line.charCodeAt(pos);
36935
+ if (first !== 47 && first !== 60) continue;
36936
+ if (hasLineBreak(line, pos)) continue;
36937
+ const name3 = line.slice(pos);
36938
+ let filePath = name3;
36939
+ let section2 = "";
36940
+ if (name3.charCodeAt(name3.length - 1) === 41) {
36941
+ const splitAt = name3.indexOf(":(");
36942
+ if (splitAt >= 0) {
36943
+ filePath = name3.slice(0, splitAt);
36944
+ section2 = name3.slice(splitAt + 2, -1);
36945
+ }
36946
+ }
36947
+ let objectName;
36948
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
36949
+ const open = filePath.lastIndexOf("(");
36950
+ if (open >= 0 && open + 1 < filePath.length - 1) {
36951
+ const close = filePath.indexOf(")", open + 1);
36952
+ if (close === filePath.length - 1) {
36953
+ objectName = filePath.slice(open + 1, -1);
36954
+ }
36955
+ }
36722
36956
  }
36957
+ if (objectName === void 0) objectName = (0, import_node_path56.basename)(filePath);
36958
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
36959
+ objectName = objectName.replace(/^lib\w*?__/, "");
36960
+ }
36961
+ previous = {
36962
+ inputFile: filePath,
36963
+ segment: segment2,
36964
+ address,
36965
+ offset,
36966
+ size: size2,
36967
+ object: objectName,
36968
+ section: section2,
36969
+ symbols: []
36970
+ };
36971
+ (kind === "DATA" ? data : code).push(previous);
36723
36972
  }
36724
- if (kind !== "DATA" && kind !== "CODE") continue;
36725
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
36726
- if (!input) continue;
36727
- const name3 = input[4];
36728
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
36729
- const path161 = split ? split[1] : name3;
36730
- const member = /\(([^()]+)\)$/.exec(path161);
36731
- previous = {
36732
- inputFile: path161,
36733
- segment: segment2,
36734
- address: hex(input[1]),
36735
- offset: parseInt(input[2], 16),
36736
- size: parseInt(input[3], 16),
36737
- object: (member ? member[1] : (0, import_node_path56.basename)(path161)).replace(/^lib\w*?__/, ""),
36738
- section: split ? split[2] : "",
36739
- symbols: []
36740
- };
36741
- (kind === "DATA" ? data : code).push(previous);
36742
36973
  }
36743
36974
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
36744
36975
  }
@@ -37884,6 +38115,7 @@ function patchSwiftrtObject(src) {
37884
38115
  return buf;
37885
38116
  }
37886
38117
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38118
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
37887
38119
  let pos = 8;
37888
38120
  let numImportFuncs = 0;
37889
38121
  let importsDlsym = false;
@@ -37919,10 +38151,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
37919
38151
  let [cnt, cp] = readULEB2(buf, p);
37920
38152
  for (let i = 0; i < cnt; i++) {
37921
38153
  const [mLen, m2] = readULEB2(buf, cp);
37922
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
38154
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
37923
38155
  cp = m2 + mLen;
37924
38156
  const [fLen, f2] = readULEB2(buf, cp);
37925
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
38157
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
37926
38158
  cp = f2 + fLen;
37927
38159
  const kind = buf[cp++];
37928
38160
  if (kind === 0) {
@@ -38002,7 +38234,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38002
38234
  }
38003
38235
  } else if (id === 0) {
38004
38236
  const [nLen, np] = readULEB2(buf, p);
38005
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
38237
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
38006
38238
  const cp = np + nLen;
38007
38239
  if (name3 === "linking") {
38008
38240
  let [, lp] = readULEB2(buf, cp);
@@ -38015,7 +38247,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38015
38247
  let cur = p2;
38016
38248
  for (let i = 0; i < cnt; i++) {
38017
38249
  const [sLen, s2] = readULEB2(buf, cur);
38018
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
38250
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
38019
38251
  cur = s2 + sLen;
38020
38252
  const [, s3] = readULEB2(buf, cur);
38021
38253
  const [fl, s4] = readULEB2(buf, s3);
@@ -38055,7 +38287,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38055
38287
  let sName = "";
38056
38288
  if (!isUndef || isExplicitName) {
38057
38289
  const [sLen, c4] = readULEB2(buf, cur);
38058
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
38290
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
38059
38291
  cur = c4 + sLen;
38060
38292
  } else if (kind === 0) {
38061
38293
  sName = importFuncNames[el] ?? "";
@@ -38071,7 +38303,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38071
38303
  symNames.push(sName);
38072
38304
  } else if (kind === 1) {
38073
38305
  const [sLen, c3] = readULEB2(buf, cur);
38074
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
38306
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
38075
38307
  cur = c3 + sLen;
38076
38308
  if (!isUndef) {
38077
38309
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -38186,9 +38418,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38186
38418
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
38187
38419
  let ownerSymIdx = -1;
38188
38420
  const topList = segTopSyms.get(lo);
38189
- if (topList) {
38190
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
38191
- if (owner) ownerSymIdx = owner.symIdx;
38421
+ if (topList && topList.length > 0) {
38422
+ let tLo = 0;
38423
+ let tHi = topList.length - 1;
38424
+ while (tLo <= tHi) {
38425
+ const tMid = tLo + tHi >> 1;
38426
+ const top = topList[tMid];
38427
+ if (offInSeg < top.off) {
38428
+ tHi = tMid - 1;
38429
+ } else if (offInSeg >= top.end) {
38430
+ tLo = tMid + 1;
38431
+ } else {
38432
+ ownerSymIdx = top.symIdx;
38433
+ break;
38434
+ }
38435
+ }
38192
38436
  }
38193
38437
  if (ownerSymIdx !== -1) {
38194
38438
  let list2 = symDataRelocs.get(ownerSymIdx);
@@ -38443,54 +38687,151 @@ function localizeDefinedWasmSymbols(bytes, names) {
38443
38687
  return output;
38444
38688
  }
38445
38689
  function guestWasmSymbols(bytes) {
38446
- const object8 = parseWasmObjectBytes("", bytes, false);
38690
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
38691
+ let cur = 8;
38692
+ const readU = () => {
38693
+ const b0 = bytes[cur++];
38694
+ if (b0 < 128) return b0;
38695
+ let res = b0 & 127;
38696
+ let shift = 7;
38697
+ while (true) {
38698
+ const byte = bytes[cur++];
38699
+ res |= (byte & 127) << shift;
38700
+ if ((byte & 128) === 0) return res;
38701
+ shift += 7;
38702
+ }
38703
+ };
38704
+ let importsDlsym = false;
38705
+ const importFuncNames = [];
38706
+ const importFuncModules = [];
38707
+ const importGlobalNames = [];
38708
+ const importTableNames = [];
38709
+ const importEventNames = [];
38710
+ const undefinedSyms = /* @__PURE__ */ new Set();
38711
+ const tags = /* @__PURE__ */ new Set();
38712
+ const globals = /* @__PURE__ */ new Set();
38713
+ const hostImports = /* @__PURE__ */ new Set();
38714
+ const weakUndefined = /* @__PURE__ */ new Set();
38715
+ const defined = /* @__PURE__ */ new Set();
38716
+ const weakDefined = /* @__PURE__ */ new Set();
38717
+ while (cur < bytes.length) {
38718
+ const id = bytes[cur++];
38719
+ const sz = readU();
38720
+ const end = cur + sz;
38721
+ if (id === 2) {
38722
+ const cnt = readU();
38723
+ for (let i = 0; i < cnt; i++) {
38724
+ const mLen = readU();
38725
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
38726
+ cur += mLen;
38727
+ const fLen = readU();
38728
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
38729
+ cur += fLen;
38730
+ const kind = bytes[cur++];
38731
+ if (kind === 0) {
38732
+ readU();
38733
+ importFuncNames.push(fName);
38734
+ importFuncModules.push(mName);
38735
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
38736
+ } else if (kind === 1) {
38737
+ cur++;
38738
+ const fl = readU();
38739
+ readU();
38740
+ if (fl & 1) readU();
38741
+ importTableNames.push(fName);
38742
+ } else if (kind === 2) {
38743
+ const fl = readU();
38744
+ readU();
38745
+ if (fl & 1) readU();
38746
+ } else if (kind === 3) {
38747
+ cur += 2;
38748
+ importGlobalNames.push(fName);
38749
+ } else if (kind === 4) {
38750
+ cur++;
38751
+ readU();
38752
+ importEventNames.push(fName);
38753
+ }
38754
+ }
38755
+ } else if (id === 0) {
38756
+ const nLen = readU();
38757
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
38758
+ cur += nLen;
38759
+ readU();
38760
+ while (cur < end) {
38761
+ const subId = bytes[cur++];
38762
+ const subLen = readU();
38763
+ const subEnd = cur + subLen;
38764
+ if (subId === 8) {
38765
+ const cnt = readU();
38766
+ for (let i = 0; i < cnt; i++) {
38767
+ const kind = bytes[cur++];
38768
+ const fl = readU();
38769
+ const isUndef = (fl & 16) !== 0;
38770
+ const isExplicitName = (fl & 64) !== 0;
38771
+ let sName = "";
38772
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
38773
+ const el = readU();
38774
+ if (!isUndef || isExplicitName) {
38775
+ const sLen = readU();
38776
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
38777
+ cur += sLen;
38778
+ } else if (kind === 0) {
38779
+ sName = importFuncNames[el] ?? "";
38780
+ } else if (kind === 2) {
38781
+ sName = importGlobalNames[el] ?? "";
38782
+ } else if (kind === 4) {
38783
+ sName = importEventNames[el] ?? "";
38784
+ } else if (kind === 5) {
38785
+ sName = importTableNames[el] ?? "";
38786
+ }
38787
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
38788
+ hostImports.add(sName);
38789
+ } else if (kind === 1) {
38790
+ const sLen = readU();
38791
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
38792
+ cur += sLen;
38793
+ if (!isUndef) {
38794
+ readU();
38795
+ readU();
38796
+ readU();
38797
+ }
38798
+ } else if (kind === 3) {
38799
+ readU();
38800
+ }
38801
+ if (sName) {
38802
+ if (isUndef) {
38803
+ undefinedSyms.add(sName);
38804
+ if ((fl & 19) === 17) weakUndefined.add(sName);
38805
+ } else if ((fl & 3) !== 2) {
38806
+ defined.add(sName);
38807
+ if ((fl & 19) === 1) weakDefined.add(sName);
38808
+ }
38809
+ if (kind === 4) tags.add(sName);
38810
+ else if (kind === 2 || kind === 5) globals.add(sName);
38811
+ }
38812
+ }
38813
+ break;
38814
+ }
38815
+ cur = subEnd;
38816
+ }
38817
+ break;
38818
+ }
38819
+ }
38820
+ cur = end;
38821
+ }
38447
38822
  return {
38448
- importsDlsym: object8.importsDlsym,
38449
- undefined: [
38450
- ...new Set(
38451
- object8.symNames.filter(
38452
- (name3, index) => name3 && (object8.symFlags[index] & 16) !== 0
38453
- )
38454
- )
38455
- ],
38823
+ importsDlsym,
38824
+ undefined: [...undefinedSyms],
38456
38825
  // a wasm tag is one module entity unified by name across the link, as the
38457
38826
  // main module owns it for dynamic images, so no image scope applies.
38458
- tags: [
38459
- ...new Set(
38460
- object8.symNames.filter((name3, index) => name3 && object8.symKind[index] === 4)
38461
- )
38462
- ],
38463
- globals: [
38464
- ...new Set(
38465
- object8.symNames.filter(
38466
- (name3, index) => name3 && (object8.symKind[index] === 2 || object8.symKind[index] === 5)
38467
- )
38468
- )
38469
- ],
38827
+ tags: [...tags],
38828
+ globals: [...globals],
38470
38829
  // an undefined function imported from a module other than env is supplied
38471
38830
  // by the host, whatever linker symbol names it.
38472
- hostImports: [...object8.hostImportNames],
38473
- weakUndefined: [
38474
- ...new Set(
38475
- object8.symNames.filter(
38476
- (name3, index) => name3 && (object8.symFlags[index] & 19) === 17
38477
- )
38478
- )
38479
- ],
38480
- defined: [
38481
- ...new Set(
38482
- object8.symNames.filter(
38483
- (name3, index) => name3 && (object8.symFlags[index] & 16) === 0 && (object8.symFlags[index] & 3) !== 2
38484
- )
38485
- )
38486
- ],
38487
- weakDefined: [
38488
- ...new Set(
38489
- object8.symNames.filter(
38490
- (name3, index) => name3 && (object8.symFlags[index] & 19) === 1
38491
- )
38492
- )
38493
- ]
38831
+ hostImports: [...hostImports],
38832
+ weakUndefined: [...weakUndefined],
38833
+ defined: [...defined],
38834
+ weakDefined: [...weakDefined]
38494
38835
  };
38495
38836
  }
38496
38837
  function sdkObjectName(archive, member, ordinal) {
@@ -39007,9 +39348,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39007
39348
  for (const entry of waiting) tryActivateConformance(entry);
39008
39349
  }
39009
39350
  };
39351
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
39010
39352
  const checkProtocolTrigger = (rawSymName) => {
39011
39353
  if (!rawSymName) return;
39012
39354
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
39355
+ if (checkedProtocolTriggers.has(sName)) return;
39356
+ checkedProtocolTriggers.add(sName);
39013
39357
  if (knownProtocols.has(sName)) {
39014
39358
  markProtocolLive(sName);
39015
39359
  return;
@@ -39042,6 +39386,43 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39042
39386
  }
39043
39387
  }
39044
39388
  };
39389
+ const typeIndexes = /* @__PURE__ */ new Map();
39390
+ const getTypeIndex = (obj) => {
39391
+ let idx = typeIndexes.get(obj);
39392
+ if (idx) return idx;
39393
+ const mnByPrefix = /* @__PURE__ */ new Map();
39394
+ for (let i = 0; i < obj.symNames.length; i++) {
39395
+ const name3 = obj.symNames[i];
39396
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
39397
+ const pref = name3.slice(0, -2);
39398
+ let list2 = mnByPrefix.get(pref);
39399
+ if (!list2) mnByPrefix.set(pref, list2 = []);
39400
+ list2.push(i);
39401
+ }
39402
+ }
39403
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
39404
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
39405
+ let list2 = objcRegByPrefix.get(p);
39406
+ if (!list2) objcRegByPrefix.set(p, list2 = []);
39407
+ list2.push(lf);
39408
+ }
39409
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
39410
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
39411
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
39412
+ let list2 = objcClassByPrefix.get(p);
39413
+ if (!list2) objcClassByPrefix.set(p, list2 = []);
39414
+ list2.push(classSym.slice("._OBJC_CLASS_".length));
39415
+ }
39416
+ let minPrefLen = Infinity;
39417
+ let maxPrefLen = 0;
39418
+ for (const p of obj.typePrefixesInObj) {
39419
+ if (p.length < minPrefLen) minPrefLen = p.length;
39420
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
39421
+ }
39422
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
39423
+ typeIndexes.set(obj, idx);
39424
+ return idx;
39425
+ };
39045
39426
  const markTypeLive = (obj, pref) => {
39046
39427
  const set2 = liveTypes.get(obj);
39047
39428
  if (set2.has(pref)) return;
@@ -39055,22 +39436,10 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39055
39436
  const outer = pref.slice(0, n);
39056
39437
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
39057
39438
  }
39058
- const mnName = `${pref}Mn`;
39059
- for (let i = 0; i < obj.symNames.length; i++) {
39060
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
39061
- activateSymbolInObj(obj, i);
39062
- }
39063
- }
39064
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
39065
- if (p === pref) {
39066
- markFuncLive(obj, lf);
39067
- }
39068
- }
39069
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
39070
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
39071
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
39072
- }
39073
- }
39439
+ const idx = getTypeIndex(obj);
39440
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
39441
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
39442
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
39074
39443
  };
39075
39444
  const checkTypeTrigger = (obj, rawSymName) => {
39076
39445
  if (!rawSymName) return;
@@ -39095,11 +39464,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39095
39464
  }
39096
39465
  }
39097
39466
  }
39098
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
39099
- for (const pref of obj.typePrefixesInObj) {
39100
- if (sName.startsWith(pref)) {
39101
- markTypeLive(obj, pref);
39102
- }
39467
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
39468
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
39469
+ const hi = Math.min(sName.length, maxPrefLen);
39470
+ for (let n = minPrefLen; n <= hi; n++) {
39471
+ const cand = sName.slice(0, n);
39472
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
39103
39473
  }
39104
39474
  }
39105
39475
  };
@@ -39192,7 +39562,8 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39192
39562
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
39193
39563
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
39194
39564
  for (const name3 of obj.symNames) {
39195
- const loaded4 = name3?.match(/^_c_(\w+)__load$/)?.[1];
39565
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
39566
+ const loaded4 = name3.match(/^_c_(\w+)__load$/)?.[1];
39196
39567
  if (!loaded4) continue;
39197
39568
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded4}`);
39198
39569
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -39340,14 +39711,30 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39340
39711
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
39341
39712
  const range3 = obj.segPayloadRanges[segIdx];
39342
39713
  if (!range3) return;
39714
+ const [rangeStart, rangeEnd] = range3;
39715
+ if (rangeEnd - rangeStart < 4) return;
39343
39716
  let bytes = objectBytes.get(obj);
39344
39717
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs56.default.readFileSync(obj.file));
39345
- const text7 = bytes.toString("latin1", range3[0], range3[1]);
39346
- for (const match of text7.matchAll(/So(\d+)/g)) {
39347
- const start = match.index + 2 + match[1].length;
39348
- const length = Number(match[1]);
39349
- if (text7[start + length] !== "C") continue;
39350
- const symbol2 = `._OBJC_CLASS_${text7.slice(start, start + length)}`;
39718
+ let pos = rangeStart;
39719
+ while (pos < rangeEnd - 3) {
39720
+ const at = bytes.indexOf("So", pos);
39721
+ if (at < 0 || at >= rangeEnd - 2) break;
39722
+ let digitEnd = at + 2;
39723
+ let length = 0;
39724
+ while (digitEnd < rangeEnd) {
39725
+ const ch = bytes[digitEnd];
39726
+ if (ch < 48 || ch > 57) break;
39727
+ length = length * 10 + (ch - 48);
39728
+ digitEnd++;
39729
+ }
39730
+ if (digitEnd === at + 2) {
39731
+ pos = at + 2;
39732
+ continue;
39733
+ }
39734
+ pos = digitEnd;
39735
+ const nameEnd = digitEnd + length;
39736
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
39737
+ const symbol2 = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
39351
39738
  for (const provider of lazyProviders.get(symbol2) ?? []) {
39352
39739
  eagerDynamicObjects.add(provider);
39353
39740
  extractObject(provider);
@@ -40441,6 +40828,10 @@ var init_nativeDyldTableContract = __esm({
40441
40828
 
40442
40829
  // src/swift-guest-image-ledger.ts
40443
40830
  function readNumber(bytes, position) {
40831
+ if (position < bytes.length) {
40832
+ const first = bytes[position];
40833
+ if (first < 128) return [first, position + 1];
40834
+ }
40444
40835
  let value = 0;
40445
40836
  let shift = 0;
40446
40837
  for (; ; ) {
@@ -40452,6 +40843,7 @@ function readNumber(bytes, position) {
40452
40843
  }
40453
40844
  }
40454
40845
  function encodeNumber(value) {
40846
+ if (value < 128) return Buffer.from([value]);
40455
40847
  const bytes = [];
40456
40848
  do {
40457
40849
  let byte = value % 128;
@@ -40473,6 +40865,9 @@ function encodedString(value) {
40473
40865
  const bytes = Buffer.from(value);
40474
40866
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
40475
40867
  }
40868
+ function isWasmMagic(bytes) {
40869
+ 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;
40870
+ }
40476
40871
  function llvmType(value) {
40477
40872
  switch (value) {
40478
40873
  case 127:
@@ -40488,11 +40883,12 @@ function llvmType(value) {
40488
40883
  }
40489
40884
  }
40490
40885
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options2 = {}) {
40491
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
40492
- throw new Error("expected wasm object");
40886
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
40887
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
40493
40888
  const { sdkLookupOnly, sdkProduct } = options2;
40494
40889
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
40495
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
40890
+ const rewrite = binding !== void 0;
40891
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
40496
40892
  const types2 = [];
40497
40893
  const functionTypes = [];
40498
40894
  const definitions = [];
@@ -40506,45 +40902,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40506
40902
  const usedSymbols = /* @__PURE__ */ new Set();
40507
40903
  let position = 8;
40508
40904
  while (position < bytes.length) {
40905
+ const headerStart2 = position;
40509
40906
  const id = bytes[position++];
40510
- const [size2, start] = readNumber(bytes, position);
40907
+ let size2 = 0;
40908
+ if (position < bytes.length && bytes[position] < 128) {
40909
+ size2 = bytes[position++];
40910
+ } else {
40911
+ const [val, next] = readNumber(bytes, position);
40912
+ size2 = val;
40913
+ position = next;
40914
+ }
40915
+ const start = position;
40511
40916
  const end = start + size2;
40512
40917
  if (end > bytes.length) throw new Error("invalid wasm section");
40513
40918
  position = end;
40514
- if (!sections && id > 3) continue;
40515
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size2);
40516
- let offset = 0;
40919
+ if (id > 3) {
40920
+ if (sections) sections.push(bytes.subarray(headerStart2, end));
40921
+ continue;
40922
+ }
40923
+ let offset = start;
40517
40924
  const number4 = () => {
40518
- const [value, next] = readNumber(section2, offset);
40519
- offset = next;
40520
- return value;
40925
+ if (offset < end) {
40926
+ const first = bytes[offset];
40927
+ if (first < 128) {
40928
+ offset++;
40929
+ return first;
40930
+ }
40931
+ }
40932
+ let value = 0;
40933
+ let shift = 0;
40934
+ for (; ; ) {
40935
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
40936
+ const byte = bytes[offset++];
40937
+ value += (byte & 127) * 2 ** shift;
40938
+ if (!(byte & 128)) return value;
40939
+ shift += 7;
40940
+ }
40521
40941
  };
40522
40942
  const string8 = () => {
40523
- const [value, next] = readString(section2, offset);
40524
- offset = next;
40943
+ const length = number4();
40944
+ const strEnd = offset + length;
40945
+ if (strEnd > end) throw new Error("invalid wasm string");
40946
+ const value = rawBuf.toString("utf8", offset, strEnd);
40947
+ offset = strEnd;
40525
40948
  return value;
40526
40949
  };
40950
+ let rewrittenSection;
40527
40951
  if (id === 1) {
40528
40952
  const count = number4();
40529
40953
  for (let i = 0; i < count; i++) {
40530
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
40954
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
40531
40955
  const parameterCount = number4();
40532
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
40533
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
40534
- offset += parameterCount;
40956
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
40957
+ const parameters = new Array(parameterCount);
40958
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
40535
40959
  const resultCount = number4();
40536
- const results = [...section2.subarray(offset, offset + resultCount)];
40537
- if (results.length !== resultCount) throw new Error("invalid wasm type");
40538
- offset += resultCount;
40960
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
40961
+ const results = new Array(resultCount);
40962
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
40539
40963
  types2.push({ parameters, results });
40540
40964
  }
40541
40965
  } else if (id === 2) {
40542
40966
  const count = number4();
40543
- const imports2 = sections ? [encodeNumber(count)] : void 0;
40967
+ const importWriter = rewrite ? new ByteWriter(size2 + 64) : void 0;
40968
+ importWriter?.uleb(count);
40544
40969
  for (let i = 0; i < count; i++) {
40545
40970
  const module2 = string8();
40546
40971
  const name3 = string8();
40547
- const kind = section2[offset++];
40972
+ const kind = bytes[offset++];
40548
40973
  const typeStart = offset;
40549
40974
  let functionType2 = -1;
40550
40975
  if (kind === 0) {
@@ -40552,7 +40977,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40552
40977
  functionTypes.push(functionType2);
40553
40978
  functionImportNames.push(name3);
40554
40979
  } else if (kind === 1) {
40555
- const referenceType = section2[offset++];
40980
+ const referenceType = bytes[offset++];
40556
40981
  if (referenceType !== 112 && referenceType !== 111)
40557
40982
  throw new Error("unsupported table type");
40558
40983
  const flags = number4();
@@ -40571,11 +40996,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40571
40996
  } else throw new Error("unsupported wasm import");
40572
40997
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
40573
40998
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
40574
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
40575
- if (module2 === "env" && kind === 0 && names.has(name3)) {
40576
- const type = types2[functionType2];
40577
- if (!type) throw new Error(`missing import type for ${name3}`);
40578
- functionImports.set(name3, type);
40999
+ if (!rewrite) {
41000
+ if (module2 === "env" && names.has(name3)) {
41001
+ usedSymbols.add(name3);
41002
+ if (kind === 0) {
41003
+ const type = types2[functionType2];
41004
+ if (!type) throw new Error(`missing import type for ${name3}`);
41005
+ functionImports.set(name3, type);
41006
+ }
41007
+ }
40579
41008
  }
40580
41009
  if (isDlsym || isDlerror) {
40581
41010
  const type = types2[functionType2];
@@ -40585,17 +41014,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40585
41014
  }
40586
41015
  if (isDlsym) usesDlsym = true;
40587
41016
  if (isDlerror) usesDlerror = true;
40588
- imports2?.push(
40589
- encodedString(module2),
40590
- encodedString(
40591
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
40592
- ),
40593
- Buffer.from([kind]),
40594
- section2.subarray(typeStart, offset)
40595
- );
41017
+ if (importWriter && binding) {
41018
+ importWriter.string(module2);
41019
+ importWriter.string(
41020
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
41021
+ );
41022
+ importWriter.byte(kind);
41023
+ importWriter.bytes(bytes, typeStart, offset);
41024
+ }
40596
41025
  }
40597
- if (offset !== section2.length) throw new Error("invalid wasm import section");
40598
- if (imports2) section2 = Buffer.concat(imports2);
41026
+ if (offset !== end) throw new Error("invalid wasm import section");
41027
+ if (importWriter) rewrittenSection = importWriter.finish();
40599
41028
  } else if (id === 3) {
40600
41029
  const count = number4();
40601
41030
  for (let i = 0; i < count; i++) functionTypes.push(number4());
@@ -40604,43 +41033,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40604
41033
  if (sectionName === "linking") {
40605
41034
  const version2 = number4();
40606
41035
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
40607
- const subsections = [];
41036
+ const subsections = rewrite ? [] : void 0;
40608
41037
  let objcLoader;
40609
- while (offset < section2.length) {
40610
- const kind = section2[offset++];
41038
+ while (offset < end) {
41039
+ const kind = bytes[offset++];
40611
41040
  const length = number4();
40612
41041
  const stop = offset + length;
40613
- if (stop > section2.length) throw new Error("invalid linking subsection");
40614
- let content = section2.subarray(offset, stop);
40615
- if (kind === 7 && !sdkLookupOnly) {
40616
- const groups = [];
41042
+ if (stop > end) throw new Error("invalid linking subsection");
41043
+ const contentStart = offset;
41044
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
41045
+ const comdatWriter = new ByteWriter(length + 64);
40617
41046
  const count = number4();
40618
- groups.push(encodeNumber(count));
41047
+ comdatWriter.uleb(count);
40619
41048
  for (let i = 0; i < count; i++) {
40620
41049
  const group = string8();
40621
41050
  const begin = offset;
40622
41051
  number4();
40623
41052
  const members2 = number4();
40624
41053
  for (let member = 0; member < members2 * 2; member++) number4();
40625
- groups.push(
40626
- encodedString(
40627
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
40628
- ),
40629
- section2.subarray(begin, offset)
41054
+ comdatWriter.string(
41055
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
40630
41056
  );
41057
+ comdatWriter.bytes(bytes, begin, offset);
40631
41058
  }
40632
41059
  if (offset !== stop) throw new Error("invalid comdat subsection");
40633
- content = Buffer.concat(groups);
40634
- }
40635
- if (kind === 8) {
40636
- const entries2 = [];
40637
- const extraEntries = [];
41060
+ const buf = comdatWriter.finish();
41061
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
41062
+ } else if (kind === 8) {
41063
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
41064
+ let extraWriter;
40638
41065
  const count = number4();
40639
- entries2.push(encodeNumber(count));
40640
41066
  let added = 0;
40641
41067
  for (let i = 0; i < count; i++) {
40642
41068
  const begin = offset;
40643
- const symbolKind = section2[offset++];
41069
+ const symbolKind = bytes[offset++];
40644
41070
  const flags = number4();
40645
41071
  const flagsEnd = offset;
40646
41072
  let index = -1;
@@ -40668,25 +41094,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40668
41094
  }
40669
41095
  } else if (symbolKind === 3) number4();
40670
41096
  else throw new Error("unsupported wasm symbol kind");
40671
- if (symbolKind === 0)
41097
+ if (!rewrite && symbolKind === 0)
40672
41098
  functionSymbols[i] = name3 || functionImportNames[index];
40673
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
41099
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
40674
41100
  objcLoader = i;
40675
41101
  }
40676
41102
  const alias = names.get(name3);
40677
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
40678
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
40679
- entries2.push(
40680
- section2.subarray(begin, nameStart),
40681
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
40682
- section2.subarray(nameEnd, offset)
40683
- );
40684
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
40685
- entries2.push(
40686
- section2.subarray(begin, nameStart),
40687
- encodedString(binding(name3)),
40688
- section2.subarray(nameEnd, offset)
40689
- );
41103
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
41104
+ usedSymbols.add(name3);
41105
+ if (entryWriter && binding) {
41106
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
41107
+ entryWriter.bytes(bytes, begin, nameStart);
41108
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
41109
+ entryWriter.bytes(bytes, nameEnd, offset);
41110
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
41111
+ entryWriter.bytes(bytes, begin, nameStart);
41112
+ entryWriter.string(binding(name3));
41113
+ entryWriter.bytes(bytes, nameEnd, offset);
41114
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
41115
+ if (symbolKind !== 0 && symbolKind !== 1)
41116
+ throw new Error(`unsupported symbol ${name3}`);
41117
+ if (preserveCanonical.has(name3)) {
41118
+ entryWriter.bytes(bytes, begin, offset);
41119
+ extraWriter ??= new ByteWriter(256);
41120
+ extraWriter.byte(bytes[begin]);
41121
+ extraWriter.uleb(flags & ~32);
41122
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
41123
+ extraWriter.string(alias);
41124
+ extraWriter.bytes(bytes, nameEnd, offset);
41125
+ added++;
41126
+ } else {
41127
+ entryWriter.bytes(bytes, begin, nameStart);
41128
+ entryWriter.string(alias);
41129
+ entryWriter.bytes(bytes, nameEnd, offset);
41130
+ }
41131
+ } else {
41132
+ entryWriter.bytes(bytes, begin, offset);
41133
+ }
40690
41134
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
40691
41135
  if (symbolKind !== 0 && symbolKind !== 1)
40692
41136
  throw new Error(`unsupported symbol ${name3}`);
@@ -40700,63 +41144,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40700
41144
  hidden: (flags & 4) !== 0,
40701
41145
  type
40702
41146
  });
40703
- if (preserveCanonical.has(name3)) {
40704
- entries2.push(section2.subarray(begin, offset));
40705
- extraEntries.push(
40706
- section2.subarray(begin, begin + 1),
40707
- encodeNumber(flags & ~32),
40708
- section2.subarray(flagsEnd, nameStart),
40709
- encodedString(alias),
40710
- section2.subarray(nameEnd, offset)
40711
- );
40712
- added++;
40713
- } else {
40714
- entries2.push(
40715
- section2.subarray(begin, nameStart),
40716
- encodedString(alias),
40717
- section2.subarray(nameEnd, offset)
40718
- );
40719
- }
40720
- } else entries2.push(section2.subarray(begin, offset));
41147
+ }
40721
41148
  }
40722
41149
  if (offset !== stop) throw new Error("invalid symbol subsection");
40723
- entries2[0] = encodeNumber(count + added);
40724
- content = Buffer.concat([...entries2, ...extraEntries]);
41150
+ if (entryWriter) {
41151
+ const countBytes = encodeNumber(count + added);
41152
+ const entryBuf = entryWriter.finish();
41153
+ if (extraWriter) {
41154
+ const extraBuf = extraWriter.finish();
41155
+ subsections.push({
41156
+ kind,
41157
+ parts: [countBytes, entryBuf, extraBuf],
41158
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
41159
+ });
41160
+ } else {
41161
+ subsections.push({
41162
+ kind,
41163
+ parts: [countBytes, entryBuf],
41164
+ byteLength: countBytes.length + entryBuf.length
41165
+ });
41166
+ }
41167
+ }
41168
+ } else if (subsections) {
41169
+ subsections.push({
41170
+ kind,
41171
+ parts: [bytes.subarray(contentStart, stop)],
41172
+ byteLength: length
41173
+ });
40725
41174
  }
40726
41175
  offset = stop;
40727
- subsections.push({ kind, content });
40728
- }
40729
- const parts2 = [encodedString(sectionName), encodeNumber(version2)];
40730
- for (const subsection of subsections) {
40731
- let content = subsection.content;
40732
- if (subsection.kind === 6 && objcLoader !== void 0) {
40733
- const [count, entriesStart] = readNumber(content, 0);
40734
- const entries2 = [content.subarray(0, entriesStart)];
40735
- let entryStart = entriesStart;
40736
- for (let i = 0; i < count; i++) {
40737
- const [, symbolStart] = readNumber(content, entryStart);
40738
- const [symbol2, entryEnd] = readNumber(content, symbolStart);
40739
- if (symbol2 === objcLoader) entries2.push(encodeNumber(1));
40740
- entries2.push(
40741
- content.subarray(
40742
- symbol2 === objcLoader ? symbolStart : entryStart,
40743
- entryEnd
40744
- )
40745
- );
40746
- entryStart = entryEnd;
41176
+ }
41177
+ if (subsections) {
41178
+ const linkingWriter = new ByteWriter(size2 + 128);
41179
+ linkingWriter.string(sectionName);
41180
+ linkingWriter.uleb(version2);
41181
+ for (const subsection of subsections) {
41182
+ if (subsection.kind === 6 && objcLoader !== void 0) {
41183
+ const content = subsection.parts[0];
41184
+ const [count, entriesStart] = readNumber(content, 0);
41185
+ const initWriter = new ByteWriter(content.length + 16);
41186
+ initWriter.bytes(content, 0, entriesStart);
41187
+ let entryStart = entriesStart;
41188
+ for (let i = 0; i < count; i++) {
41189
+ const [, symbolStart] = readNumber(content, entryStart);
41190
+ const [symbol2, entryEnd] = readNumber(content, symbolStart);
41191
+ if (symbol2 === objcLoader) {
41192
+ initWriter.uleb(1);
41193
+ initWriter.bytes(content, symbolStart, entryEnd);
41194
+ } else {
41195
+ initWriter.bytes(content, entryStart, entryEnd);
41196
+ }
41197
+ entryStart = entryEnd;
41198
+ }
41199
+ if (entryStart !== content.length)
41200
+ throw new Error("invalid init functions subsection");
41201
+ const initBuf = initWriter.finish();
41202
+ linkingWriter.byte(subsection.kind);
41203
+ linkingWriter.uleb(initBuf.length);
41204
+ linkingWriter.bytes(initBuf);
41205
+ } else {
41206
+ linkingWriter.byte(subsection.kind);
41207
+ linkingWriter.uleb(subsection.byteLength);
41208
+ for (const part of subsection.parts) linkingWriter.bytes(part);
40747
41209
  }
40748
- if (entryStart !== content.length)
40749
- throw new Error("invalid init functions subsection");
40750
- content = Buffer.concat(entries2);
40751
41210
  }
40752
- parts2.push(
40753
- Buffer.from([subsection.kind]),
40754
- encodeNumber(content.length),
40755
- content
40756
- );
41211
+ rewrittenSection = linkingWriter.finish();
40757
41212
  }
40758
- section2 = Buffer.concat(parts2);
40759
- } else if (!sections && sectionName.startsWith("reloc.")) {
41213
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
40760
41214
  number4();
40761
41215
  for (let count = number4(); count > 0; count--) {
40762
41216
  const type = number4();
@@ -40766,18 +41220,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40766
41220
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
40767
41221
  addressTaken.add(name3);
40768
41222
  }
40769
- if (offset !== section2.length)
40770
- throw new Error(`invalid relocation section ${sectionName}`);
41223
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
41224
+ }
41225
+ }
41226
+ if (sections) {
41227
+ if (rewrittenSection) {
41228
+ sections.push(
41229
+ Buffer.from([id]),
41230
+ encodeNumber(rewrittenSection.length),
41231
+ rewrittenSection
41232
+ );
41233
+ } else {
41234
+ sections.push(bytes.subarray(headerStart2, end));
40771
41235
  }
40772
41236
  }
40773
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
40774
41237
  }
40775
41238
  return {
40776
41239
  bytes: sections ? Buffer.concat(sections) : bytes,
40777
41240
  definitions,
40778
41241
  functionImports,
40779
41242
  usesDlsym,
40780
- usedSymbols: [...usedSymbols],
41243
+ usedSymbols,
40781
41244
  addressTaken: [...addressTaken]
40782
41245
  };
40783
41246
  }
@@ -40866,36 +41329,51 @@ function createGuestImageLedger(input) {
40866
41329
  }
40867
41330
  }
40868
41331
  }
40869
- const nameBytes = /* @__PURE__ */ new Map();
40870
- for (const definition2 of definitions)
40871
- if (!nameBytes.has(definition2.name))
40872
- nameBytes.set(definition2.name, Buffer.from(definition2.name));
40873
- definitions.sort(
40874
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
40875
- );
41332
+ let hasNonAscii = false;
41333
+ for (const definition2 of definitions) {
41334
+ const s = definition2.name;
41335
+ for (let i = 0; i < s.length; i++) {
41336
+ if (s.charCodeAt(i) > 127) {
41337
+ hasNonAscii = true;
41338
+ break;
41339
+ }
41340
+ }
41341
+ if (hasNonAscii) break;
41342
+ }
41343
+ if (hasNonAscii) {
41344
+ const nameBytes = /* @__PURE__ */ new Map();
41345
+ for (const definition2 of definitions)
41346
+ if (!nameBytes.has(definition2.name))
41347
+ nameBytes.set(definition2.name, Buffer.from(definition2.name));
41348
+ definitions.sort(
41349
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
41350
+ );
41351
+ } else {
41352
+ definitions.sort(
41353
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
41354
+ );
41355
+ }
40876
41356
  const preserveCanonical = /* @__PURE__ */ new Set();
40877
41357
  const definitionsByName = Map.groupBy(definitions, (definition2) => definition2.name);
40878
- for (const name3 of input.symbols) {
41358
+ if (symbolIndices.has("__cxa_throw")) {
41359
+ const name3 = "__cxa_throw";
40879
41360
  const matching2 = definitionsByName.get(name3) ?? [];
40880
- if (new Set(matching2.map((definition2) => definition2.image)).size < 2 || !matching2.some((definition2) => definition2.weak))
40881
- continue;
40882
- const weak = matching2.filter((definition2) => definition2.weak);
40883
- const strong = matching2.filter((definition2) => !definition2.weak);
40884
- if (name3 !== "__cxa_throw") continue;
40885
- if (weak.length !== 1 || strong.length !== 1)
40886
- throw new Error(`unsupported weak interposition for ${name3}`);
40887
- const [local] = weak;
40888
- const [runtime] = strong;
40889
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
40890
- throw new Error(`incompatible weak interposition for ${name3}`);
40891
- for (const caller of input.callers) {
40892
- const uses = caller.image === local.image || units.some(
40893
- (unit2) => unit2.image === caller.image && unit2.usedSymbols.includes(name3)
40894
- );
40895
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
40896
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
41361
+ if (new Set(matching2.map((definition2) => definition2.image)).size >= 2 && matching2.some((definition2) => definition2.weak)) {
41362
+ const weak = matching2.filter((definition2) => definition2.weak);
41363
+ const strong = matching2.filter((definition2) => !definition2.weak);
41364
+ if (weak.length !== 1 || strong.length !== 1)
41365
+ throw new Error(`unsupported weak interposition for ${name3}`);
41366
+ const [local] = weak;
41367
+ const [runtime] = strong;
41368
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
41369
+ throw new Error(`incompatible weak interposition for ${name3}`);
41370
+ for (const caller of input.callers) {
41371
+ const uses = caller.image === local.image || units.some((unit2) => unit2.image === caller.image && unit2.usedSymbols.has(name3));
41372
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
41373
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
41374
+ }
41375
+ preserveCanonical.add(name3);
40897
41376
  }
40898
- preserveCanonical.add(name3);
40899
41377
  }
40900
41378
  for (const name3 of [
40901
41379
  "dlsym",
@@ -40907,40 +41385,76 @@ function createGuestImageLedger(input) {
40907
41385
  ])
40908
41386
  preserveCanonical.add(name3);
40909
41387
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
40910
- const bindingsByImage = /* @__PURE__ */ new Map();
40911
- const definitionsByImage = Map.groupBy(definitions, (definition2) => definition2.image);
41388
+ const imageAliases = /* @__PURE__ */ new Map();
41389
+ const imageWeakNames = /* @__PURE__ */ new Map();
41390
+ const singleOwnerByName = /* @__PURE__ */ new Map();
41391
+ for (const definition2 of definitions) {
41392
+ let aliases = imageAliases.get(definition2.image);
41393
+ if (!aliases) imageAliases.set(definition2.image, aliases = /* @__PURE__ */ new Map());
41394
+ const existing = aliases.get(definition2.name);
41395
+ if (existing === void 0) {
41396
+ aliases.set(definition2.name, definition2.alias);
41397
+ if (definition2.weak) {
41398
+ let weak = imageWeakNames.get(definition2.image);
41399
+ if (!weak) imageWeakNames.set(definition2.image, weak = /* @__PURE__ */ new Set());
41400
+ weak.add(definition2.name);
41401
+ }
41402
+ const owner = singleOwnerByName.get(definition2.name);
41403
+ if (owner === void 0)
41404
+ singleOwnerByName.set(definition2.name, {
41405
+ image: definition2.image,
41406
+ alias: definition2.alias
41407
+ });
41408
+ else if (owner !== null && owner.image !== definition2.image)
41409
+ singleOwnerByName.set(definition2.name, null);
41410
+ } else if (!definition2.weak && imageWeakNames.get(definition2.image)?.has(definition2.name)) {
41411
+ aliases.set(definition2.name, definition2.alias);
41412
+ imageWeakNames.get(definition2.image).delete(definition2.name);
41413
+ const owner = singleOwnerByName.get(definition2.name);
41414
+ if (owner && owner.image === definition2.image) owner.alias = definition2.alias;
41415
+ }
41416
+ }
41417
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
40912
41418
  for (const caller of input.callers) {
40913
- const bindings = /* @__PURE__ */ new Map();
40914
- const seen = /* @__PURE__ */ new Map();
40915
41419
  const scope2 = [caller.image, ...caller.next];
40916
41420
  if (input.systemImage !== void 0 && !scope2.includes(input.systemImage))
40917
41421
  scope2.push(input.systemImage);
40918
- for (const image of scope2)
40919
- for (const definition2 of definitionsByImage.get(image) ?? []) {
40920
- const previous = seen.get(definition2.name);
40921
- if (previous?.image === definition2.image) {
40922
- if (previous.weak && !definition2.weak) {
40923
- seen.set(definition2.name, definition2);
40924
- if (!preserveCanonical.has(definition2.name))
40925
- bindings.set(definition2.name, definition2.alias);
40926
- }
40927
- continue;
40928
- }
40929
- if (!previous) {
40930
- seen.set(definition2.name, definition2);
40931
- if (!preserveCanonical.has(definition2.name))
40932
- bindings.set(definition2.name, definition2.alias);
41422
+ const scopeSet = new Set(scope2);
41423
+ const scopeMaps = [];
41424
+ const seenImages = /* @__PURE__ */ new Set();
41425
+ for (const image of scope2) {
41426
+ if (seenImages.has(image)) continue;
41427
+ seenImages.add(image);
41428
+ const aliases = imageAliases.get(image);
41429
+ if (aliases) scopeMaps.push(aliases);
41430
+ }
41431
+ const cache = /* @__PURE__ */ new Map();
41432
+ sharedLookupByImage.set(caller.image, (name3) => {
41433
+ if (preserveCanonical.has(name3)) return void 0;
41434
+ const single = singleOwnerByName.get(name3);
41435
+ if (single === void 0) return void 0;
41436
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
41437
+ const hit = cache.get(name3);
41438
+ if (hit !== void 0) return hit ?? void 0;
41439
+ for (const aliases of scopeMaps) {
41440
+ const alias = aliases.get(name3);
41441
+ if (alias !== void 0) {
41442
+ cache.set(name3, alias);
41443
+ return alias;
40933
41444
  }
40934
41445
  }
40935
- bindingsByImage.set(caller.image, bindings);
41446
+ cache.set(name3, null);
41447
+ return void 0;
41448
+ });
40936
41449
  }
40937
41450
  const startup = /* @__PURE__ */ new Map();
41451
+ const unitsByPath = new Map(units.map((unit2) => [unit2.object.path, unit2]));
40938
41452
  for (const binding of input.directBindings ?? []) {
40939
- const unit2 = units.find(({ object: object8 }) => object8.path === binding.object);
41453
+ const unit2 = unitsByPath.get(binding.object);
40940
41454
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
40941
41455
  (definition2) => definition2.object === binding.providerObject && definition2.image === binding.providerImage
40942
41456
  );
40943
- if (!unit2 || !unit2.usedSymbols.includes(binding.symbol) || matches.length !== 1)
41457
+ if (!unit2 || !unit2.usedSymbols.has(binding.symbol) || matches.length !== 1)
40944
41458
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
40945
41459
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
40946
41460
  if (bindings.has(binding.symbol))
@@ -40981,11 +41495,11 @@ function createGuestImageLedger(input) {
40981
41495
  }
40982
41496
  }
40983
41497
  const objects = units.map(({ image, object: object8, aliases, functionImports }) => {
40984
- const shared = bindingsByImage.get(image);
41498
+ const shared = sharedLookupByImage.get(image);
40985
41499
  const own2 = startup.get(object8.path);
40986
41500
  const bindings = new Map(own2);
40987
41501
  const weak = input.sdkWeakReferences?.get(object8.path);
40988
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
41502
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
40989
41503
  for (const [name3, type] of functionImports) {
40990
41504
  const alias = binding(name3);
40991
41505
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -41250,7 +41764,7 @@ function nameGuestImageAliases(wasm, symbols) {
41250
41764
  }
41251
41765
  return Buffer.concat(parts2);
41252
41766
  }
41253
- var import_node_crypto31, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
41767
+ var import_node_crypto31, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
41254
41768
  var init_swift_guest_image_ledger = __esm({
41255
41769
  "src/swift-guest-image-ledger.ts"() {
41256
41770
  "use strict";
@@ -41258,6 +41772,57 @@ var init_swift_guest_image_ledger = __esm({
41258
41772
  init_nativeWasmContract();
41259
41773
  init_swift_sdk_image_wasm();
41260
41774
  init_swiftSdkLinkContract();
41775
+ ByteWriter = class {
41776
+ buf;
41777
+ pos = 0;
41778
+ constructor(initialCapacity = 256) {
41779
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
41780
+ }
41781
+ ensure(extra) {
41782
+ const needed = this.pos + extra;
41783
+ if (needed <= this.buf.length) return;
41784
+ let next = this.buf.length * 2;
41785
+ while (next < needed) next *= 2;
41786
+ const grown = Buffer.allocUnsafe(next);
41787
+ this.buf.copy(grown, 0, 0, this.pos);
41788
+ this.buf = grown;
41789
+ }
41790
+ byte(value) {
41791
+ this.ensure(1);
41792
+ this.buf[this.pos++] = value;
41793
+ }
41794
+ uleb(value) {
41795
+ this.ensure(10);
41796
+ let pos = this.pos;
41797
+ const buf = this.buf;
41798
+ do {
41799
+ let byte = value % 128;
41800
+ value = Math.floor(value / 128);
41801
+ if (value) byte |= 128;
41802
+ buf[pos++] = byte;
41803
+ } while (value);
41804
+ this.pos = pos;
41805
+ }
41806
+ bytes(source, start = 0, end = source.length) {
41807
+ const len = end - start;
41808
+ if (len <= 0) return;
41809
+ this.ensure(len);
41810
+ this.buf.set(source.subarray(start, end), this.pos);
41811
+ this.pos += len;
41812
+ }
41813
+ string(value) {
41814
+ const len = Buffer.byteLength(value, "utf8");
41815
+ this.uleb(len);
41816
+ if (len > 0) {
41817
+ this.ensure(len);
41818
+ this.buf.write(value, this.pos, len, "utf8");
41819
+ this.pos += len;
41820
+ }
41821
+ }
41822
+ finish() {
41823
+ return this.buf.subarray(0, this.pos);
41824
+ }
41825
+ };
41261
41826
  OBJC_INIT_RECORD = ".objc_init";
41262
41827
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
41263
41828
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -41875,8 +42440,11 @@ function moveGuestDyldTable(map2, wasm, symbols, bindingValues = /* @__PURE__ */
41875
42440
  function guestDyldValueRange(map2) {
41876
42441
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
41877
42442
  let found2;
41878
- for (const line of map2.split("\n")) {
41879
- if (!line.endsWith(suffix)) continue;
42443
+ for (let at = map2.indexOf(suffix); at !== -1; at = map2.indexOf(suffix, at + suffix.length)) {
42444
+ const lineEnd = at + suffix.length;
42445
+ if (lineEnd < map2.length && map2.charCodeAt(lineEnd) !== 10) continue;
42446
+ const lineStart = map2.lastIndexOf("\n", at) + 1;
42447
+ const line = map2.slice(lineStart, lineEnd);
41880
42448
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
41881
42449
  if (!match) throw new Error("unreadable dyld values map line");
41882
42450
  if (found2) throw new Error("link map has several dyld value sections");
@@ -41929,7 +42497,7 @@ var init_swift_guest_link_plan = __esm({
41929
42497
  });
41930
42498
 
41931
42499
  // src/swift-guest-manifest.ts
41932
- function selectedGuestManifestInputs(plan, selection, identities) {
42500
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
41933
42501
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
41934
42502
  const archives = /* @__PURE__ */ new Map();
41935
42503
  const images = /* @__PURE__ */ new Map();
@@ -41940,19 +42508,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
41940
42508
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
41941
42509
  let bytes;
41942
42510
  let memberIdentity = null;
41943
- if (item.member === null) bytes = (0, import_node_fs58.readFileSync)(item.artifact);
41944
- else {
41945
- let members2 = archives.get(item.artifact);
41946
- if (!members2) {
41947
- members2 = readArMembers((0, import_node_fs58.readFileSync)(item.artifact));
41948
- archives.set(item.artifact, members2);
42511
+ if (item.member === null) {
42512
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs58.readFileSync)(item.artifact);
42513
+ } else {
42514
+ if (readSelected) {
42515
+ bytes = readSelected(item);
42516
+ } else {
42517
+ let members2 = archives.get(item.artifact);
42518
+ if (!members2) {
42519
+ members2 = /* @__PURE__ */ new Map();
42520
+ for (const member of readArMembers((0, import_node_fs58.readFileSync)(item.artifact))) {
42521
+ let list2 = members2.get(member.name);
42522
+ if (!list2) members2.set(member.name, list2 = []);
42523
+ list2.push(member.bytes);
42524
+ }
42525
+ archives.set(item.artifact, members2);
42526
+ }
42527
+ const matching2 = members2.get(item.member);
42528
+ if (!matching2 || matching2.length !== 1)
42529
+ throw new Error(
42530
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
42531
+ );
42532
+ bytes = matching2[0];
41949
42533
  }
41950
- const matching2 = members2.filter((member) => member.name === item.member);
41951
- if (matching2.length !== 1)
41952
- throw new Error(
41953
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
41954
- );
41955
- bytes = matching2[0].bytes;
41956
42534
  const origin = artifact.memberOrigins?.get(item.member);
41957
42535
  if (artifact.memberOrigins && !origin)
41958
42536
  throw new Error(
@@ -42044,7 +42622,7 @@ var init_swift_guest_manifest = __esm({
42044
42622
  function isSwiftGuestImageManifest(value) {
42045
42623
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
42046
42624
  const text7 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
42047
- const name3 = (value2) => text7(value2) && new TextEncoder().encode(value2).length <= 16;
42625
+ const name3 = (value2) => text7(value2) && Buffer.byteLength(value2, "utf8") <= 16;
42048
42626
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
42049
42627
  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))
42050
42628
  return false;
@@ -42358,27 +42936,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
42358
42936
  function finalizeGuestProjectionStorage(options2) {
42359
42937
  const owner = options2.owners.get(options2.projectionObject);
42360
42938
  if (owner === void 0) throw new Error("guest projection object has no image owner");
42939
+ const ranges = [];
42361
42940
  const spans = guestLinkedSpans(
42362
42941
  options2.map,
42363
42942
  options2.linked,
42364
42943
  options2.optimized,
42365
42944
  options2.owners,
42366
42945
  options2.sectionOwners,
42367
- options2.sdkSpans !== void 0
42946
+ options2.sdkSpans !== void 0,
42947
+ {
42948
+ trackedObject: options2.projectionObject,
42949
+ trackedObjectOwner: owner,
42950
+ trackedLinearSpans: ranges
42951
+ }
42368
42952
  );
42369
42953
  const images = planGuestProjectionRegions(
42370
42954
  options2.reserved.images,
42371
42955
  options2.reserved.capacities,
42372
42956
  options2.sdkSpans ? [...spans, ...options2.sdkSpans] : spans
42373
42957
  );
42374
- const ranges = guestLinkedSpans(
42375
- options2.map,
42376
- options2.linked,
42377
- options2.optimized,
42378
- /* @__PURE__ */ new Map([[options2.projectionObject, owner]]),
42379
- void 0,
42380
- options2.sdkSpans !== void 0
42381
- ).filter((span) => span.space === "linear-memory");
42382
42958
  const result = Buffer.from(options2.optimized);
42383
42959
  const data = guestWasmDataSegments(options2.optimized, options2.sdkSpans === void 0);
42384
42960
  const locations = /* @__PURE__ */ new Map();
@@ -43446,7 +44022,7 @@ function occurrences(plan, args) {
43446
44022
  throw new Error("guest plan does not match linker inputs");
43447
44023
  return found2;
43448
44024
  }
43449
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
44025
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
43450
44026
  const rows = whyExtract.trimEnd().split("\n");
43451
44027
  if (rows.shift() !== "reference extracted symbol")
43452
44028
  throw new Error("invalid wasm-ld extraction report");
@@ -43461,8 +44037,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
43461
44037
  for (const file of extracted)
43462
44038
  if (!traced.has(file))
43463
44039
  throw new Error(`extracted guest input is absent from link trace ${file}`);
44040
+ const foundOccurrences = occurrences(plan, args);
44041
+ const archivePaths = /* @__PURE__ */ new Set();
44042
+ for (const { artifact } of foundOccurrences)
44043
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
44044
+ const tracedMembers = /* @__PURE__ */ new Map();
44045
+ if (archivePaths.size > 0) {
44046
+ const archivePrefixes = [...archivePaths].map(
44047
+ (archivePath) => [archivePath, `${archivePath}(`]
44048
+ );
44049
+ for (const item of traced) {
44050
+ if (!item.endsWith(")")) continue;
44051
+ const open = item.lastIndexOf("(");
44052
+ if (open > 0) {
44053
+ const archivePath = item.slice(0, open);
44054
+ if (archivePaths.has(archivePath)) {
44055
+ let list2 = tracedMembers.get(archivePath);
44056
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
44057
+ list2.push(item.slice(open + 1, -1));
44058
+ continue;
44059
+ }
44060
+ }
44061
+ for (const [archivePath, prefix] of archivePrefixes) {
44062
+ if (item.startsWith(prefix)) {
44063
+ let list2 = tracedMembers.get(archivePath);
44064
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
44065
+ list2.push(item.slice(prefix.length, -1));
44066
+ }
44067
+ }
44068
+ }
44069
+ }
43464
44070
  const result = [];
43465
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
44071
+ for (const { artifact, lazy, whole } of foundOccurrences) {
43466
44072
  if (artifact.kind === "object") {
43467
44073
  if (!lazy && !traced.has(artifact.path))
43468
44074
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -43470,15 +44076,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
43470
44076
  result.push({ artifact: artifact.path, member: null });
43471
44077
  continue;
43472
44078
  }
43473
- const prefix = `${artifact.path}(`;
43474
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
43475
- const members2 = readArMembers(import_node_fs61.default.readFileSync(artifact.path));
44079
+ const names = tracedMembers.get(artifact.path) ?? [];
44080
+ const nameSet = new Set(names);
44081
+ let members2 = archiveCache?.get(artifact.path);
44082
+ if (!members2) {
44083
+ members2 = readArMembers(import_node_fs61.default.readFileSync(artifact.path));
44084
+ archiveCache?.set(artifact.path, members2);
44085
+ }
44086
+ const memberCounts = /* @__PURE__ */ new Map();
43476
44087
  for (const member of members2) {
43477
- if (whole || names.includes(member.name))
44088
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
44089
+ if (whole || nameSet.has(member.name))
43478
44090
  result.push({ artifact: artifact.path, member: member.name });
43479
44091
  }
43480
44092
  for (const name3 of names)
43481
- if (members2.filter((member) => member.name === name3).length !== 1)
44093
+ if (memberCounts.get(name3) !== 1)
43482
44094
  throw new Error(
43483
44095
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
43484
44096
  );
@@ -43555,14 +44167,25 @@ function linkGuestImages(options2) {
43555
44167
  }
43556
44168
  const archives = /* @__PURE__ */ new Map();
43557
44169
  const memberBytes = /* @__PURE__ */ new Map();
44170
+ const objectBytes = /* @__PURE__ */ new Map();
43558
44171
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
43559
44172
  const providerSymbol = "__peach_dlsym_from_image";
43560
44173
  const readSelected = (item) => {
43561
- if (item.member === null) return import_node_fs61.default.readFileSync(item.artifact);
44174
+ if (item.member === null) {
44175
+ let bytes = objectBytes.get(item.artifact);
44176
+ if (!bytes) {
44177
+ bytes = import_node_fs61.default.readFileSync(item.artifact);
44178
+ objectBytes.set(item.artifact, bytes);
44179
+ }
44180
+ return bytes;
44181
+ }
43562
44182
  let byName2 = memberBytes.get(item.artifact);
43563
44183
  if (!byName2) {
43564
- const members2 = readArMembers(import_node_fs61.default.readFileSync(item.artifact));
43565
- archives.set(item.artifact, members2);
44184
+ let members2 = archives.get(item.artifact);
44185
+ if (!members2) {
44186
+ members2 = readArMembers(import_node_fs61.default.readFileSync(item.artifact));
44187
+ archives.set(item.artifact, members2);
44188
+ }
43566
44189
  byName2 = /* @__PURE__ */ new Map();
43567
44190
  for (const member of members2)
43568
44191
  if (!byName2.has(member.name))
@@ -43586,7 +44209,13 @@ function linkGuestImages(options2) {
43586
44209
  `--why-extract=${whyPath}`,
43587
44210
  `--Map=${mapPath}`
43588
44211
  ]);
43589
- return selectedGuestLinkInputs(plan, args, import_node_fs61.default.readFileSync(whyPath, "utf8"), trace);
44212
+ return selectedGuestLinkInputs(
44213
+ plan,
44214
+ args,
44215
+ import_node_fs61.default.readFileSync(whyPath, "utf8"),
44216
+ trace,
44217
+ archives
44218
+ );
43590
44219
  };
43591
44220
  const needsProvider = (item) => {
43592
44221
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -43626,7 +44255,7 @@ function linkGuestImages(options2) {
43626
44255
  )
43627
44256
  ]);
43628
44257
  const originalOwnership = identity2(plan);
43629
- const resolved = options2.resolvePlan(selected, plan);
44258
+ const resolved = options2.resolvePlan(selected, plan, readSelected);
43630
44259
  if (identity2(resolved) !== originalOwnership)
43631
44260
  throw new Error("resolved guest scopes changed input ownership");
43632
44261
  plan = resolved;
@@ -43680,6 +44309,7 @@ function linkGuestImages(options2) {
43680
44309
  }
43681
44310
  }
43682
44311
  let discoveryRegions;
44312
+ let liveSymbols;
43683
44313
  if (discoveryProjection && options2.projection) {
43684
44314
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options2.projection.image]]);
43685
44315
  for (const item of selected)
@@ -43688,10 +44318,15 @@ function linkGuestImages(options2) {
43688
44318
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
43689
44319
  );
43690
44320
  const wasm = import_node_fs61.default.readFileSync(discovery);
44321
+ liveSymbols = /* @__PURE__ */ new Set();
43691
44322
  discoveryRegions = guestProjectionRegionCounts(
43692
44323
  plan.images.length,
43693
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
44324
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
44325
+ collectSymbols: liveSymbols
44326
+ })
43694
44327
  );
44328
+ } else {
44329
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
43695
44330
  }
43696
44331
  const ledger = createGuestImageLedger({
43697
44332
  images: plan.images.map((image) => ({
@@ -43700,7 +44335,7 @@ function linkGuestImages(options2) {
43700
44335
  })),
43701
44336
  callers: plan.callers,
43702
44337
  symbols: plan.symbols,
43703
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
44338
+ liveSymbols,
43704
44339
  commandLineSymbols: commandLineSymbols(args),
43705
44340
  directBindings: plan.directBindings,
43706
44341
  registerAppTables: sdkCallers !== void 0,
@@ -43832,7 +44467,8 @@ function linkGuestImages(options2) {
43832
44467
  const selectedInputs = selectedGuestManifestInputs(
43833
44468
  plan,
43834
44469
  selected,
43835
- projection.identities
44470
+ projection.identities,
44471
+ readSelected
43836
44472
  );
43837
44473
  const images = projection.images.map(
43838
44474
  (image) => createGuestImageManifest({
@@ -43842,6 +44478,9 @@ function linkGuestImages(options2) {
43842
44478
  regions: []
43843
44479
  })
43844
44480
  );
44481
+ objectBytes.clear();
44482
+ memberBytes.clear();
44483
+ archives.clear();
43845
44484
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
43846
44485
  const regionsBefore = discoveryRegions;
43847
44486
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs61.default.readFileSync(ledgerObject)], 0);
@@ -43867,6 +44506,7 @@ function linkGuestImages(options2) {
43867
44506
  { stdio: "pipe" }
43868
44507
  );
43869
44508
  finalTrace = linkFinal(projectionObject, callerMap ? void 0 : layoutMap);
44509
+ if (sharedSdk) break;
43870
44510
  const wasm = import_node_fs61.default.readFileSync(finalOutput);
43871
44511
  const actual = guestProjectionRegionCounts(
43872
44512
  images.length,
@@ -43935,10 +44575,47 @@ ${changed2.join("\n")}`
43935
44575
  }
43936
44576
  function linkedMapSymbols(lines) {
43937
44577
  const names = /* @__PURE__ */ new Set();
43938
- const symbol2 = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
43939
44578
  for (const line of lines) {
43940
- const match = symbol2.exec(line);
43941
- if (match) names.add(match[1]);
44579
+ const length = line.length;
44580
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
44581
+ let pos = 1;
44582
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44583
+ const c1 = pos;
44584
+ while (pos < length) {
44585
+ const ch = line.charCodeAt(pos);
44586
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
44587
+ pos++;
44588
+ }
44589
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
44590
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44591
+ const c2 = pos;
44592
+ while (pos < length) {
44593
+ const ch = line.charCodeAt(pos);
44594
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
44595
+ pos++;
44596
+ }
44597
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
44598
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44599
+ const c3 = pos;
44600
+ while (pos < length) {
44601
+ const ch = line.charCodeAt(pos);
44602
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
44603
+ pos++;
44604
+ }
44605
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
44606
+ const sStart = pos;
44607
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44608
+ if (pos - sStart < 9 || pos >= length) continue;
44609
+ const first = line.charCodeAt(pos);
44610
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
44611
+ continue;
44612
+ let end = pos + 1;
44613
+ while (end < length) {
44614
+ const ch = line.charCodeAt(end);
44615
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
44616
+ end++;
44617
+ }
44618
+ names.add(line.slice(pos, end));
43942
44619
  }
43943
44620
  return names;
43944
44621
  }
@@ -44037,7 +44714,7 @@ function discoverGuestLinkInputs(options2) {
44037
44714
  import_node_fs61.default.mkdirSync(options2.directory, { recursive: true });
44038
44715
  const why = import_node_path61.default.join(options2.directory, "preselection-why.txt");
44039
44716
  const response = import_node_path61.default.join(options2.directory, "preselection.rsp");
44040
- const output = import_node_path61.default.join(options2.directory, "preselection.wasm");
44717
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path61.default.join(options2.directory, "preselection.wasm");
44041
44718
  const flags = [
44042
44719
  ...withOutput(args, output, true),
44043
44720
  ...options2.objects,
@@ -44135,7 +44812,7 @@ function prepareGuestRuntimeInputs(options2) {
44135
44812
  });
44136
44813
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
44137
44814
  }
44138
- function selectedGuestSymbolInputs(plan, selected) {
44815
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
44139
44816
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
44140
44817
  const archives = /* @__PURE__ */ new Map();
44141
44818
  const symbols = /* @__PURE__ */ new Set();
@@ -44151,22 +44828,27 @@ function selectedGuestSymbolInputs(plan, selected) {
44151
44828
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
44152
44829
  let bytes;
44153
44830
  let name3 = item.artifact;
44154
- if (item.member === null) bytes = import_node_fs61.default.readFileSync(item.artifact);
44155
- else {
44156
- let members2 = archives.get(item.artifact);
44157
- if (!members2) {
44158
- members2 = Map.groupBy(
44159
- readArMembers(import_node_fs61.default.readFileSync(item.artifact)),
44160
- (member) => member.name
44161
- );
44162
- archives.set(item.artifact, members2);
44831
+ if (item.member === null) {
44832
+ bytes = readSelected ? readSelected(item) : import_node_fs61.default.readFileSync(item.artifact);
44833
+ } else {
44834
+ if (readSelected) {
44835
+ bytes = readSelected(item);
44836
+ } else {
44837
+ let members2 = archives.get(item.artifact);
44838
+ if (!members2) {
44839
+ members2 = Map.groupBy(
44840
+ readArMembers(import_node_fs61.default.readFileSync(item.artifact)),
44841
+ (member) => member.name
44842
+ );
44843
+ archives.set(item.artifact, members2);
44844
+ }
44845
+ const matching2 = members2.get(item.member) ?? [];
44846
+ if (matching2.length !== 1)
44847
+ throw new Error(
44848
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
44849
+ );
44850
+ bytes = matching2[0].bytes;
44163
44851
  }
44164
- const matching2 = members2.get(item.member) ?? [];
44165
- if (matching2.length !== 1)
44166
- throw new Error(
44167
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
44168
- );
44169
- bytes = matching2[0].bytes;
44170
44852
  name3 += `(${item.member})`;
44171
44853
  }
44172
44854
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -44179,9 +44861,9 @@ function selectedGuestSymbolInputs(plan, selected) {
44179
44861
  for (const symbol2 of names.tags) tags.add(symbol2);
44180
44862
  for (const symbol2 of names.defined) {
44181
44863
  definitions.add(symbol2);
44182
- const objects = definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
44864
+ let objects = definitionObjects.get(symbol2);
44865
+ if (!objects) definitionObjects.set(symbol2, objects = /* @__PURE__ */ new Set());
44183
44866
  objects.add(name3);
44184
- definitionObjects.set(symbol2, objects);
44185
44867
  }
44186
44868
  }
44187
44869
  return {
@@ -44202,7 +44884,7 @@ function verifyGuestSymbolScopes(options2) {
44202
44884
  if (!symbols.length) return { bindings: [], directBindings: [] };
44203
44885
  import_node_fs61.default.mkdirSync(options2.directory, { recursive: true });
44204
44886
  const response = import_node_path61.default.join(options2.directory, "scope-trace.rsp");
44205
- const output = import_node_path61.default.join(options2.directory, "scope-trace.wasm");
44887
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path61.default.join(options2.directory, "scope-trace.wasm");
44206
44888
  const args = [
44207
44889
  ...withOutput(normalizedGuestLinkArgs(options2.args), output, true),
44208
44890
  ...options2.objects,
@@ -44220,55 +44902,76 @@ function verifyGuestSymbolScopes(options2) {
44220
44902
  import_node_fs61.default.closeSync(traceOutput);
44221
44903
  }
44222
44904
  const records = /* @__PURE__ */ new Map();
44223
- const consume = (line) => {
44224
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
44225
- if (!match) return;
44226
- const [, object8, kind, symbol2] = match;
44227
- if (!requested.has(symbol2)) return;
44228
- if (options2.hostImports.has(symbol2)) return;
44229
- const record6 = records.get(symbol2) ?? {
44230
- references: /* @__PURE__ */ new Map(),
44231
- providers: /* @__PURE__ */ new Map(),
44232
- physicalModule: false
44233
- };
44905
+ for (const line of guestLinkLines(tracePath)) {
44906
+ const refSep = line.lastIndexOf(": reference to ");
44907
+ const defSep = line.lastIndexOf(": definition of ");
44908
+ if (refSep < 0 && defSep < 0) continue;
44909
+ const isRef = refSep > defSep;
44910
+ const sep3 = isRef ? refSep : defSep;
44911
+ const symbol2 = line.slice(sep3 + (isRef ? 15 : 16));
44912
+ if (!requested.has(symbol2) || options2.hostImports.has(symbol2)) continue;
44913
+ let record6 = records.get(symbol2);
44914
+ if (!record6) {
44915
+ record6 = {
44916
+ references: /* @__PURE__ */ new Map(),
44917
+ providers: /* @__PURE__ */ new Map(),
44918
+ physicalModule: false
44919
+ };
44920
+ records.set(symbol2, record6);
44921
+ }
44922
+ const object8 = line.slice(0, sep3);
44234
44923
  if (object8 === "<internal>") {
44235
- if (kind === "definition of") record6.physicalModule = true;
44924
+ if (!isRef) record6.physicalModule = true;
44236
44925
  } else {
44237
44926
  const image = options2.owners.get(object8);
44238
44927
  if (image === void 0)
44239
44928
  throw new Error(`traced guest object has no owner ${object8}`);
44240
- (kind === "reference to" ? record6.references : record6.providers).set(
44241
- object8,
44242
- image
44243
- );
44929
+ (isRef ? record6.references : record6.providers).set(object8, image);
44244
44930
  }
44245
- records.set(symbol2, record6);
44246
- };
44247
- for (const line of guestLinkLines(tracePath)) consume(line);
44931
+ }
44248
44932
  const callers = new Map(options2.callers.map((caller) => [caller.image, caller.next]));
44933
+ const callerSets = new Map(
44934
+ options2.callers.map((caller) => [caller.image, new Set(caller.next)])
44935
+ );
44936
+ const rootScope = callerSets.get(0);
44249
44937
  const result = [];
44250
44938
  const directBindings = [];
44251
44939
  for (const symbol2 of symbols) {
44252
44940
  const record6 = records.get(symbol2);
44253
44941
  if (!record6 || !record6.references.size) continue;
44254
44942
  if (!record6.providers.size && options2.hostImports.has(symbol2)) continue;
44255
- const startupReferences = [...record6.references].filter(
44256
- ([object8]) => options2.startupObjects.has(object8) && options2.weakReferences.get(object8)?.has(symbol2)
44257
- );
44258
- const otherReferences = [...record6.references].filter(
44259
- ([object8]) => !startupReferences.some(([startup]) => startup === object8)
44260
- );
44943
+ const startupReferences = [];
44944
+ const otherReferences = [];
44945
+ let allWeakRefs = true;
44946
+ for (const [object8, caller] of record6.references) {
44947
+ const isWeakRef = options2.weakReferences.get(object8)?.has(symbol2) === true;
44948
+ if (!isWeakRef) allWeakRefs = false;
44949
+ if (isWeakRef && options2.startupObjects.has(object8)) {
44950
+ startupReferences.push([object8, caller]);
44951
+ } else {
44952
+ otherReferences.push([object8, caller]);
44953
+ }
44954
+ }
44261
44955
  for (const [, caller] of startupReferences)
44262
44956
  if (!callers.has(caller))
44263
44957
  throw new Error(`guest image has no caller scope ${caller}`);
44264
44958
  if (startupReferences.length && !record6.physicalModule) {
44265
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
44266
- if (candidates.size > 1 || record6.providers.size > 1)
44959
+ const candidates2 = options2.definitionObjects.get(symbol2);
44960
+ const candidateSize = candidates2?.size ?? 0;
44961
+ if (candidateSize > 1 || record6.providers.size > 1)
44267
44962
  throw new Error(`ambiguous startup provider ${symbol2}`);
44268
- if (candidates.size !== record6.providers.size || [...record6.providers.keys()].some((object8) => !candidates.has(object8)))
44269
- throw new Error(`unproven startup provider ${symbol2}`);
44963
+ let unproven = candidateSize !== record6.providers.size;
44964
+ if (!unproven && candidates2) {
44965
+ for (const object8 of record6.providers.keys()) {
44966
+ if (!candidates2.has(object8)) {
44967
+ unproven = true;
44968
+ break;
44969
+ }
44970
+ }
44971
+ }
44972
+ if (unproven) throw new Error(`unproven startup provider ${symbol2}`);
44270
44973
  if (record6.providers.size === 1) {
44271
- const [providerObject, providerImage] = [...record6.providers][0];
44974
+ const [providerObject, providerImage] = record6.providers.entries().next().value;
44272
44975
  if (options2.weakDefinitions.get(providerObject)?.has(symbol2))
44273
44976
  throw new Error(`weak startup provider ${symbol2}`);
44274
44977
  for (const [object8] of startupReferences)
@@ -44276,28 +44979,34 @@ function verifyGuestSymbolScopes(options2) {
44276
44979
  }
44277
44980
  if (!otherReferences.length) continue;
44278
44981
  }
44279
- if (!record6.providers.size && !record6.physicalModule && [...record6.references.keys()].every(
44280
- (object8) => options2.weakReferences.get(object8)?.has(symbol2)
44281
- ))
44282
- continue;
44982
+ if (!record6.providers.size && !record6.physicalModule && allWeakRefs) continue;
44283
44983
  const providerImages = new Set(record6.providers.values());
44284
- const copies = [...options2.definitionObjects.get(symbol2) ?? []].flatMap(
44285
- (object8) => {
44984
+ const candidates = options2.definitionObjects.get(symbol2);
44985
+ const copyImages = /* @__PURE__ */ new Set();
44986
+ const strongImages = /* @__PURE__ */ new Set();
44987
+ let weakDefinerImages;
44988
+ if (candidates) {
44989
+ for (const object8 of candidates) {
44286
44990
  const image = options2.owners.get(object8);
44287
- return image === void 0 ? [] : [{ image, weak: !!options2.weakDefinitions.get(object8)?.has(symbol2) }];
44991
+ if (image === void 0) continue;
44992
+ copyImages.add(image);
44993
+ if (options2.weakDefinitions.get(object8)?.has(symbol2)) {
44994
+ ;
44995
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
44996
+ } else {
44997
+ strongImages.add(image);
44998
+ }
44288
44999
  }
44289
- );
44290
- const copyImages = new Set(copies.map((copy) => copy.image));
44291
- const strongImages = new Set(
44292
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
44293
- );
45000
+ }
44294
45001
  const interposed = !record6.physicalModule && copyImages.size > 1;
44295
45002
  const providerCount = interposed ? 1 : providerImages.size + Number(record6.physicalModule);
44296
45003
  if (!providerCount) continue;
44297
45004
  if (providerCount !== 1)
44298
45005
  throw new Error(`guest symbol has ambiguous provider ${symbol2}`);
44299
- const scopedReferences = record6.physicalModule ? [...record6.references] : otherReferences;
44300
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
45006
+ const scopedReferences = record6.physicalModule ? record6.references : otherReferences;
45007
+ const firstProviderImage = providerImages.values().next().value;
45008
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
45009
+ let interposedByCaller;
44301
45010
  for (const [object8, caller] of scopedReferences) {
44302
45011
  const scope2 = callers.get(caller);
44303
45012
  if (!scope2) throw new Error(`guest image has no caller scope ${caller}`);
@@ -44305,18 +45014,35 @@ function verifyGuestSymbolScopes(options2) {
44305
45014
  result.push({ symbol: symbol2, caller, provider: { kind: "physical-module" } });
44306
45015
  continue;
44307
45016
  }
44308
- const provider = interposed ? [caller, ...scope2].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
45017
+ let provider;
45018
+ if (interposed) {
45019
+ if (interposedByCaller?.has(caller)) {
45020
+ provider = interposedByCaller.get(caller);
45021
+ } else {
45022
+ if (copyImages.has(caller)) {
45023
+ provider = caller;
45024
+ } else {
45025
+ for (const image of scope2) {
45026
+ if (copyImages.has(image)) {
45027
+ provider = image;
45028
+ break;
45029
+ }
45030
+ }
45031
+ if (provider === void 0) provider = uniqueProvider;
45032
+ }
45033
+ ;
45034
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
45035
+ }
45036
+ } else {
45037
+ provider = firstProviderImage;
45038
+ }
44309
45039
  if (provider === void 0) {
44310
45040
  if (options2.weakReferences.get(object8)?.has(symbol2)) continue;
44311
45041
  throw new Error(`guest scope ${caller} omits every provider of ${symbol2}`);
44312
45042
  }
44313
45043
  if (caller === provider) continue;
44314
- if ([...options2.definitionObjects.get(symbol2) ?? []].some(
44315
- (definer) => options2.owners.get(definer) === caller && options2.weakDefinitions.get(definer)?.has(symbol2)
44316
- ))
44317
- continue;
44318
- if (!scope2.includes(provider)) {
44319
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
45044
+ if (weakDefinerImages?.has(caller)) continue;
45045
+ if (!callerSets.get(caller).has(provider)) {
44320
45046
  const traced = [...record6.providers.keys()];
44321
45047
  const strongTraced = traced.filter(
44322
45048
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
@@ -44324,16 +45050,17 @@ function verifyGuestSymbolScopes(options2) {
44324
45050
  const providers = strongTraced.length === 1 ? strongTraced : traced;
44325
45051
  if (options2.weakReferences.get(object8)?.has(symbol2) && !providers.some((provider2) => options2.systemProviders.has(provider2)))
44326
45052
  continue;
44327
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
45053
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
45054
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
44328
45055
  (definer) => options2.weakDefinitions.get(definer)?.has(symbol2)
44329
45056
  );
44330
- const strongCandidates = [...candidates].filter(
45057
+ const strongCandidates = [...candidateSet].filter(
44331
45058
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
44332
45059
  );
44333
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
44334
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
45060
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
45061
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
44335
45062
  // scope, the root image and its dependency closure, as in elf.
44336
- provider === 0 || callers.get(0)?.includes(provider) || !options2.weakReferences.get(object8)?.has(symbol2) && options2.frameworkProviders.get(object8)?.has(providers[0]))))
45063
+ provider === 0 || rootScope?.has(provider) || !options2.weakReferences.get(object8)?.has(symbol2) && options2.frameworkProviders.get(object8)?.has(providers[0]))))
44337
45064
  throw new Error(
44338
45065
  `guest scope ${caller} omits traced provider ${provider} for ${symbol2}`
44339
45066
  );
@@ -44533,6 +45260,85 @@ function clangProducerStamp(file) {
44533
45260
  const stat2 = (0, import_node_fs62.statSync)(file, { bigint: true });
44534
45261
  return [stat2.dev, stat2.ino, stat2.size, stat2.mtimeNs, stat2.ctimeNs].join(":");
44535
45262
  }
45263
+ function clangBinaryStamp(file) {
45264
+ const stat2 = (0, import_node_fs62.statSync)(file, { bigint: true });
45265
+ return [file, stat2.size, stat2.mtimeNs].join(":");
45266
+ }
45267
+ function clangWrapperStamp(file) {
45268
+ return (0, import_node_crypto36.createHash)("sha256").update((0, import_node_fs62.readFileSync)(file)).digest("hex");
45269
+ }
45270
+ function clangArgsNeedCwd(args) {
45271
+ const pathFlags = /* @__PURE__ */ new Set([
45272
+ "-I",
45273
+ "-isystem",
45274
+ "-iquote",
45275
+ "-F",
45276
+ "-iframework",
45277
+ "-isysroot",
45278
+ "-o",
45279
+ "-MF"
45280
+ ]);
45281
+ const includeFlags = /* @__PURE__ */ new Set(["-include", "-imacros"]);
45282
+ const valueFlags = /* @__PURE__ */ new Set([
45283
+ "-x",
45284
+ "-target",
45285
+ "-MT",
45286
+ "-MQ",
45287
+ "-D",
45288
+ "-U",
45289
+ "-mllvm",
45290
+ "-Xclang",
45291
+ "-arch",
45292
+ "-std"
45293
+ ]);
45294
+ const prefixFlags = [
45295
+ "-I",
45296
+ "-F",
45297
+ "-isystem",
45298
+ "-iquote",
45299
+ "--sysroot=",
45300
+ "-fmodule-map-file=",
45301
+ "-fmodules-cache-path="
45302
+ ];
45303
+ const isRelativePath = (value) => value.length > 0 && !value.startsWith("/") && !value.startsWith("=/") && value !== "-";
45304
+ for (let i = 1; i < args.length; i++) {
45305
+ const arg = args[i];
45306
+ if (pathFlags.has(arg)) {
45307
+ if (isRelativePath(args[++i] ?? "")) return true;
45308
+ continue;
45309
+ }
45310
+ if (includeFlags.has(arg)) {
45311
+ const value = args[++i] ?? "";
45312
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs62.existsSync)(value))) return true;
45313
+ continue;
45314
+ }
45315
+ if (valueFlags.has(arg)) {
45316
+ i++;
45317
+ continue;
45318
+ }
45319
+ if (arg.startsWith("@")) {
45320
+ if (isRelativePath(arg.slice(1))) return true;
45321
+ continue;
45322
+ }
45323
+ if (arg.startsWith("-")) {
45324
+ if (arg.startsWith("-include") && arg.length > 8) {
45325
+ const value = arg.slice(8);
45326
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs62.existsSync)(value)))
45327
+ return true;
45328
+ continue;
45329
+ }
45330
+ for (const prefix of prefixFlags) {
45331
+ if (arg.startsWith(prefix) && arg.length > prefix.length) {
45332
+ if (isRelativePath(arg.slice(prefix.length))) return true;
45333
+ break;
45334
+ }
45335
+ }
45336
+ continue;
45337
+ }
45338
+ if (isRelativePath(arg)) return true;
45339
+ }
45340
+ return false;
45341
+ }
44536
45342
  function validateClangLinkOptions(flags) {
44537
45343
  for (let index = 0; index < flags.length; index++) {
44538
45344
  const flag = flags[index];
@@ -44612,7 +45418,7 @@ function sourceGuestClangLinkOptions(options2) {
44612
45418
  let clang;
44613
45419
  let clangStamp;
44614
45420
  let wrapperStamp;
44615
- for (const [index, file] of [...wanted].entries()) {
45421
+ for (const file of wanted) {
44616
45422
  const command = commands.get(file);
44617
45423
  if (!command) throw new Error(`missing source object producer ${file}`);
44618
45424
  if (command.tool === "shell") {
@@ -44626,12 +45432,12 @@ function sourceGuestClangLinkOptions(options2) {
44626
45432
  throw new Error(`unsupported source object producer ${file}`);
44627
45433
  const key2 = (0, import_node_crypto36.createHash)("sha256").update(
44628
45434
  JSON.stringify([
44629
- "clang-link-options/v1",
44630
- process.cwd(),
45435
+ "clang-link-options/v2",
45436
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
44631
45437
  driverEnvironment,
44632
45438
  command.args,
44633
- clangStamp ??= clangProducerStamp(clang),
44634
- compiler === clang ? null : wrapperStamp ??= clangProducerStamp(compiler),
45439
+ clangStamp ??= clangBinaryStamp(clang),
45440
+ compiler === clang ? null : wrapperStamp ??= clangWrapperStamp(compiler),
44635
45441
  clangProducerStamp(file)
44636
45442
  ])
44637
45443
  ).digest("hex");
@@ -44646,31 +45452,44 @@ function sourceGuestClangLinkOptions(options2) {
44646
45452
  continue;
44647
45453
  }
44648
45454
  result.set(file, []);
44649
- const args = command.args.slice(1).filter((arg) => arg !== "-c");
44650
45455
  const targetBuild = import_node_path62.default.relative(options2.buildDirectory, file).split(import_node_path62.default.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
44651
- const outputDirectory = import_node_path62.default.join(
44652
- options2.directory,
44653
- targetBuild ?? import_node_path62.default.basename(import_node_path62.default.dirname(file))
44654
- );
44655
- (0, import_node_fs62.mkdirSync)(outputDirectory, { recursive: true });
44656
- const output = import_node_path62.default.join(outputDirectory, `clang-link-${index}.ll`);
44657
- for (const flag of ["-o", "-MF"]) {
44658
- const index2 = args.lastIndexOf(flag);
44659
- if (index2 < 0 || index2 + 1 >= args.length)
44660
- throw new Error(`missing clang ${flag} for ${file}`);
44661
- args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
45456
+ const args = [];
45457
+ let sawOutput = false;
45458
+ let explicitModuleName = false;
45459
+ for (let i = 1; i < command.args.length; i++) {
45460
+ const arg = command.args[i];
45461
+ if (arg === "-c" || arg === "-MD" || arg === "-MMD" || arg === "-MP") continue;
45462
+ if (arg === "-MF" || arg === "-MT" || arg === "-MQ") {
45463
+ if (i + 1 >= command.args.length)
45464
+ throw new Error(`missing clang ${arg} for ${file}`);
45465
+ i++;
45466
+ continue;
45467
+ }
45468
+ if (arg === "-o") {
45469
+ if (i + 1 >= command.args.length) throw new Error(`missing clang -o for ${file}`);
45470
+ i++;
45471
+ args.push("-o", "-");
45472
+ sawOutput = true;
45473
+ continue;
45474
+ }
45475
+ if (arg.startsWith("-fmodule-name=")) explicitModuleName = true;
45476
+ args.push(arg);
45477
+ }
45478
+ if (!sawOutput) throw new Error(`missing clang -o for ${file}`);
45479
+ if (compiler !== clang && targetBuild && !explicitModuleName) {
45480
+ args.unshift(`-fmodule-name=${targetBuild.slice(0, -".build".length)}`);
44662
45481
  }
44663
45482
  replays.push({
44664
45483
  file,
44665
45484
  compiler: command.args[0],
44666
45485
  args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
44667
- output,
44668
45486
  cacheFile,
44669
45487
  key: key2
44670
45488
  });
44671
45489
  }
44672
45490
  if (replays.length === 0) return result;
44673
45491
  const plan = import_node_path62.default.join(options2.directory, "clang-link-replays.json");
45492
+ const resultsPath = import_node_path62.default.join(options2.directory, "clang-link-results.json");
44674
45493
  (0, import_node_fs62.writeFileSync)(
44675
45494
  plan,
44676
45495
  JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
@@ -44683,12 +45502,16 @@ function sourceGuestClangLinkOptions(options2) {
44683
45502
  ...process.env,
44684
45503
  [PEACH_FORKED_SCRIPT_ENV]: "1",
44685
45504
  PEACH_CLANG_REPLAYS: plan,
45505
+ PEACH_CLANG_RESULTS: resultsPath,
44686
45506
  PEACH_CLANG_JOBS: String(options2.jobs)
44687
45507
  }
44688
45508
  });
45509
+ const replayMetadata = JSON.parse((0, import_node_fs62.readFileSync)(resultsPath, "utf8"));
45510
+ if (!Array.isArray(replayMetadata) || replayMetadata.length !== replays.length || !replayMetadata.every((item) => typeof item === "string"))
45511
+ throw new Error("invalid clang link replay results");
44689
45512
  (0, import_node_fs62.mkdirSync)(cacheDirectory, { recursive: true });
44690
- for (const { file, output, cacheFile, key: key2 } of replays) {
44691
- const flags = clangIrLinkOptions((0, import_node_fs62.readFileSync)(output, "utf8"));
45513
+ for (const [index, { file, cacheFile, key: key2 }] of replays.entries()) {
45514
+ const flags = clangIrLinkOptions(replayMetadata[index]);
44692
45515
  validateClangLinkOptions(flags);
44693
45516
  const temporary = `${cacheFile}.${process.pid}`;
44694
45517
  (0, import_node_fs62.writeFileSync)(temporary, JSON.stringify({ key: key2, flags }));
@@ -44926,22 +45749,47 @@ var init_swift_guest_source_inputs = __esm({
44926
45749
  CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
44927
45750
  PARALLEL_REPLAY = `
44928
45751
  const { spawn } = require('node:child_process')
44929
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
45752
+ const fs = require('node:fs')
45753
+ const commands = JSON.parse(fs.readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
45754
+ const results = new Array(commands.length)
44930
45755
  let next = 0
44931
45756
  const run = () => {
44932
45757
  if (next >= commands.length) return Promise.resolve()
44933
- const [file, ...args] = commands[next++]
45758
+ const index = next++
45759
+ const [file, ...args] = commands[index]
44934
45760
  return new Promise((resolve, reject) => {
44935
- const child = spawn(file, args, { stdio: 'inherit' })
45761
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'inherit'] })
45762
+ const metadata = []
45763
+ let pending = ''
45764
+ child.stdout.setEncoding('utf8')
45765
+ child.stdout.on('data', (chunk) => {
45766
+ const text = pending + chunk
45767
+ let start = 0
45768
+ for (let nl = text.indexOf('\\n'); nl !== -1; nl = text.indexOf('\\n', start)) {
45769
+ if (text.charCodeAt(start) === 33) metadata.push(text.slice(start, nl))
45770
+ start = nl + 1
45771
+ }
45772
+ pending = text.slice(start)
45773
+ })
44936
45774
  child.on('error', reject)
44937
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
45775
+ child.on('close', (code) => {
45776
+ if (pending.charCodeAt(0) === 33) metadata.push(pending)
45777
+ if (code === 0) {
45778
+ results[index] = metadata.join('\\n')
45779
+ resolve()
45780
+ } else reject(new Error('clang link replay failed: ' + file))
45781
+ })
44938
45782
  }).then(run)
44939
45783
  }
44940
45784
  const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
44941
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
44942
- console.error(error.message)
44943
- process.exit(1)
44944
- })
45785
+ Promise.all(Array.from({ length: jobs }, run))
45786
+ .then(() => {
45787
+ fs.writeFileSync(process.env.PEACH_CLANG_RESULTS, JSON.stringify(results))
45788
+ })
45789
+ .catch((error) => {
45790
+ console.error(error.message)
45791
+ process.exit(1)
45792
+ })
44945
45793
  `;
44946
45794
  }
44947
45795
  });
@@ -48774,6 +49622,7 @@ __export(swift_sdk_app_module_exports, {
48774
49622
  readSwiftSdkUsage: () => readSwiftSdkUsage,
48775
49623
  selectSwiftSdkData: () => selectSwiftSdkData,
48776
49624
  swiftAppModuleInputs: () => swiftAppModuleInputs,
49625
+ swiftSdkProjectionSpans: () => swiftSdkProjectionSpans,
48777
49626
  writeSwiftSdkAppLink: () => writeSwiftSdkAppLink
48778
49627
  });
48779
49628
  async function buildSwiftAppModule(options2) {
@@ -48889,15 +49738,18 @@ async function compileSdkForwarders(inputs2, sdk2, toolchainBin, output, project
48889
49738
  index++;
48890
49739
  }
48891
49740
  const errno = tls.errno;
49741
+ let declaredErrno = false;
48892
49742
  for (const name3 of referenced) {
48893
49743
  const offset = tls[name3];
48894
49744
  if (offset === void 0 || defined.has(name3)) continue;
48895
49745
  if (errno === void 0 || signatures.__errno_location !== ":j")
48896
49746
  throw new Error("the sdk image has no errno to find its thread block by");
48897
- if (!lines.some((line) => line.startsWith("char *__peach_errno(")))
49747
+ if (!declaredErrno) {
49748
+ declaredErrno = true;
48898
49749
  lines.push(
48899
49750
  `__attribute__((import_module("env"), import_name("__errno_location"))) char *__peach_errno(void);`
48900
49751
  );
49752
+ }
48901
49753
  lines.push(
48902
49754
  `__attribute__((weak)) _Thread_local char t${index} __asm__(${literal4(name3)});`,
48903
49755
  `__attribute__((used)) long long h${index}(void) __asm__(${literal4(SDK_TLS_HELPER + name3)});`,
@@ -49273,6 +50125,20 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49273
50125
  symbols.filter((symbol2) => symbol2.kind === 0 && symbol2.name.startsWith(SDK_TLS_HELPER)).map((symbol2) => [symbol2.name.slice(SDK_TLS_HELPER.length), symbol2.index])
49274
50126
  );
49275
50127
  const segments = guestWasmDataSegments(bytes, false);
50128
+ const segmentsByOffset = [...segments].sort((a, b) => a.offset - b.offset);
50129
+ const segmentNameSet = new Set(segmentNames);
50130
+ const findSegmentByOffset = (at, size2) => {
50131
+ let lo = 0;
50132
+ let hi = segmentsByOffset.length - 1;
50133
+ while (lo <= hi) {
50134
+ const mid = lo + hi >> 1;
50135
+ const entry = segmentsByOffset[mid];
50136
+ if (at < entry.offset) hi = mid - 1;
50137
+ else if (at >= entry.offset + entry.length) lo = mid + 1;
50138
+ else return at + size2 <= entry.offset + entry.length ? entry : void 0;
50139
+ }
50140
+ return void 0;
50141
+ };
49276
50142
  const tdata = segmentNames.indexOf(".tdata");
49277
50143
  const tlsTemplate = tdata < 0 ? void 0 : passiveSegments(bytes)[tdata];
49278
50144
  const tlsStart = tlsTemplate && tlsTemplate.byteOffset - bytes.byteOffset;
@@ -49337,7 +50203,7 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49337
50203
  const encoding = width.width;
49338
50204
  if (kind === "address" && target.id === 11 && encoding === "u64" && addend === 0n) {
49339
50205
  const section2 = OBJC_SECTION_BOUNDARY.exec(name3)?.[1];
49340
- if (section2 && !segmentNames.includes(section2)) {
50206
+ if (section2 && !segmentNameSet.has(section2)) {
49341
50207
  bytes.fill(0, at, at + 8);
49342
50208
  continue;
49343
50209
  }
@@ -49349,9 +50215,7 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49349
50215
  if (tlsStart !== void 0 && at >= tlsStart && at < tlsStart + tlsTemplate.length)
49350
50216
  linkage.tls.push(at - tlsStart, size2, value);
49351
50217
  else {
49352
- const segment2 = segments.find(
49353
- (entry) => at >= entry.offset && at + size2 <= entry.offset + entry.length
49354
- );
50218
+ const segment2 = findSegmentByOffset(at, size2);
49355
50219
  if (!segment2)
49356
50220
  throw new Error(`Swift SDK relocation has no load address for ${name3}`);
49357
50221
  linkage.data.push(segment2.address + at - segment2.offset, size2, value);
@@ -49395,15 +50259,29 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49395
50259
  }
49396
50260
  }
49397
50261
  }
49398
- const entries2 = imports2.map((entry) => {
50262
+ const encodedNameBuf = (name3) => {
50263
+ const raw2 = Buffer.from(name3, "utf8");
50264
+ const len = uleb4(raw2.length);
50265
+ const out = Buffer.allocUnsafe(len.length + raw2.length);
50266
+ for (let i = 0; i < len.length; i++) out[i] = len[i];
50267
+ raw2.copy(out, len.length);
50268
+ return out;
50269
+ };
50270
+ const importParts = [];
50271
+ let importEntryCount = imports2.length + 1;
50272
+ for (const entry of imports2) {
49399
50273
  const slot = entry.kind === 0 && entry.module === "env" ? functionSlots.get(entry.name) : void 0;
49400
- return [
49401
- ...encodedName2(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
49402
- ...encodedName2(slot === void 0 ? entry.name : String(slot)),
49403
- ...bytes.subarray(entry.start, entry.end)
49404
- ];
49405
- });
49406
- entries2.push([...encodedName2("env"), ...encodedName2("__stack_pointer"), 3, 126, 1]);
50274
+ importParts.push(
50275
+ encodedNameBuf(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
50276
+ encodedNameBuf(slot === void 0 ? entry.name : String(slot)),
50277
+ bytes.subarray(entry.start, entry.end)
50278
+ );
50279
+ }
50280
+ importParts.push(
50281
+ encodedNameBuf("env"),
50282
+ encodedNameBuf("__stack_pointer"),
50283
+ Buffer.from([3, 126, 1])
50284
+ );
49407
50285
  const tags = sections.find((section2) => section2.id === 13);
49408
50286
  if (tags) {
49409
50287
  const r = wasmReader(bytes, tags.start);
@@ -49418,15 +50296,18 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49418
50296
  throw new Error(
49419
50297
  `Swift app defines an exception tag the sdk does not own: ${name3}`
49420
50298
  );
49421
- entries2.push([
49422
- ...encodedName2("env"),
49423
- ...encodedName2(name3),
49424
- 4,
49425
- ...bytes.subarray(start, r.at)
49426
- ]);
50299
+ importParts.push(
50300
+ encodedNameBuf("env"),
50301
+ encodedNameBuf(name3),
50302
+ Buffer.from([4]),
50303
+ bytes.subarray(start, r.at)
50304
+ );
50305
+ importEntryCount++;
49427
50306
  }
49428
50307
  }
49429
- const globals = [];
50308
+ const globalParts = [
50309
+ Buffer.from(uleb4(globalCount - 1 + syntheticGlobals.length))
50310
+ ];
49430
50311
  for (let index = 0; index < globalCount; index++) {
49431
50312
  const start = gr.at;
49432
50313
  const type = gr.byte();
@@ -49438,12 +50319,12 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49438
50319
  if (gr.byte() !== 11) throw new Error("app global initializer has no end");
49439
50320
  if (index === 0) continue;
49440
50321
  const value = got.get(index);
49441
- if (value === void 0) globals.push(...bytes.subarray(start, gr.at));
49442
- else globals.push(type, 1, type === 126 ? 66 : 65, 0, 11);
50322
+ if (value === void 0) globalParts.push(bytes.subarray(start, gr.at));
50323
+ else globalParts.push(Buffer.from([type, 1, type === 126 ? 66 : 65, 0, 11]));
49443
50324
  }
49444
50325
  for (const type of syntheticGlobals) {
49445
50326
  const zero = type === 125 ? [67, 0, 0, 0, 0] : type === 124 ? [68, 0, 0, 0, 0, 0, 0, 0, 0] : [type === 126 ? 66 : 65, 0];
49446
- globals.push(type, 1, ...zero, 11);
50327
+ globalParts.push(Buffer.from([type, 1, ...zero, 11]));
49447
50328
  }
49448
50329
  const exportSection = sections.find((s) => s.id === 7);
49449
50330
  if (!exportSection) throw new Error("app link has no exports");
@@ -49466,24 +50347,21 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49466
50347
  throw new Error("Swift app exceeds its reserved static memory range");
49467
50348
  }
49468
50349
  }
50350
+ const exportParts = [
50351
+ Buffer.from(uleb4(exportCount + 1 + got.size)),
50352
+ bytes.subarray(originalExportsStart, exportSection.end)
50353
+ ];
50354
+ for (const [index, value] of got) {
50355
+ exportParts.push(
50356
+ encodedNameBuf(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
50357
+ Buffer.from([3, ...uleb4(index)])
50358
+ );
50359
+ }
50360
+ exportParts.push(encodedNameBuf("__indirect_function_table"), Buffer.from([1, 0]));
49469
50361
  const replaced = /* @__PURE__ */ new Map([
49470
- [2, [...uleb4(entries2.length), ...entries2.flat()]],
49471
- [6, [...uleb4(globalCount - 1 + syntheticGlobals.length), ...globals]],
49472
- [
49473
- 7,
49474
- [
49475
- ...uleb4(exportCount + 1 + got.size),
49476
- ...bytes.subarray(originalExportsStart, exportSection.end),
49477
- ...[...got].flatMap(([index, value]) => [
49478
- ...encodedName2(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
49479
- 3,
49480
- ...uleb4(index)
49481
- ]),
49482
- ...encodedName2("__indirect_function_table"),
49483
- 1,
49484
- 0
49485
- ]
49486
- ]
50362
+ [2, Buffer.concat([Buffer.from(uleb4(importEntryCount)), ...importParts])],
50363
+ [6, Buffer.concat(globalParts)],
50364
+ [7, Buffer.concat(exportParts)]
49487
50365
  ]);
49488
50366
  const rebuiltCode = expanded.length ? expandSdkRelocations(
49489
50367
  bytes,
@@ -49495,9 +50373,13 @@ function resolveSdkReferences(source, sdk2, forwarders) {
49495
50373
  if (s === tags || s.name === "linking" || s.name?.startsWith("reloc.") || s.name === ".swift1_autolink_entries")
49496
50374
  continue;
49497
50375
  const payload = replaced.get(s.id);
49498
- parts2.push(
49499
- s.id === 10 && rebuiltCode ? rebuiltCode : payload ? Uint8Array.from([s.id, ...uleb4(payload.length), ...payload]) : bytes.subarray(s.offset, s.end)
49500
- );
50376
+ if (s.id === 10 && rebuiltCode) {
50377
+ parts2.push(rebuiltCode);
50378
+ } else if (payload) {
50379
+ parts2.push(Buffer.from([s.id, ...uleb4(payload.length)]), payload);
50380
+ } else {
50381
+ parts2.push(bytes.subarray(s.offset, s.end));
50382
+ }
49501
50383
  }
49502
50384
  return { bytes: Buffer.concat(parts2), linkage };
49503
50385
  }
@@ -49595,6 +50477,49 @@ function readSwiftSdkUsage(mapFile, linkedFile, sdkObjects) {
49595
50477
  constructors: [...new Set(constructorKeys(map2, (0, import_node_fs71.readFileSync)(linkedFile)))]
49596
50478
  };
49597
50479
  }
50480
+ function swiftSdkProjectionSpans(sdk2, imageFor) {
50481
+ const { manifest, block: block2 } = readSwiftSdkManifest(sdk2);
50482
+ const guestObjects = manifest.guestObjects;
50483
+ if (!guestObjects) return [];
50484
+ const { strings: strings7 } = manifest;
50485
+ const fields = block2("pieces");
50486
+ const ordered = [];
50487
+ for (let i = 0; i < fields.length; i += SWIFT_SDK_PIECE_FIELDS) {
50488
+ const size2 = fields[i + 1];
50489
+ if (!size2) continue;
50490
+ ordered.push({
50491
+ address: fields[i],
50492
+ size: size2,
50493
+ object: strings7[fields[i + 3]]
50494
+ });
50495
+ }
50496
+ ordered.sort((a, b) => a.address - b.address);
50497
+ const imageOf = (object8) => {
50498
+ const product = guestObjects[object8]?.product;
50499
+ return product === void 0 ? void 0 : imageFor(object8, product);
50500
+ };
50501
+ const spans = [];
50502
+ for (let index = 0; index < ordered.length; index++) {
50503
+ const { object: object8, address, size: size2 } = ordered[index];
50504
+ const image = imageOf(object8);
50505
+ if (image === void 0) continue;
50506
+ let next = index + 1;
50507
+ while (next < ordered.length && ordered[next].address < address + size2) next++;
50508
+ const end = ordered[next]?.address ?? address + size2;
50509
+ spans.push({ image, space: "linear-memory", address, length: end - address });
50510
+ }
50511
+ const functionKeys = block2("functions");
50512
+ const slots = block2("functionSlots");
50513
+ for (let index = 0; index < functionKeys.length; index++) {
50514
+ const slot = slots[index];
50515
+ if (!slot) continue;
50516
+ const key2 = strings7[functionKeys[index]];
50517
+ const image = imageOf(key2.slice(0, key2.indexOf(":")));
50518
+ if (image !== void 0)
50519
+ spans.push({ image, space: "function-table", address: slot, length: 1 });
50520
+ }
50521
+ return spans;
50522
+ }
49598
50523
  function selectSwiftSdkData(sdk2, usage, linkage, projection) {
49599
50524
  const { manifest, block: block2, segments } = readSwiftSdkManifest(sdk2);
49600
50525
  const { strings: strings7 } = manifest;
@@ -49617,15 +50542,24 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
49617
50542
  });
49618
50543
  }
49619
50544
  const memory = new Map(segments.map((segment2) => [segment2.name, segment2]));
49620
- const read = (address2, size2) => {
50545
+ let lastSegment = segments[0];
50546
+ const segmentAt = (address2, size2) => {
50547
+ if (lastSegment && address2 >= lastSegment.address && address2 + size2 <= lastSegment.address + lastSegment.data.length)
50548
+ return lastSegment;
49621
50549
  for (const segment2 of segments)
49622
- if (address2 >= segment2.address && address2 + size2 <= segment2.address + segment2.data.length)
49623
- return segment2.data.subarray(
49624
- address2 - segment2.address,
49625
- address2 - segment2.address + size2
49626
- );
50550
+ if (address2 >= segment2.address && address2 + size2 <= segment2.address + segment2.data.length) {
50551
+ lastSegment = segment2;
50552
+ return segment2;
50553
+ }
49627
50554
  return void 0;
49628
50555
  };
50556
+ const read = (address2, size2) => {
50557
+ const segment2 = segmentAt(address2, size2);
50558
+ return segment2?.data.subarray(
50559
+ address2 - segment2.address,
50560
+ address2 - segment2.address + size2
50561
+ );
50562
+ };
49629
50563
  const appSectionsByObject = /* @__PURE__ */ new Map();
49630
50564
  const appSections = /* @__PURE__ */ new Set();
49631
50565
  const appSymbols = /* @__PURE__ */ new Set();
@@ -49731,9 +50665,7 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
49731
50665
  const classAddress = Number(
49732
50666
  new DataView(field.buffer, field.byteOffset, 8).getBigUint64(0, true)
49733
50667
  );
49734
- const segment2 = segments.find(
49735
- ({ address: address3, data }) => classAddress >= address3 && classAddress < address3 + data.length
49736
- );
50668
+ const segment2 = segmentAt(classAddress, 1);
49737
50669
  if (!segment2) continue;
49738
50670
  const start = classAddress - segment2.address;
49739
50671
  const end = segment2.data.indexOf(0, start);
@@ -49941,7 +50873,7 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
49941
50873
  if (current2)
49942
50874
  runs.push({
49943
50875
  address: current2.address,
49944
- bytes: Uint8Array.from(Buffer.concat(current2.parts))
50876
+ bytes: Buffer.concat(current2.parts)
49945
50877
  });
49946
50878
  };
49947
50879
  for (const piece of loaded4) {
@@ -50359,13 +51291,19 @@ async function compileGuestLink(options2) {
50359
51291
  const selectedSource = source.artifacts.filter(
50360
51292
  (artifact) => selected.has(import_node_path72.default.resolve(rewritten.get(artifact.path) ?? artifact.path))
50361
51293
  );
51294
+ const admittedCores = Number(process.env.TM_EXEC_CPU_CORES);
51295
+ const linuxMemory = process.env.TM_EXEC_ADMITTED === "1" && process.env.LINUX_BUILD_SCOPE ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX) : NaN;
51296
+ const clangReplayJobs = Number.isInteger(admittedCores) && admittedCores > 0 ? Math.min(
51297
+ admittedCores,
51298
+ Number.isSafeInteger(linuxMemory) && linuxMemory > 0 ? Math.max(options2.jobs, Math.floor(linuxMemory / (512 * 1024 ** 2))) : Math.max(options2.jobs, admittedCores)
51299
+ ) : options2.jobs;
50362
51300
  const clangOptions2 = sourceGuestClangLinkOptions({
50363
51301
  buildDirectory: options2.buildDirectory,
50364
51302
  directory: directory2,
50365
51303
  toolchainBin: options2.toolchainBin,
50366
51304
  swiftCompiler: options2.swiftCompiler,
50367
51305
  objects: selectedSource.map((artifact) => artifact.path),
50368
- jobs: options2.jobs
51306
+ jobs: clangReplayJobs
50369
51307
  });
50370
51308
  const links = sourceGuestRuntimeLinks({
50371
51309
  toolchainBin: options2.toolchainBin,
@@ -50467,9 +51405,9 @@ async function compileGuestLink(options2) {
50467
51405
  }
50468
51406
  };
50469
51407
  },
50470
- resolvePlan: (selected, plan) => {
51408
+ resolvePlan: (selected, plan, readSelected) => {
50471
51409
  if (!prepared) throw new Error("guest runtime selection is unavailable");
50472
- const scope2 = selectedGuestSymbolInputs(plan, selected);
51410
+ const scope2 = selectedGuestSymbolInputs(plan, selected, readSelected);
50473
51411
  const owners = new Map(scope2.owners);
50474
51412
  owners.set(import_node_path72.default.join(directory2, "projection-discovery.o"), 0);
50475
51413
  const providersByImage = Map.groupBy(scope2.owners, ([, image]) => image);
@@ -50547,7 +51485,8 @@ async function compileGuestLink(options2) {
50547
51485
  createSwiftSdkBinding: createSwiftSdkBinding2,
50548
51486
  finishSwiftAppModule: finishSwiftAppModule2,
50549
51487
  linkSwiftAppModule: linkSwiftAppModule2,
50550
- readSwiftSdkUsage: readSwiftSdkUsage2
51488
+ readSwiftSdkUsage: readSwiftSdkUsage2,
51489
+ swiftSdkProjectionSpans: swiftSdkProjectionSpans2
50551
51490
  } = await Promise.resolve().then(() => (init_swift_sdk_app_module(), swift_sdk_app_module_exports));
50552
51491
  const project2 = options2.project;
50553
51492
  const work = project2 ? (0, import_node_fs72.mkdtempSync)(import_node_path72.default.join(directory2, "app-module-")) : import_node_path72.default.join(directory2, "app-module");
@@ -50569,7 +51508,28 @@ async function compileGuestLink(options2) {
50569
51508
  }
50570
51509
  const usage = readSwiftSdkUsage2(result.mapPath, options2.output, sdkObjectKeys);
50571
51510
  const linkedModule = import_node_path72.default.join(work, "app.wasm");
51511
+ const sdkSpans = swiftSdkProjectionSpans2(
51512
+ sdk2,
51513
+ (object8, product) => sdkObjectImages.get(object8) ?? sdkProductImages.get(product)
51514
+ );
50572
51515
  let storage = reserved2;
51516
+ if (sdkSpans.length > 0) {
51517
+ const sdkCounts = guestProjectionRegionCounts(storage.images.length, sdkSpans);
51518
+ storage = reserveGuestProjectionStorage(
51519
+ storage.images,
51520
+ storage.capacities.map((capacity, index) => ({
51521
+ ...capacity,
51522
+ regions: capacity.regions + sdkCounts[index] + 16
51523
+ }))
51524
+ );
51525
+ const projectionSource = import_node_path72.default.join(work, "projection.c");
51526
+ (0, import_node_fs72.writeFileSync)(projectionSource, storage.source);
51527
+ (0, import_node_child_process36.execFileSync)(
51528
+ import_node_path72.default.join(options2.toolchainBin, "clang"),
51529
+ [...clangOptions, "-c", projectionSource, "-o", projectionObject],
51530
+ { stdio: "pipe" }
51531
+ );
51532
+ }
50573
51533
  for (; ; ) {
50574
51534
  const link = await linkSwiftAppModule2({
50575
51535
  objects: [...owners.keys()],
@@ -50607,11 +51567,7 @@ async function compileGuestLink(options2) {
50607
51567
  bindingRows.set((address - values.address) / 8, value);
50608
51568
  } else data.push(address, size2, value);
50609
51569
  }
50610
- const sdkSpans = [];
50611
- const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk2, usage, {
50612
- imageFor: (object8, product) => sdkObjectImages.get(object8) ?? sdkProductImages.get(product),
50613
- spans: sdkSpans
50614
- });
51570
+ const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk2, usage);
50615
51571
  const linked = (0, import_node_fs72.readFileSync)(
50616
51572
  project2 ? projectOutputFile(work, linkedModule, project2) : linkedModule
50617
51573
  );
@@ -58145,7 +59101,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
58145
59101
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
58146
59102
  MULTI_MANIFEST_VERSION = 76;
58147
59103
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
58148
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
59104
+ compilerSourceDigest = true ? "d4cf22b53d08266bf9bd0238bffe899805f62daeb3d628664ee351830e496cda" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
58149
59105
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
58150
59106
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
58151
59107
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));
@@ -113575,7 +114531,7 @@ function eventBindings(name3, source) {
113575
114531
  });
113576
114532
  continue;
113577
114533
  }
113578
- const call = /emitter->(\w+)\( ?\{([^}]*)\} ?\)/.exec(body);
114534
+ const call = /emitter->(\w+)\(\s*\{([^}]*)\}\s*\)/.exec(body);
113579
114535
  if (!call) throw new Error(`${name3}: unmapped event block ${property}`);
113580
114536
  const fields = [...call[2].matchAll(/\.(\w+) = ([^,]+)/g)].map(
113581
114537
  ([, field, expression]) => {
@@ -113617,18 +114573,20 @@ function configuration(name3, source) {
113617
114573
  }
113618
114574
  function arrayBindings(name3, body) {
113619
114575
  const bindings = /* @__PURE__ */ new Map();
113620
- for (const [, prop, element] of body.matchAll(
113621
- /for \(const auto &item : next\.(\w+)\) \[\w+ addObject:(.*?)\];/g
114576
+ for (const [, item, prop, variable, element] of body.matchAll(
114577
+ /for \(const auto &(\w+) : next\.(\w+)\) \[(\w+) addObject:(.*?)\];/g
113622
114578
  )) {
113623
- if (element === "RCTNSStringFromString(item)") {
113624
- bindings.set(prop, []);
114579
+ if (element === `RCTNSStringFromString(${item})`) {
114580
+ bindings.set(variable, { prop, fields: [] });
113625
114581
  continue;
113626
114582
  }
113627
114583
  const fields = [
113628
- ...element.matchAll(/@"(\w+)" ?: (RCTNSStringFromString|@)\(item\.\w+\)/g)
114584
+ ...element.matchAll(
114585
+ new RegExp(`@"(\\w+)" ?: (RCTNSStringFromString|@)\\(${item}\\.\\w+\\)`, "g")
114586
+ )
113629
114587
  ].map(([, name4, kind]) => ({ name: name4, defaultValue: kind === "@" ? 0 : "" }));
113630
114588
  if (!fields.length) throw new Error(`${name3}: unmapped array ${prop}`);
113631
- bindings.set(prop, fields);
114589
+ bindings.set(variable, { prop, fields });
113632
114590
  }
113633
114591
  return bindings;
113634
114592
  }
@@ -113680,38 +114638,41 @@ function swiftGuestControls(one, names, linkedGroups) {
113680
114638
  }
113681
114639
  const withLabel = /^(\w+)With([A-Z])(\w*)$/.exec(first);
113682
114640
  const args = selector.map(({ label, expression }, index) => {
113683
- const fields = arrays.get(expression);
114641
+ const array9 = arrays.get(expression);
113684
114642
  let value;
113685
114643
  if (expression === "OneNativeStyleDictionary(next.swiftStyle)") value = "style";
113686
114644
  else if (expression === "boundedHeight")
113687
114645
  value = 'spec["boundedHeight"] as? Bool ?? false';
113688
114646
  else if (/^@"[^"]*"$/.test(expression)) value = expression.slice(1);
113689
- else if (fields?.length) {
113690
- const entries3 = fields.map(
113691
- ({ name: name4, defaultValue: defaultValue2 }) => `"${name4}": row["${name4}"].flatMap { $0 is NSNull ? nil : $0 } ?? ${JSON.stringify(defaultValue2)}`
114647
+ else if (array9?.fields.length) {
114648
+ const entries3 = array9.fields.map(
114649
+ ({ name: name4, defaultValue: defaultValue2 }) => `"${name4}": row["${name4}"] as? ${typeof defaultValue2 === "number" ? "Double" : "String"} ?? ${JSON.stringify(defaultValue2)}`
113692
114650
  ).join(", ");
113693
- value = `(spec["${expression}"] as? [Spec] ?? []).map { row in [${entries3}] }`;
113694
- } else if (fields) value = `spec["${expression}"] as? [String] ?? []`;
114651
+ value = `(spec["${array9.prop}"] as? [Spec] ?? []).map { row in [${entries3}] }`;
114652
+ } else if (array9) value = `spec["${array9.prop}"] as? [String] ?? []`;
113695
114653
  else {
113696
- const prop = /\bnext\.(\w+)/.exec(expression)?.[1];
114654
+ const prop = /\bnext\.(\w+)/.exec(expression)?.[1] ?? "";
113697
114655
  const types2 = {
113698
- string: 'String ?? ""',
113699
- boolean: "Bool ?? false",
113700
- Double: "Double ?? 0",
113701
- Int32: "Int ?? 0"
114656
+ string: ["String", ""],
114657
+ boolean: ["Bool", false],
114658
+ Double: ["Double", 0],
114659
+ Int32: ["Int", 0]
113702
114660
  };
113703
- const type = prop && props[prop]?.type;
114661
+ const field = props[prop];
114662
+ const type = field?.type;
113704
114663
  if (type === "ColorValue") value = `spec["${prop}"].flatMap(oneControlColor)`;
113705
- else if (type && types2[type]) value = `spec["${prop}"] as? ${types2[type]}`;
113706
- else throw new Error(`${name3}: unmapped guest argument ${expression}`);
114664
+ else if (type && types2[type]) {
114665
+ const [swiftType, implicitDefault] = types2[type];
114666
+ value = `spec["${prop}"] as? ${swiftType} ?? ${JSON.stringify(field.default ?? implicitDefault)}`;
114667
+ } else throw new Error(`${name3}: unmapped guest argument ${expression}`);
113707
114668
  }
113708
114669
  const argLabel = index ? label : withLabel ? withLabel[2].toLowerCase() + withLabel[3] : "";
113709
114670
  return argLabel ? argLabel + ": " + value : value;
113710
114671
  });
113711
114672
  const call = `view.${withLabel?.[1] ?? first}(${args.join(", ")})`;
113712
- const array8 = selector[0].expression;
114673
+ const array8 = arrays.get(selector[0].expression)?.prop;
113713
114674
  lines.push(
113714
- arrays.has(array8) ? ` if previous == nil || (spec["${array8}"] as? NSArray) != (previous?["${array8}"] as? NSArray) { ${call} }` : ` ${call}`
114675
+ array8 ? ` if previous == nil || (spec["${array8}"] as? NSArray) != (previous?["${array8}"] as? NSArray) { ${call} }` : ` ${call}`
113715
114676
  );
113716
114677
  }
113717
114678
  for (const { property, parameters, fields, event, sync } of eventBindings(
@@ -118850,7 +119811,7 @@ var init_nitro_superset = __esm({
118850
119811
  init_nitroContract();
118851
119812
  init_swift_standin_digest();
118852
119813
  NITRO_SUPERSET_ENTRY_NAME = "superset";
118853
- NITRO_COMPILER_DIGEST = true ? "59081cf672cb2bb9c125425cd97f2df60507acfc6de96f1525f18ddca39ff000" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
119814
+ NITRO_COMPILER_DIGEST = true ? "0ce63814b4a72a014a0388c3792cede09d8d1cae4f69a18e904584487588222d" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
118854
119815
  nitroSupersetLock = parseLock(nitro_superset_lock_default);
118855
119816
  nitroSupersetKey = (inputs2) => nativeEntryKey({ ...inputs2, compiler: NITRO_COMPILER_DIGEST });
118856
119817
  published3 = /* @__PURE__ */ new Map();