peachsim 0.1.1674 → 0.1.1684

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 (190) hide show
  1. package/cli/commands/control.ts +13 -1
  2. package/cli/commands/coverage-swift.ts +83 -27
  3. package/cli/commands/coverage.ts +219 -20
  4. package/cli/commands/detect.ts +10 -6
  5. package/cli/commands/inspect/core.ts +2 -0
  6. package/cli/commands/inspect/wait-ready.ts +7 -0
  7. package/cli/outbound-endpoints.ts +12 -0
  8. package/detox/index.ts +11 -1
  9. package/detox/jest-environment.cjs +14 -0
  10. package/dist-lib/agent-daemon-client.cjs +1 -1
  11. package/dist-lib/agent-events.cjs +1 -1
  12. package/dist-lib/attached-projects.cjs +1 -1
  13. package/dist-lib/auth/shared-session.cjs +1 -1
  14. package/dist-lib/backend-origin.cjs +1 -1
  15. package/dist-lib/beta.cjs +1 -1
  16. package/dist-lib/beta.mjs +1 -1
  17. package/dist-lib/bridge-constants.cjs +1 -1
  18. package/dist-lib/bridge-contract-input.cjs +1 -1
  19. package/dist-lib/bridge-contract-input.mjs +1 -1
  20. package/dist-lib/bridge-contract.cjs +1 -1
  21. package/dist-lib/bridge-contract.mjs +1 -1
  22. package/dist-lib/bundle-channel.cjs +3274 -1663
  23. package/dist-lib/capture-contract.cjs +1 -1
  24. package/dist-lib/capture-contract.mjs +1 -1
  25. package/dist-lib/cloud-contract.cjs +1 -1
  26. package/dist-lib/cloud-contract.mjs +1 -1
  27. package/dist-lib/cloud-test-args.cjs +1 -1
  28. package/dist-lib/cloud-test-args.mjs +1 -1
  29. package/dist-lib/cloud.cjs +1 -1
  30. package/dist-lib/cloud.mjs +1 -1
  31. package/dist-lib/config.cjs +1 -1
  32. package/dist-lib/config.mjs +1 -1
  33. package/dist-lib/detox/index.cjs +6 -4
  34. package/dist-lib/detox/jest-environment.cjs +14 -0
  35. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  36. package/dist-lib/expo-swift-bundle.cjs +2407 -1126
  37. package/dist-lib/expo-swift-metadata.cjs +1 -1
  38. package/dist-lib/expo-swift-metadata.mjs +1 -1
  39. package/dist-lib/home-paths.cjs +1 -1
  40. package/dist-lib/host/bridge-host.cjs +2879 -1598
  41. package/dist-lib/host/fetch-proxy-handler.cjs +18 -5
  42. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  43. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  44. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  45. package/dist-lib/host/websocket-proxy.cjs +1 -1
  46. package/dist-lib/index.cjs +1904 -741
  47. package/dist-lib/jump-to-source-babel.cjs +1 -1
  48. package/dist-lib/jump-to-source-native.cjs +1 -1
  49. package/dist-lib/kotlin-host.cjs +1 -1
  50. package/dist-lib/menu.cjs +1 -1
  51. package/dist-lib/menu.mjs +1 -1
  52. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  53. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  54. package/dist-lib/metro-production-bundle.cjs +1 -1
  55. package/dist-lib/metro-production-bundle.mjs +1 -1
  56. package/dist-lib/metro.cjs +6215 -4283
  57. package/dist-lib/native-app-identity-project.cjs +31 -6
  58. package/dist-lib/native-app-identity-project.mjs +31 -6
  59. package/dist-lib/native-app-identity.cjs +1 -1
  60. package/dist-lib/native-app-identity.mjs +1 -1
  61. package/dist-lib/native-firebase-metadata.cjs +1 -1
  62. package/dist-lib/native-firebase-metadata.mjs +1 -1
  63. package/dist-lib/plist.cjs +1 -1
  64. package/dist-lib/plist.mjs +1 -1
  65. package/dist-lib/profiles.cjs +1 -1
  66. package/dist-lib/public-brand.cjs +1 -1
  67. package/dist-lib/public-origins-lib-esm.json +24 -23
  68. package/dist-lib/public-origins-lib-static.json +1 -1
  69. package/dist-lib/public-origins-lib.json +134 -78
  70. package/dist-lib/react-native-host-modules.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.mjs +1 -1
  72. package/dist-lib/reap-browser.cjs +2 -2
  73. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  74. package/dist-lib/sdk.cjs +2 -1
  75. package/dist-lib/sdk.mjs +2 -1
  76. package/dist-lib/skills.cjs +3570 -2160
  77. package/dist-lib/swift-compile.cjs +473 -351
  78. package/dist-lib/swift-compile.mjs +471 -349
  79. package/dist-lib/swift-package.cjs +36 -6
  80. package/dist-lib/swift-package.mjs +35 -6
  81. package/dist-lib/swift-submit.cjs +1 -1
  82. package/dist-lib/swift-submit.mjs +1 -1
  83. package/dist-lib/swift-toolchain.cjs +26 -11
  84. package/dist-lib/swift.cjs +1 -1
  85. package/dist-lib/vite-swift.cjs +2418 -1132
  86. package/dist-lib/vite.cjs +1907 -766
  87. package/dist-lib/worklet-executable.cjs +1 -1
  88. package/dist-lib/worklet-executable.mjs +1 -1
  89. package/dist-types/packages/peach-engine/src/engine/canvaskit-api.d.ts +1 -1
  90. package/dist-types/packages/peach-engine/src/engine/clipboardContract.d.ts +9 -1
  91. package/dist-types/packages/peach-engine/src/preview/upload-protocol.d.ts +11 -3
  92. package/dist-types/packages/peach-engine/src/webview-automation-host.d.ts +6 -0
  93. package/dist-types/packages/peach-globals/src/clipboardBridgeContract.d.ts +2 -0
  94. package/package.json +1 -1
  95. package/runtime-companion.json +1 -1
  96. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h +51 -2
  97. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h +21 -0
  98. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFComposeAssistantViewController.h +29 -0
  99. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMailComposeControllerDeferredAction.h +14 -0
  100. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMailComposeViewController.h +162 -0
  101. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMailDraft.h +24 -0
  102. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMessageComposeViewController+UPI.h +31 -0
  103. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MFMessageComposeViewController.h +169 -0
  104. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Headers/MessageUI.h +13 -0
  105. package/sdk/ios/System/Library/Frameworks/MessageUI.framework/Modules/module.modulemap +11 -0
  106. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h +10 -0
  107. package/sdk/ios/usr/include/arm/param.h +151 -0
  108. package/sdk/ios/usr/include/dispatch/dispatch.h +3 -0
  109. package/sdk/ios/usr/include/dlfcn.h +1 -2
  110. package/sdk/ios/usr/include/machine/param.h +42 -0
  111. package/sdk/ios/usr/include/net/if.h +1 -2
  112. package/sdk/ios/usr/include/peach/pthread.h +4 -4
  113. package/sdk/ios/usr/include/pthread/qos.h +304 -0
  114. package/sdk/ios/usr/include/sys/_types/_fd_clr.h +31 -0
  115. package/sdk/ios/usr/include/sys/_types/_fd_copy.h +31 -0
  116. package/sdk/ios/usr/include/sys/_types/_fd_def.h +121 -0
  117. package/sdk/ios/usr/include/sys/_types/_fd_isset.h +31 -0
  118. package/sdk/ios/usr/include/sys/_types/_fd_set.h +31 -0
  119. package/sdk/ios/usr/include/sys/_types/_fd_setsize.h +31 -0
  120. package/sdk/ios/usr/include/sys/_types/_fd_zero.h +31 -0
  121. package/sdk/ios/usr/include/sys/cdefs.h +3 -0
  122. package/sdk/ios/usr/include/sys/param.h +235 -0
  123. package/sdk/ios/usr/include/sys/proc.h +1 -0
  124. package/sdk/ios/usr/include/sys/qos.h +151 -12
  125. package/sdk/ios/wasm/include/__typedef_sigset_t.h +7 -0
  126. package/sdk/ios/wasm/include/fcntl.h +11 -0
  127. package/sdk/ios/wasm/include/mach/machine/boolean.h +2 -0
  128. package/sdk/ios/wasm/include/mach/machine/exception.h +5 -0
  129. package/sdk/ios/wasm/include/mach/machine/kern_return.h +2 -0
  130. package/sdk/ios/wasm/include/mach/machine/processor_info.h +2 -0
  131. package/sdk/ios/wasm/include/mach/machine/rpc.h +2 -0
  132. package/sdk/ios/wasm/include/mach/machine/thread_state.h +3 -0
  133. package/sdk/ios/wasm/include/mach/machine/thread_status.h +3 -0
  134. package/sdk/ios/wasm/include/mach/machine/vm_param.h +3 -0
  135. package/sdk/ios/wasm/include/mach/machine/vm_types.h +18 -0
  136. package/sdk/ios/wasm/include/machine/_types.h +153 -0
  137. package/sdk/ios/wasm/include/machine/endian.h +2 -0
  138. package/sdk/ios/wasm/include/machine/limits.h +2 -0
  139. package/sdk/ios/wasm/include/machine/types.h +30 -0
  140. package/sdk/ios/wasm/include/poll.h +8 -0
  141. package/sdk/ios/wasm/include/pthread.h +50 -0
  142. package/sdk/ios/wasm/include/signal.h +72 -0
  143. package/sdk/ios/wasm/include/stdlib.h +3 -0
  144. package/sdk/ios/wasm/include/string.h +10 -0
  145. package/sdk/ios/wasm/include/sys/_pthread/_pthread_attr_t.h +7 -0
  146. package/sdk/ios/wasm/include/sys/_pthread/_pthread_t.h +7 -0
  147. package/sdk/ios/wasm/include/sys/mman.h +122 -0
  148. package/sdk/ios/wasm/include/sys/select.h +37 -0
  149. package/sdk/ios/wasm/include/sys/signal.h +259 -0
  150. package/sdk/ios/wasm/include/sys/socket.h +8 -0
  151. package/sdk/ios/wasm/include/sys/types.h +14 -0
  152. package/sdk/ios/wasm/include/sys/ucontext.h +1 -0
  153. package/sdk/ios/wasm/include/sys/uio.h +11 -0
  154. package/sdk/ios/wasm/include/sys/wait.h +89 -0
  155. package/sdk/ios/wasm/include/time.h +8 -0
  156. package/sdk/ios/wasm/include/unistd.h +17 -0
  157. package/src/bridge-contract.ts +2 -0
  158. package/src/chromium-admission.ts +10 -5
  159. package/src/device-catalog.ts +4 -4
  160. package/src/host/fetch-proxy-handler.ts +20 -0
  161. package/src/metro-plugin.ts +5 -2
  162. package/src/nitro-adapter.lock.json +6 -6
  163. package/src/nitro-compile.ts +63 -2
  164. package/src/numbered-lock.ts +72 -0
  165. package/src/react-native-coverage/capability-reference-resolution.ts +62 -5
  166. package/src/react-native-coverage/capability-source-references.ts +50 -13
  167. package/src/react-native-coverage/native-source-credit.ts +126 -0
  168. package/src/react-native-coverage/native-source-ranges-file.ts +38 -0
  169. package/src/react-native-coverage/native-surface.ts +49 -0
  170. package/src/react-native-coverage/verified-reach.ts +22 -2
  171. package/src/runtime-assets.ts +17 -0
  172. package/src/swift-compile.ts +84 -48
  173. package/src/swift-coverage/indexing.ts +17 -1
  174. package/src/swift-coverage/sdk.ts +71 -0
  175. package/src/swift-coverage/source.ts +74 -2
  176. package/src/swift-coverage/types.ts +6 -0
  177. package/src/swift-distribution.lock.json +12 -12
  178. package/src/swift-host.ts +133 -14
  179. package/src/swift-objc-compile.ts +6 -21
  180. package/src/swift-objc-metadata.ts +2 -8
  181. package/src/swift-objc-platform.ts +53 -0
  182. package/src/swift-objc-standin.ts +45 -1
  183. package/src/swift-package-manifest.ts +48 -3
  184. package/src/swift-package.ts +59 -9
  185. package/src/swift-packages.ts +157 -44
  186. package/src/swift-source-pods.ts +288 -0
  187. package/src/swift-toolchain.ts +32 -10
  188. package/src/vite-plugin-one.ts +5 -4
  189. package/src/worker-system-chunks.ts +7 -1
  190. package/src/xcode-project.ts +40 -11
package/dist-lib/vite.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.1674 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.1684 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  let __sootsim_import_meta_url = '', __sootsim_import_meta_dirname = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; __sootsim_import_meta_dirname = __dirname; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
@@ -42,7 +42,7 @@ var init_define_SWIFT_COVERAGE_SOURCE_DIGESTS = __esm({
42
42
  var runtime_companion_default;
43
43
  var init_runtime_companion = __esm({
44
44
  "runtime-companion.json"() {
45
- runtime_companion_default = { abi: 1, sha256: "24766e3afc21d3c7b319b6d6db0422d93f64ecd0af7147a8ef16d16b5cb4e9a8", file: "node/cli-24766e3afc21d3c7b319b6d6db0422d93f64ecd0af7147a8ef16d16b5cb4e9a8.cjs" };
45
+ runtime_companion_default = { abi: 1, sha256: "0aa1bb93377f2ed084f869ab161285ff9e1c638510065738c97f0cbe806bb630", file: "node/cli-0aa1bb93377f2ed084f869ab161285ff9e1c638510065738c97f0cbe806bb630.cjs" };
46
46
  }
47
47
  });
48
48
 
@@ -245,7 +245,18 @@ function resolveRuntimeFilePath(runtimeRoot, pathname) {
245
245
  if (!import_fs.default.existsSync(fullPath) || !import_fs.default.statSync(fullPath).isFile()) return null;
246
246
  return fullPath;
247
247
  }
248
+ function setRuntimeIsolationHeaders(res) {
249
+ res.setHeader("cross-origin-opener-policy", "same-origin");
250
+ res.setHeader("cross-origin-embedder-policy", "require-corp");
251
+ res.setHeader("cross-origin-resource-policy", "cross-origin");
252
+ }
253
+ function sendShellHtml(res, html) {
254
+ setRuntimeIsolationHeaders(res);
255
+ res.setHeader("content-type", "text/html");
256
+ res.end(html);
257
+ }
248
258
  function serveRuntimeFile(req, res, fullPath) {
259
+ setRuntimeIsolationHeaders(res);
249
260
  const ext = import_path.default.extname(fullPath);
250
261
  const stat = import_fs.default.statSync(fullPath);
251
262
  const lastModified = stat.mtime.toUTCString();
@@ -415,13 +426,13 @@ __export(vite_plugin_one_exports, {
415
426
  });
416
427
  module.exports = __toCommonJS(vite_plugin_one_exports);
417
428
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
418
- var import_fs3 = __toESM(require("fs"), 1);
429
+ var import_fs4 = __toESM(require("fs"), 1);
419
430
  var import_node_crypto4 = require("node:crypto");
420
431
  var import_node_http = __toESM(require("node:http"), 1);
421
432
  var import_node_https = __toESM(require("node:https"), 1);
422
433
  var import_node_url = require("node:url");
423
- var import_path3 = __toESM(require("path"), 1);
424
- var import_promises3 = require("stream/promises");
434
+ var import_path4 = __toESM(require("path"), 1);
435
+ var import_promises5 = require("stream/promises");
425
436
  var import_ws = require("ws");
426
437
 
427
438
  // src/bridge-constants.ts
@@ -517,530 +528,120 @@ function launchRnxDesktop(bundleUrl, appName) {
517
528
  // src/vite-plugin-one.ts
518
529
  init_home_paths();
519
530
 
520
- // src/host/replacement-module-handler.ts
521
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
522
- var import_node_fs4 = require("node:fs");
523
- var import_promises = __toESM(require("node:fs/promises"), 1);
524
- var import_node_path4 = __toESM(require("node:path"), 1);
525
-
526
- // ../contrast-bundler/src/replacementModule.ts
531
+ // src/host/fetch-proxy-handler.ts
527
532
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
528
- var import_dist = require("sucrase/dist/index.js");
529
- var import_parser = require("sucrase/dist/parser/index.js");
530
- var import_types = require("sucrase/dist/parser/tokenizer/types.js");
533
+ var import_http = __toESM(require("http"), 1);
534
+ var import_https = __toESM(require("https"), 1);
535
+ var import_node_http2 = require("node:http2");
536
+ var import_promises3 = require("stream/promises");
531
537
 
532
- // ../contrast-bundler/src/posixPath.ts
538
+ // src/backend-origin.ts
533
539
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
534
- var sep = "/";
535
- var delimiter = ":";
536
- function isAbsolute(p) {
537
- return p.charCodeAt(0) === 47;
538
- }
539
- function normalizeSegments(parts, allowAboveRoot) {
540
- const out = [];
541
- for (const part of parts) {
542
- if (part === "" || part === ".") continue;
543
- if (part === "..") {
544
- if (out.length > 0 && out[out.length - 1] !== "..") out.pop();
545
- else if (allowAboveRoot) out.push("..");
546
- continue;
547
- }
548
- out.push(part);
549
- }
550
- return out;
551
- }
552
- function normalize(p) {
553
- if (p.length === 0) return ".";
554
- const absolute = isAbsolute(p);
555
- const trailingSlash = p.charCodeAt(p.length - 1) === 47;
556
- const segments = normalizeSegments(p.split("/"), !absolute);
557
- let joined = segments.join("/");
558
- if (joined.length === 0) {
559
- if (absolute) return "/";
560
- return trailingSlash ? "./" : ".";
561
- }
562
- if (trailingSlash) joined += "/";
563
- return absolute ? "/" + joined : joined;
540
+ function normalizeHostname(hostname) {
541
+ return hostname.replace(/^\[|\]$/g, "").toLowerCase();
564
542
  }
565
- function join2(...parts) {
566
- const present = parts.filter((part) => part.length > 0);
567
- if (present.length === 0) return ".";
568
- return normalize(present.join("/"));
543
+ function isLoopbackHost(hostname) {
544
+ const normalized = normalizeHostname(hostname);
545
+ return normalized === "localhost" || normalized.endsWith(".localhost") || normalized === "0.0.0.0" || normalized === "::1" || /^127(?:\.\d{1,3}){3}$/.test(normalized);
569
546
  }
570
- function resolve(...parts) {
571
- let resolved = "";
572
- let absolute = false;
573
- for (let i = parts.length - 1; i >= 0 && !absolute; i--) {
574
- const part = parts[i];
575
- if (part.length === 0) continue;
576
- resolved = resolved.length > 0 ? `${part}/${resolved}` : part;
577
- absolute = isAbsolute(part);
578
- }
579
- if (!absolute)
580
- throw new Error(
581
- `posixPath.resolve needs an absolute segment, got: ${parts.join(", ")}`
547
+ function isTrustedBridgeRequest(headers) {
548
+ const origin = headers.origin;
549
+ if (origin === void 0) return true;
550
+ try {
551
+ const { hostname, host } = new URL(String(origin));
552
+ return isLoopbackHost(hostname) || [headers.host, headers[":authority"], headers["x-forwarded-host"]].some(
553
+ (value) => typeof value === "string" && value.toLowerCase() === host
582
554
  );
583
- const normalized = normalizeSegments(resolved.split("/"), false).join("/");
584
- return normalized.length > 0 ? "/" + normalized : "/";
585
- }
586
- function dirname(p) {
587
- const idx = p.lastIndexOf("/");
588
- if (idx < 0) return ".";
589
- if (idx === 0) return "/";
590
- return p.slice(0, idx);
591
- }
592
- function basename(p, ext) {
593
- const idx = p.lastIndexOf("/");
594
- const base = idx < 0 ? p : p.slice(idx + 1);
595
- if (ext != null && ext.length < base.length && base.endsWith(ext)) {
596
- return base.slice(0, base.length - ext.length);
555
+ } catch {
556
+ return false;
597
557
  }
598
- return base;
599
- }
600
- function extname(p) {
601
- const base = basename(p);
602
- const idx = base.lastIndexOf(".");
603
- if (idx <= 0) return "";
604
- return base.slice(idx);
605
558
  }
606
- function relative(from, to) {
607
- if (from === to) return "";
608
- const fromParts = normalizeSegments(from.split("/"), false);
609
- const toParts = normalizeSegments(to.split("/"), false);
610
- let shared = 0;
611
- while (shared < fromParts.length && shared < toParts.length && fromParts[shared] === toParts[shared]) {
612
- shared++;
559
+ function loopbackOriginOf(value) {
560
+ try {
561
+ const url = new URL(value);
562
+ return isLoopbackHost(url.hostname) ? url.origin : null;
563
+ } catch {
564
+ return null;
613
565
  }
614
- const up = new Array(fromParts.length - shared).fill("..");
615
- return [...up, ...toParts.slice(shared)].join("/");
616
566
  }
617
- var posix = {
618
- sep,
619
- delimiter,
620
- isAbsolute,
621
- normalize,
622
- join: join2,
623
- resolve,
624
- dirname,
625
- basename,
626
- extname,
627
- relative
628
- };
629
- var posixPath_default = { ...posix, posix };
630
567
 
631
- // ../contrast-bundler/src/replacementModule.ts
632
- var REPLACEMENT_MODULE_EXTENSIONS = [".js", ".jsx", ".ts", ".tsx"];
633
- var IMPORT_KEYWORD = import_types.TokenType["_import"];
634
- var EXPORT_KEYWORD = import_types.TokenType["_export"];
635
- var REACT_BRIDGE = "globalThis.__sootsim_react_bridge";
636
- var REACT_NATIVE_BRIDGE = "globalThis.__sootsim_components__";
637
- var PACKAGE_BRIDGES = "globalThis.__sootsim_config_package_modules";
638
- var JSX_RUNTIME_SPECIFIERS = /* @__PURE__ */ new Set(["react/jsx-runtime", "react/jsx-dev-runtime"]);
639
- function transformsFor(filePath) {
640
- switch (extname(filePath).toLowerCase()) {
641
- case ".ts":
642
- return ["typescript"];
643
- case ".tsx":
644
- return ["typescript", "jsx"];
645
- case ".js":
646
- case ".jsx":
647
- return ["jsx"];
648
- default:
649
- throw new Error(
650
- `replacement files must be ${REPLACEMENT_MODULE_EXTENSIONS.join(", ")}`
651
- );
568
+ // src/packageVersionsContract.ts
569
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
570
+
571
+ // src/bundleGlobalFooter.ts
572
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
573
+ function findBundleFooter(source, prefix) {
574
+ let end = source.length;
575
+ while (end > 0) {
576
+ const newline = source.lastIndexOf("\n", end - 1);
577
+ if (newline < 0) return -1;
578
+ const line = newline + 1;
579
+ if (source.startsWith(prefix, line)) return newline;
580
+ if (!isFooterBlockLine(source, line, end)) return -1;
581
+ end = newline;
652
582
  }
583
+ return -1;
653
584
  }
654
- function isLocalSpecifier(specifier) {
655
- return specifier.startsWith("./") || specifier.startsWith("../");
656
- }
657
- function isPeachKitSpecifier(specifier) {
658
- return specifier === "peach-kit" || specifier.startsWith("peach-kit/");
585
+ function isFooterBlockLine(source, line, end) {
586
+ return line === end || source.startsWith("globalThis.", line) || source.startsWith("//", line);
659
587
  }
660
- function unsupportedSpecifier(specifier) {
661
- return new Error(
662
- `replacement modules may only import react, react-native, peach-kit, the packages rnx stubs for this app, and other project files by relative path; '${specifier}' is none of those. vendor the code into a project file, or add the package to peach.config so the simulator bridges it.`
588
+ function readFooter(source, prefix, suffix, name) {
589
+ const start = findBundleFooter(source, prefix);
590
+ if (start < 0) return null;
591
+ const end = source.indexOf("\n", start + 1);
592
+ const line = source.slice(start + 1, end < 0 ? void 0 : end);
593
+ if (!line.endsWith(suffix)) throw new Error(`${name} footer is truncated`);
594
+ const value = JSON.parse(
595
+ line.slice(prefix.length, suffix ? -suffix.length : void 0)
663
596
  );
597
+ if (value === null) throw new Error(`${name} footer has no metadata`);
598
+ return value;
664
599
  }
665
- function bridgeDeclaration(name, specifier) {
666
- const notReady = (what) => JSON.stringify(`[peach] replacement ${what} bridge is not ready`);
667
- if (specifier === "react") {
668
- return `const ${name} = ${REACT_BRIDGE}; if (!${name}) throw new Error(${notReady("React")});`;
669
- }
670
- if (specifier === "react-native") {
671
- return `const ${name} = ${REACT_NATIVE_BRIDGE}; if (!${name}) throw new Error(${notReady("React Native")});`;
672
- }
673
- if (isPeachKitSpecifier(specifier)) {
674
- return `const ${name} = (globalThis.__peach_kit_modules && globalThis.__peach_kit_modules[${JSON.stringify(specifier)}]) || (${PACKAGE_BRIDGES} || {})[${JSON.stringify(specifier)}]; if (!${name}) throw new Error(${JSON.stringify(`[peach] replacement package bridge ${specifier} is not ready`)});`;
600
+ function detachFooter(source, prefix, suffix, name) {
601
+ const start = findBundleFooter(source, prefix);
602
+ if (start < 0) return { source, value: null };
603
+ const value = readFooter(source, prefix, suffix, name);
604
+ const end = source.indexOf("\n", start + 1);
605
+ return { source: source.slice(0, start) + (end < 0 ? "" : source.slice(end)), value };
606
+ }
607
+ function insertBundleGlobalFooter(source, name, value) {
608
+ return insertFooter(source, `globalThis.${name}=`, ";", name, value);
609
+ }
610
+ function insertFooter(source, prefix, suffix, name, value) {
611
+ source = detachFooter(source, prefix, suffix, name).source;
612
+ const json = JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/<\//g, "<\\/");
613
+ const footer = `
614
+ ${prefix}${json}${suffix}`;
615
+ const identity = findBundleFooter(source, "globalThis.__sootsimModulePaths=");
616
+ return identity < 0 ? source + footer : source.slice(0, identity) + footer + source.slice(identity);
617
+ }
618
+
619
+ // src/packageVersionsContract.ts
620
+ var PACKAGE_VERSIONS_HEADER = "X-Peach-Package-Versions";
621
+ var FOOTER = "__peachPackageVersions";
622
+ function readPackageVersions(value) {
623
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
624
+ throw new Error("invalid package versions");
675
625
  }
676
- if (JSX_RUNTIME_SPECIFIERS.has(specifier)) {
677
- return `const ${name} = (() => { const react = ${REACT_BRIDGE}; if (!react) throw new Error(${notReady("React")}); const jsx = (type, props, key) => react.createElement(type, key === undefined ? props : { ...props, key }); return { Fragment: react.Fragment, jsx, jsxs: jsx, jsxDEV: jsx }; })();`;
626
+ const versions = {};
627
+ for (const [name, version] of Object.entries(value)) {
628
+ if (name.length === 0 || typeof version !== "string" || version.length === 0) {
629
+ throw new Error("invalid package versions");
630
+ }
631
+ versions[name] = version;
678
632
  }
679
- return `const ${name} = (${PACKAGE_BRIDGES} || {})[${JSON.stringify(specifier)}]; if (!${name}) throw new Error(${JSON.stringify(`[peach] replacement package bridge ${specifier} is not ready`)});`;
633
+ return versions;
680
634
  }
681
- var DEFAULT_INTEROP = "__rnxReplacementDefault";
682
- var DEFAULT_INTEROP_DECLARATION = `const ${DEFAULT_INTEROP} = (bridge) => (bridge && bridge.__esModule ? bridge.default : bridge);`;
683
- function compileReplacementModule(input) {
684
- const transformed = (0, import_dist.transform)(input.source, {
685
- transforms: transformsFor(input.filePath),
686
- filePath: input.filePath,
687
- // the automatic runtime, as @react-native/babel-preset and babel-preset-expo
688
- // compile the app's own files: jsx needs no React import.
689
- jsxRuntime: "automatic",
690
- production: true,
691
- sourceMapOptions: { compiledFilename: input.filePath }
692
- });
693
- const code = transformed.code;
694
- const sourceMap = transformed.sourceMap;
695
- if (!sourceMap) throw new Error("sucrase compiled the replacement with no source map");
696
- const { tokens } = (0, import_parser.parse)(code, false, false, false);
697
- const read = (token) => code.slice(token.start, token.end);
698
- const readSpecifier = (token) => {
699
- if (token.type !== import_types.TokenType.string) {
700
- throw new Error("replacement module import has no string specifier");
701
- }
702
- return code.slice(token.start + 1, token.end - 1);
703
- };
704
- const bridgeNames = /* @__PURE__ */ new Map();
705
- const bareSpecifiers = /* @__PURE__ */ new Set();
706
- const declarations = [];
707
- let needsDefaultInterop = false;
708
- const bridgeFor = (specifier) => {
709
- const existing = bridgeNames.get(specifier);
710
- if (existing) return existing;
711
- const name = `__rnxReplacementBridge${bridgeNames.size}`;
712
- bridgeNames.set(specifier, name);
713
- declarations.push(bridgeDeclaration(name, specifier));
714
- return name;
715
- };
716
- const edits = [];
717
- const pointAtLocalModule = (specifierToken, specifier) => {
718
- edits.push({
719
- start: specifierToken.start,
720
- end: specifierToken.end,
721
- text: JSON.stringify(input.localModuleUrl(specifier))
722
- });
723
- };
724
- for (let index = 0; index < tokens.length; index++) {
725
- const token = tokens[index];
726
- if (token.type === EXPORT_KEYWORD) {
727
- const after2 = tokens[index + 1];
728
- let fromAt = -1;
729
- if (after2?.type === import_types.TokenType.star) {
730
- fromAt = read(tokens[index + 2]) === "from" ? index + 2 : index + 4;
731
- } else if (after2?.type === import_types.TokenType.braceL) {
732
- let depth = 1;
733
- let cursor2 = index + 2;
734
- while (cursor2 < tokens.length && depth > 0) {
735
- if (tokens[cursor2].type === import_types.TokenType.braceL) depth++;
736
- else if (tokens[cursor2].type === import_types.TokenType.braceR) depth--;
737
- cursor2++;
738
- }
739
- fromAt = cursor2;
740
- }
741
- if (fromAt > 0 && tokens[fromAt] && read(tokens[fromAt]) === "from" && tokens[fromAt + 1]?.type === import_types.TokenType.string) {
742
- const specifier2 = readSpecifier(tokens[fromAt + 1]);
743
- if (isLocalSpecifier(specifier2)) {
744
- pointAtLocalModule(tokens[fromAt + 1], specifier2);
745
- continue;
746
- }
747
- throw new Error(
748
- `a replacement module cannot re-export from another module, and this one re-exports from '${specifier2}'. import what you need and export the binding.`
749
- );
750
- }
751
- continue;
752
- }
753
- if (token.type !== IMPORT_KEYWORD) continue;
754
- const after = tokens[index + 1];
755
- if (!after || after.type === import_types.TokenType.parenL || after.type === import_types.TokenType.dot) continue;
756
- const bindings = [];
757
- let cursor = index + 1;
758
- if (after.type !== import_types.TokenType.string) {
759
- while (cursor < tokens.length) {
760
- const clause = tokens[cursor];
761
- if (clause.type === import_types.TokenType.name && read(clause) === "from") break;
762
- if (clause.type === import_types.TokenType.comma) {
763
- cursor++;
764
- continue;
765
- }
766
- if (clause.type === import_types.TokenType.star) {
767
- bindings.push({ local: read(tokens[cursor + 2]), imported: null });
768
- cursor += 3;
769
- continue;
770
- }
771
- if (clause.type === import_types.TokenType.braceL) {
772
- cursor++;
773
- while (cursor < tokens.length && tokens[cursor].type !== import_types.TokenType.braceR) {
774
- if (tokens[cursor].type === import_types.TokenType.comma) {
775
- cursor++;
776
- continue;
777
- }
778
- const nameToken = tokens[cursor];
779
- const imported = nameToken.type === import_types.TokenType.string ? readSpecifier(nameToken) : read(nameToken);
780
- let local = imported;
781
- if (tokens[cursor + 1] && read(tokens[cursor + 1]) === "as") {
782
- local = read(tokens[cursor + 2]);
783
- cursor += 2;
784
- }
785
- bindings.push({ local, imported });
786
- cursor++;
787
- }
788
- cursor++;
789
- continue;
790
- }
791
- bindings.push({ local: read(clause), imported: "default" });
792
- cursor++;
793
- }
794
- cursor++;
795
- }
796
- const specifierToken = tokens[cursor];
797
- if (!specifierToken) throw new Error("replacement module import is unterminated");
798
- const specifier = readSpecifier(specifierToken);
799
- if (isLocalSpecifier(specifier)) {
800
- pointAtLocalModule(specifierToken, specifier);
801
- continue;
802
- }
803
- if (specifier !== "react" && specifier !== "react-native" && !JSX_RUNTIME_SPECIFIERS.has(specifier) && !isPeachKitSpecifier(specifier) && !input.runtimePackages.has(specifier)) {
804
- throw unsupportedSpecifier(specifier);
805
- }
806
- bareSpecifiers.add(specifier);
807
- const bridge = bindings.length > 0 ? bridgeFor(specifier) : null;
808
- const replacement = bindings.map((binding) => {
809
- if (binding.imported === null) return `const ${binding.local} = ${bridge};`;
810
- if (binding.imported === "default") {
811
- needsDefaultInterop = true;
812
- return `const ${binding.local} = ${DEFAULT_INTEROP}(${bridge});`;
813
- }
814
- return `const ${binding.local} = ${bridge}[${JSON.stringify(binding.imported)}];`;
815
- }).join(" ");
816
- const start = token.start;
817
- const end = specifierToken.end;
818
- const newlines = code.slice(start, end).split("\n").length - 1;
819
- edits.push({ start, end, text: replacement + "\n".repeat(newlines) });
820
- }
821
- let out = code;
822
- for (const edit of edits.reverse()) {
823
- out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
824
- }
825
- if (needsDefaultInterop) declarations.unshift(DEFAULT_INTEROP_DECLARATION);
826
- const preamble = declarations.join(" ");
827
- return {
828
- code: preamble ? `${preamble} ${out}` : out,
829
- bareSpecifiers: [...bareSpecifiers],
830
- sourceMap: { ...sourceMap, sourcesContent: [input.source] }
831
- };
635
+ function insertPackageVersionsFooter(source, versions) {
636
+ return insertBundleGlobalFooter(source, FOOTER, readPackageVersions(versions));
832
637
  }
833
638
 
834
- // src/backend-origin.ts
639
+ // src/host/dev-server-package-versions.ts
835
640
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
836
- function normalizeHostname(hostname) {
837
- return hostname.replace(/^\[|\]$/g, "").toLowerCase();
838
- }
839
- function isLoopbackHost(hostname) {
840
- const normalized = normalizeHostname(hostname);
841
- return normalized === "localhost" || normalized.endsWith(".localhost") || normalized === "0.0.0.0" || normalized === "::1" || /^127(?:\.\d{1,3}){3}$/.test(normalized);
842
- }
843
-
844
- // src/host/replacement-module-handler.ts
845
- var REPLACEMENT_MODULE_ROUTE = "/__sootsim-replacement-module";
846
- function sendJavaScript(req, res, source) {
847
- const origin = req.headers.origin;
848
- let allowedOrigin;
849
- if (origin) {
850
- try {
851
- if (isLoopbackHost(new URL(origin).hostname)) allowedOrigin = origin;
852
- } catch {
853
- }
854
- }
855
- res.writeHead(200, {
856
- "Content-Type": "application/javascript; charset=utf-8",
857
- "Cache-Control": "no-cache",
858
- ...allowedOrigin ? { "Access-Control-Allow-Origin": allowedOrigin, Vary: "Origin" } : {}
859
- });
860
- res.end(req.method === "HEAD" ? void 0 : source);
861
- }
862
- function resolveReplacementModuleFile(fromFile, specifier) {
863
- const base = import_node_path4.default.resolve(import_node_path4.default.dirname(fromFile), specifier);
864
- const candidates = [
865
- ...REPLACEMENT_MODULE_EXTENSIONS.some(
866
- (ext) => ext === import_node_path4.default.extname(base).toLowerCase()
867
- ) ? [base] : [],
868
- ...REPLACEMENT_MODULE_EXTENSIONS.map((ext) => base + ext),
869
- ...REPLACEMENT_MODULE_EXTENSIONS.map((ext) => import_node_path4.default.join(base, `index${ext}`))
870
- ];
871
- const found = candidates.find(
872
- (candidate) => (0, import_node_fs4.statSync)(candidate, { throwIfNoEntry: false })?.isFile()
873
- );
874
- if (!found) {
875
- throw new Error(
876
- `'${specifier}' imported by ${fromFile} matches no ${REPLACEMENT_MODULE_EXTENSIONS.join(", ")} file`
877
- );
878
- }
879
- return found;
880
- }
881
- function isInsideAny(roots, file) {
882
- return roots.some((root) => {
883
- const relative2 = import_node_path4.default.relative(root, file);
884
- return !relative2.startsWith("..") && !import_node_path4.default.isAbsolute(relative2);
885
- });
886
- }
887
- async function handleReplacementModuleRequest(req, res, options = {}) {
888
- const rawUrl = req.url || "";
889
- let url;
890
- try {
891
- url = new URL(rawUrl, "http://peach.local");
892
- } catch {
893
- return false;
894
- }
895
- if (url.pathname !== REPLACEMENT_MODULE_ROUTE) return false;
896
- if (options.requireLoopbackOrigin) {
897
- const origin = req.headers.origin;
898
- const remoteAddress = req.socket.remoteAddress?.replace(/^::ffff:/, "");
899
- let allowed = Boolean(remoteAddress && isLoopbackHost(remoteAddress));
900
- if (allowed && origin) {
901
- try {
902
- allowed = isLoopbackHost(new URL(origin).hostname);
903
- } catch {
904
- allowed = false;
905
- }
906
- }
907
- if (!allowed) {
908
- res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
909
- res.end("replacement modules are available only to loopback origins");
910
- return true;
911
- }
912
- }
913
- if (options.requestToken && url.searchParams.get("token") !== options.requestToken) {
914
- res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
915
- res.end("replacement module request token is invalid");
916
- return true;
917
- }
918
- const targetPath = url.searchParams.get("path");
919
- if (!targetPath) {
920
- res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
921
- res.end("missing path param");
922
- return true;
923
- }
924
- const extension = import_node_path4.default.extname(targetPath).toLowerCase();
925
- if (!REPLACEMENT_MODULE_EXTENSIONS.some((allowed) => allowed === extension)) {
926
- res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
927
- res.end(`replacement files must be ${REPLACEMENT_MODULE_EXTENSIONS.join(", ")}`);
928
- return true;
929
- }
930
- if (!import_node_path4.default.isAbsolute(targetPath)) {
931
- res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
932
- res.end("replacement file path must be absolute");
933
- return true;
934
- }
935
- const runtimePackages = new Set(url.searchParams.getAll("runtimePackage"));
936
- const servedRoots = options.servedRoots?.map((root) => import_node_path4.default.resolve(root));
937
- if (servedRoots && !isInsideAny(servedRoots, targetPath)) {
938
- res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
939
- res.end("replacement file must be inside a folder the bundler serves");
940
- return true;
941
- }
942
- let resolvedTargetPath;
943
- try {
944
- resolvedTargetPath = await import_promises.default.realpath(targetPath);
945
- } catch (error) {
946
- const message = error instanceof Error ? error.message : String(error);
947
- res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
948
- res.end(`replacement file not found: ${message}`);
949
- return true;
950
- }
951
- if (servedRoots) {
952
- const realRoots = (await Promise.all(servedRoots.map((root) => import_promises.default.realpath(root).catch(() => null)))).filter((root) => root !== null);
953
- if (!isInsideAny(realRoots, resolvedTargetPath)) {
954
- res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
955
- res.end("replacement file must be inside a folder the bundler serves");
956
- return true;
957
- }
958
- }
959
- try {
960
- const compiled = compileReplacementModule({
961
- filePath: resolvedTargetPath,
962
- source: await import_promises.default.readFile(resolvedTargetPath, "utf8"),
963
- runtimePackages,
964
- // the imported file's url is this request's with only its path changed,
965
- // so the token, cache key and runtime packages carry over.
966
- localModuleUrl: (specifier) => {
967
- const local = new URL(url.href);
968
- local.searchParams.set(
969
- "path",
970
- resolveReplacementModuleFile(targetPath, specifier)
971
- );
972
- return `${local.pathname}${local.search}`;
973
- }
974
- });
975
- const map = Buffer.from(JSON.stringify(compiled.sourceMap), "utf8").toString("base64");
976
- sendJavaScript(
977
- req,
978
- res,
979
- compiled.code + "\n//# sourceMappingURL=data:application/json;base64," + map + "\n"
980
- );
981
- } catch (error) {
982
- const message = error instanceof Error ? error.message : String(error);
983
- res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
984
- res.end(`replacement compile failed: ${message}`);
985
- }
986
- return true;
987
- }
641
+ var import_fs3 = __toESM(require("fs"), 1);
642
+ var import_path3 = __toESM(require("path"), 1);
988
643
 
989
- // src/host/rolldown-bundle-forward.ts
990
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
991
- var import_stream = require("stream");
992
- var import_promises2 = require("stream/promises");
993
- init_cli_runtime();
994
- var ROLLDOWN_INVENTORY_HEADER = "x-peach-rolldown-inventory";
995
- async function forwardRolldownBundleResponse(upstream, res) {
996
- res.setHeader(ROLLDOWN_INVENTORY_HEADER, "1");
997
- if (upstream.headers[ROLLDOWN_INVENTORY_HEADER] === "1") {
998
- await (0, import_promises2.pipeline)(upstream, res);
999
- return;
1000
- }
1001
- const contentType = typeof upstream.headers["content-type"] === "string" ? upstream.headers["content-type"] : "";
1002
- const inventory = getCliRuntime().rolldown_bundle_inventory;
1003
- res.removeHeader("content-length");
1004
- const annotate = async function* () {
1005
- const decoder = new TextDecoder();
1006
- let payload = "";
1007
- let sent = 0;
1008
- let bundleStarted = false;
1009
- for await (const chunk of upstream) {
1010
- payload += decoder.decode(chunk, { stream: true });
1011
- if (bundleStarted) continue;
1012
- const releasable = inventory.releasableMultipartPrefix(payload, contentType);
1013
- bundleStarted = releasable.bundleStarted;
1014
- if (releasable.length > sent) {
1015
- yield Buffer.from(payload.slice(sent, releasable.length), "utf8");
1016
- sent = releasable.length;
1017
- }
1018
- }
1019
- payload += decoder.decode();
1020
- let annotated;
1021
- try {
1022
- annotated = await inventory.attachRolldownBundleHttpPayload(payload, contentType);
1023
- } catch (error) {
1024
- const message = `could not attach the rolldown bundle inventory: ${error instanceof Error ? error.message : String(error)}`;
1025
- console.error(`[peach] ${message}`);
1026
- if (contentType.toLowerCase().includes("multipart/mixed")) {
1027
- yield Buffer.from(
1028
- inventory.multipartFailurePart(contentType, message, payload.slice(0, sent)),
1029
- "utf8"
1030
- );
1031
- return;
1032
- }
1033
- res.statusCode = 500;
1034
- res.setHeader("content-type", "application/json");
1035
- yield Buffer.from(JSON.stringify({ message }), "utf8");
1036
- return;
1037
- }
1038
- yield Buffer.from(annotated.slice(sent), "utf8");
1039
- };
1040
- await (0, import_promises2.pipeline)(import_stream.Readable.from(annotate(), { objectMode: false }), res);
1041
- }
1042
-
1043
- // src/installed-package-versions.ts
644
+ // src/installed-package-versions.ts
1044
645
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
1045
646
  var import_fs2 = __toESM(require("fs"), 1);
1046
647
  var import_path2 = __toESM(require("path"), 1);
@@ -2427,6 +2028,7 @@ var NATIVE_STUB_PACKAGE_NAMES = [
2427
2028
  "expo-quick-actions",
2428
2029
  "expo-rich-input",
2429
2030
  "expo-roomplan",
2031
+ "expo-router",
2430
2032
  "expo-screen-capture",
2431
2033
  "expo-screen-corner-radius",
2432
2034
  "expo-screen-orientation",
@@ -3026,7 +2628,6 @@ var NATIVE_RUNTIME_PACKAGE_NAMES = [
3026
2628
  "@tamagui/native-registry",
3027
2629
  "@uniswap/ethers-rs-mobile",
3028
2630
  "@valora/react-native-keychain",
3029
- "expo-router",
3030
2631
  "react-native-app-control",
3031
2632
  "react-native-blue-crypto",
3032
2633
  "react-native-nitro-base64",
@@ -3916,191 +3517,1803 @@ function packageNameAt(modulePath, start) {
3916
3517
  const secondSlash = modulePath.indexOf("/", firstSlash + 1);
3917
3518
  return modulePath.slice(start, secondSlash === -1 ? void 0 : secondSlash);
3918
3519
  }
3919
- return modulePath.slice(start, firstSlash === -1 ? void 0 : firstSlash);
3920
- }
3921
-
3922
- // src/installed-package-versions.ts
3923
- function* exists(target) {
3924
- return (yield { op: "exists", path: target }) === true;
3925
- }
3926
- function* realpath(target) {
3927
- const resolved = yield { op: "realpath", path: target };
3928
- if (typeof resolved !== "string") throw new Error(`could not resolve ${target}`);
3929
- return resolved;
3930
- }
3931
- function* readManifest(target) {
3932
- const manifest = yield { op: "manifest", path: target };
3933
- return typeof manifest === "object" ? manifest : null;
3934
- }
3935
- function parseManifest(source) {
3936
- const manifest = JSON.parse(source);
3937
- return typeof manifest === "object" && manifest !== null ? manifest : null;
3938
- }
3939
- function isMissing(error) {
3940
- return error instanceof Error && "code" in error && error.code === "ENOENT";
3941
- }
3942
- function answerSync(step) {
3943
- if (step.op === "exists") return import_fs2.default.existsSync(step.path);
3944
- if (step.op === "realpath") return import_fs2.default.realpathSync(step.path);
3520
+ return modulePath.slice(start, firstSlash === -1 ? void 0 : firstSlash);
3521
+ }
3522
+
3523
+ // src/installed-package-versions.ts
3524
+ function* exists(target) {
3525
+ return (yield { op: "exists", path: target }) === true;
3526
+ }
3527
+ function* realpath(target) {
3528
+ const resolved = yield { op: "realpath", path: target };
3529
+ if (typeof resolved !== "string") throw new Error(`could not resolve ${target}`);
3530
+ return resolved;
3531
+ }
3532
+ function* readManifest(target) {
3533
+ const manifest = yield { op: "manifest", path: target };
3534
+ return typeof manifest === "object" ? manifest : null;
3535
+ }
3536
+ function parseManifest(source) {
3537
+ const manifest = JSON.parse(source);
3538
+ return typeof manifest === "object" && manifest !== null ? manifest : null;
3539
+ }
3540
+ function isMissing(error) {
3541
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
3542
+ }
3543
+ function answerSync(step) {
3544
+ if (step.op === "exists") return import_fs2.default.existsSync(step.path);
3545
+ if (step.op === "realpath") return import_fs2.default.realpathSync(step.path);
3546
+ try {
3547
+ return parseManifest(import_fs2.default.readFileSync(step.path, "utf8"));
3548
+ } catch (error) {
3549
+ if (isMissing(error)) return null;
3550
+ throw error;
3551
+ }
3552
+ }
3553
+ async function answerAsync(step) {
3554
+ if (step.op === "exists")
3555
+ return import_fs2.default.promises.access(step.path).then(
3556
+ () => true,
3557
+ () => false
3558
+ );
3559
+ if (step.op === "realpath") return import_fs2.default.promises.realpath(step.path);
3560
+ try {
3561
+ return parseManifest(await import_fs2.default.promises.readFile(step.path, "utf8"));
3562
+ } catch (error) {
3563
+ if (isMissing(error)) return null;
3564
+ throw error;
3565
+ }
3566
+ }
3567
+ function runSync(walk) {
3568
+ for (let step = walk.next(); ; ) {
3569
+ if (step.done) return step.value;
3570
+ step = walk.next(answerSync(step.value));
3571
+ }
3572
+ }
3573
+ async function runAsync(walk) {
3574
+ for (let step = walk.next(); ; ) {
3575
+ if (step.done) return step.value;
3576
+ step = walk.next(await answerAsync(step.value));
3577
+ }
3578
+ }
3579
+ function createInstalledPackageReader() {
3580
+ const hasModules = /* @__PURE__ */ new Map();
3581
+ const manifests = /* @__PURE__ */ new Map();
3582
+ return function* readInstalledPackage(fromDir, name) {
3583
+ for (let dir = fromDir; ; ) {
3584
+ if (import_path2.default.basename(dir) !== "node_modules") {
3585
+ const modules = import_path2.default.join(dir, "node_modules");
3586
+ let present = hasModules.get(dir);
3587
+ if (present === void 0) {
3588
+ present = yield* exists(modules);
3589
+ hasModules.set(dir, present);
3590
+ }
3591
+ if (present) {
3592
+ const root = import_path2.default.join(modules, name);
3593
+ let installed = manifests.get(root);
3594
+ if (installed === void 0) {
3595
+ const manifest = yield* readManifest(import_path2.default.join(root, "package.json"));
3596
+ installed = manifest ? { root, manifest } : null;
3597
+ manifests.set(root, installed);
3598
+ }
3599
+ if (installed) return installed;
3600
+ }
3601
+ }
3602
+ const parent = import_path2.default.dirname(dir);
3603
+ if (parent === dir) return null;
3604
+ dir = parent;
3605
+ }
3606
+ };
3607
+ }
3608
+ function* installedVersionsWalk(projectRoot, names) {
3609
+ const readInstalledPackage = createInstalledPackageReader();
3610
+ const versions = {};
3611
+ for (const name of [...names].sort()) {
3612
+ const installed = yield* readInstalledPackage(projectRoot, name);
3613
+ const version = installed && Reflect.get(installed.manifest, "version");
3614
+ if (typeof version === "string" && version.length > 0) versions[name] = version;
3615
+ }
3616
+ return versions;
3617
+ }
3618
+ function* nativePackageVersionsWalk(projectRoot) {
3619
+ const appRoot = yield* realpath(projectRoot);
3620
+ const nativeNames = /* @__PURE__ */ new Set();
3621
+ for (const specifier of [
3622
+ "react-native",
3623
+ ...NATIVE_RUNTIME_PACKAGE_NAMES,
3624
+ ...LAZY_STUB_PATTERNS,
3625
+ ...Object.values(COMPAT_STUBS).map((entry) => entry.specifier)
3626
+ ]) {
3627
+ const name = extractPackageFromPath(`node_modules/${specifier}`);
3628
+ if (name) nativeNames.add(name);
3629
+ }
3630
+ const manifest = yield* readManifest(import_path2.default.join(appRoot, "package.json"));
3631
+ if (!manifest) throw new Error("app package.json must contain an object");
3632
+ const readInstalledPackage = createInstalledPackageReader();
3633
+ const pending = [{ root: appRoot, manifest }];
3634
+ const visited = /* @__PURE__ */ new Set();
3635
+ const needed = /* @__PURE__ */ new Set();
3636
+ for (let next = pending.pop(); next; next = pending.pop()) {
3637
+ const root = yield* realpath(next.root);
3638
+ if (visited.has(root)) continue;
3639
+ visited.add(root);
3640
+ const fields = ["dependencies", "optionalDependencies", "peerDependencies"];
3641
+ if (root === appRoot) fields.push("devDependencies");
3642
+ const peers = Reflect.get(next.manifest, "peerDependenciesMeta");
3643
+ for (const field of fields) {
3644
+ const dependencies = Reflect.get(next.manifest, field);
3645
+ if (typeof dependencies !== "object" || dependencies === null) continue;
3646
+ for (const name of Object.keys(dependencies)) {
3647
+ if (field === "peerDependencies" && typeof peers === "object" && peers !== null) {
3648
+ const peer = Reflect.get(peers, name);
3649
+ if (typeof peer === "object" && peer !== null && Reflect.get(peer, "optional"))
3650
+ continue;
3651
+ }
3652
+ const installed = yield* readInstalledPackage(root, name);
3653
+ if (!installed) continue;
3654
+ if (nativeNames.has(name)) needed.add(name);
3655
+ pending.push(installed);
3656
+ }
3657
+ }
3658
+ }
3659
+ return yield* installedVersionsWalk(projectRoot, needed);
3660
+ }
3661
+ function readInstalledNativePackageVersions(projectRoot) {
3662
+ return runSync(nativePackageVersionsWalk(projectRoot));
3663
+ }
3664
+ var INSTALL_RECORD_FILES = [
3665
+ "package.json",
3666
+ "bun.lock",
3667
+ "bun.lockb",
3668
+ "package-lock.json",
3669
+ "yarn.lock",
3670
+ "pnpm-lock.yaml",
3671
+ "node_modules",
3672
+ "node_modules/.package-lock.json",
3673
+ "node_modules/.yarn-integrity",
3674
+ "node_modules/.modules.yaml"
3675
+ ];
3676
+ async function installFingerprint(projectRoot) {
3677
+ const appRoot = await import_fs2.default.promises.realpath(projectRoot);
3678
+ const targets = [];
3679
+ for (let dir = appRoot; ; ) {
3680
+ if (import_path2.default.basename(dir) !== "node_modules")
3681
+ for (const file of INSTALL_RECORD_FILES) targets.push(import_path2.default.join(dir, file));
3682
+ const parent = import_path2.default.dirname(dir);
3683
+ if (parent === dir) break;
3684
+ dir = parent;
3685
+ }
3686
+ const stats = await Promise.all(
3687
+ targets.map(
3688
+ (target) => import_fs2.default.promises.stat(target).then(
3689
+ (stat) => `${stat.ino}:${stat.size}:${stat.mtimeMs}`,
3690
+ () => ""
3691
+ )
3692
+ )
3693
+ );
3694
+ return `${appRoot}
3695
+ ${stats.join("\n")}`;
3696
+ }
3697
+ var scans = /* @__PURE__ */ new Map();
3698
+ async function readInstalledNativePackageVersionsAsync(projectRoot) {
3699
+ const fingerprint = await installFingerprint(projectRoot);
3700
+ const cached = scans.get(projectRoot);
3701
+ if (cached?.fingerprint === fingerprint) return cached.versions;
3702
+ const versions = runAsync(nativePackageVersionsWalk(projectRoot));
3703
+ scans.set(projectRoot, { fingerprint, versions });
3704
+ versions.catch(() => {
3705
+ if (scans.get(projectRoot)?.versions === versions) scans.delete(projectRoot);
3706
+ });
3707
+ return versions;
3708
+ }
3709
+
3710
+ // src/metro-project-root.ts
3711
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3712
+
3713
+ // scripts/dev-server-scanner.ts
3714
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3715
+ var import_child_process = require("child_process");
3716
+ var import_promises = require("fs/promises");
3717
+ var import_node_fs4 = require("node:fs");
3718
+ var import_node_os2 = require("node:os");
3719
+ var import_node_path4 = require("node:path");
3720
+
3721
+ // src/config.ts
3722
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3723
+ init_version();
3724
+
3725
+ // src/is-record.ts
3726
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3727
+ function isRecord(value) {
3728
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3729
+ }
3730
+
3731
+ // src/nativeViewSourceContract.ts
3732
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3733
+
3734
+ // src/dev-bundle-resolution.ts
3735
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3736
+
3737
+ // src/expo-manifest-body.ts
3738
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3739
+ function parseExpoManifestBody(body) {
3740
+ const opening = /^(--[^\r\n]+)\r?\n/.exec(body);
3741
+ if (!opening) return JSON.parse(body);
3742
+ for (const part of body.split(opening[1])) {
3743
+ const headerEnd = part.search(/\r?\n\r?\n/);
3744
+ if (headerEnd < 0 || !/\bname="manifest"/.test(part.slice(0, headerEnd))) continue;
3745
+ return JSON.parse(part.slice(headerEnd).trim());
3746
+ }
3747
+ throw new Error("Expo manifest response has no manifest part");
3748
+ }
3749
+
3750
+ // src/native-dev-bundle-url.ts
3751
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3752
+
3753
+ // src/dev-bundle-resolution.ts
3754
+ var MANIFEST_PROBE_TIMEOUT_MS = 3e4;
3755
+
3756
+ // src/kotlinDiscoveryContract.ts
3757
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3758
+
3759
+ // src/oneWidgetContract.ts
3760
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3761
+ var HOME_WIDGET_FAMILIES = [
3762
+ "systemSmall",
3763
+ "systemMedium",
3764
+ "systemLarge",
3765
+ "systemExtraLargePortrait"
3766
+ ];
3767
+ function isHomeWidgetFamily(value) {
3768
+ return HOME_WIDGET_FAMILIES.some((family) => family === value);
3769
+ }
3770
+
3771
+ // src/settings-bundle.ts
3772
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3773
+
3774
+ // src/plist.ts
3775
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3776
+ var import_plist = __toESM(require("plist"), 1);
3777
+
3778
+ // src/swiftDiscoveryContract.ts
3779
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3780
+
3781
+ // scripts/optional-demo-registry.ts
3782
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
3783
+
3784
+ // scripts/dev-server-scanner.ts
3785
+ var LISTENER_LOCK_PATH = (0, import_node_path4.join)((0, import_node_os2.tmpdir)(), "peach-listener-scan.lock");
3786
+ var LISTENER_RESULT_PATH = (0, import_node_path4.join)((0, import_node_os2.tmpdir)(), "peach-listener-scan.result");
3787
+ var LISTENER_LOCK_STALE_MS = 25e3;
3788
+ var LISTENER_LOCK_WAIT_MS = 8e3;
3789
+ function sleep(ms) {
3790
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
3791
+ }
3792
+ function pidIsAlive(pid) {
3793
+ if (!Number.isInteger(pid) || pid <= 0) return false;
3794
+ try {
3795
+ process.kill(pid, 0);
3796
+ return true;
3797
+ } catch (error) {
3798
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
3799
+ return code !== "ESRCH";
3800
+ }
3801
+ }
3802
+ function readLockOwner() {
3803
+ try {
3804
+ const raw = (0, import_node_fs4.readFileSync)(LISTENER_LOCK_PATH, "utf8");
3805
+ const mtimeMs = (0, import_node_fs4.statSync)(LISTENER_LOCK_PATH).mtimeMs;
3806
+ const pid = Number(raw.split("-")[0]);
3807
+ return { raw, pid: Number.isInteger(pid) ? pid : -1, mtimeMs };
3808
+ } catch {
3809
+ return null;
3810
+ }
3811
+ }
3812
+ function lockIsAbandoned(owner) {
3813
+ if (owner.pid <= 0 || !pidIsAlive(owner.pid)) return true;
3814
+ return Date.now() - owner.mtimeMs > LISTENER_LOCK_STALE_MS;
3815
+ }
3816
+ function clearLock(raw) {
3817
+ try {
3818
+ if ((0, import_node_fs4.readFileSync)(LISTENER_LOCK_PATH, "utf8") !== raw) return;
3819
+ (0, import_node_fs4.unlinkSync)(LISTENER_LOCK_PATH);
3820
+ } catch {
3821
+ }
3822
+ }
3823
+ function readResult() {
3824
+ try {
3825
+ const parsed = JSON.parse(
3826
+ (0, import_node_fs4.readFileSync)(LISTENER_RESULT_PATH, "utf8")
3827
+ );
3828
+ if (!parsed || typeof parsed.token !== "string" || typeof parsed.key !== "string")
3829
+ return null;
3830
+ return parsed;
3831
+ } catch {
3832
+ return null;
3833
+ }
3834
+ }
3835
+ function publishResult(payload) {
3836
+ const tmp = `${LISTENER_RESULT_PATH}.${process.pid}.tmp`;
3837
+ (0, import_node_fs4.writeFileSync)(tmp, JSON.stringify(payload));
3838
+ (0, import_node_fs4.renameSync)(tmp, LISTENER_RESULT_PATH);
3839
+ }
3840
+ function throwPublished(payload) {
3841
+ throw Object.assign(new Error(payload.message || "listener scan failed"), {
3842
+ killed: payload.killed === true
3843
+ });
3844
+ }
3845
+ async function waitForSharedResult(owner, key) {
3846
+ const cap = Date.now() + LISTING_TIMEOUT_MS;
3847
+ let current = owner;
3848
+ while (Date.now() < cap) {
3849
+ const published = readResult();
3850
+ if (published && published.token === current.raw) {
3851
+ if (published.key !== key) return { kind: "retry" };
3852
+ if (!published.ok) throwPublished(published);
3853
+ return { kind: "value", value: published.value };
3854
+ }
3855
+ const latest = readLockOwner();
3856
+ if (!latest) {
3857
+ const again = readResult();
3858
+ if (again && again.token === current.raw && again.key === key) {
3859
+ if (!again.ok) throwPublished(again);
3860
+ return { kind: "value", value: again.value };
3861
+ }
3862
+ return { kind: "retry" };
3863
+ }
3864
+ if (latest.raw !== current.raw) current = latest;
3865
+ if (lockIsAbandoned(latest)) {
3866
+ clearLock(latest.raw);
3867
+ return { kind: "retry" };
3868
+ }
3869
+ await sleep(25);
3870
+ }
3871
+ throw Object.assign(new Error("listener scan lock was held past the wait"), {
3872
+ killed: true
3873
+ });
3874
+ }
3875
+ async function withListenerLock(key, body) {
3876
+ const token = `${process.pid}-${Date.now()}-${Math.random()}`;
3877
+ const deadline = Date.now() + LISTENER_LOCK_WAIT_MS;
3878
+ for (; ; ) {
3879
+ let fd = null;
3880
+ try {
3881
+ fd = (0, import_node_fs4.openSync)(LISTENER_LOCK_PATH, "wx");
3882
+ } catch (error) {
3883
+ const code = error instanceof Error && "code" in error ? error.code : "";
3884
+ if (code !== "EEXIST") throw error;
3885
+ const owner = readLockOwner();
3886
+ if (!owner || lockIsAbandoned(owner)) {
3887
+ if (owner) clearLock(owner.raw);
3888
+ else {
3889
+ try {
3890
+ (0, import_node_fs4.unlinkSync)(LISTENER_LOCK_PATH);
3891
+ } catch {
3892
+ }
3893
+ }
3894
+ continue;
3895
+ }
3896
+ if (Date.now() >= deadline) {
3897
+ const shared = await waitForSharedResult(owner, key);
3898
+ if (shared.kind === "value") return shared.value;
3899
+ continue;
3900
+ }
3901
+ await sleep(25);
3902
+ continue;
3903
+ }
3904
+ if (fd === null) continue;
3905
+ try {
3906
+ (0, import_node_fs4.writeSync)(fd, token);
3907
+ try {
3908
+ const value = await body();
3909
+ publishResult({ token, key, ok: true, value });
3910
+ return value;
3911
+ } catch (error) {
3912
+ publishResult({
3913
+ token,
3914
+ key,
3915
+ ok: false,
3916
+ message: error instanceof Error ? error.message : String(error),
3917
+ killed: !!(error && typeof error === "object" && error.killed)
3918
+ });
3919
+ throw error;
3920
+ }
3921
+ } finally {
3922
+ try {
3923
+ (0, import_node_fs4.closeSync)(fd);
3924
+ } catch {
3925
+ }
3926
+ clearLock(token);
3927
+ }
3928
+ }
3929
+ }
3930
+ function spawnReaped(file, args, timeoutMs, maxBuffer = 1024 * 1024) {
3931
+ return withListenerLock(
3932
+ `${file}\0${args.join("\0")}`,
3933
+ () => new Promise((resolvePromise, reject) => {
3934
+ const child = (0, import_child_process.spawn)(file, args, {
3935
+ stdio: ["ignore", "pipe", "pipe"]
3936
+ });
3937
+ let stdout = "";
3938
+ let settled = false;
3939
+ let timedOut = false;
3940
+ let overflow = false;
3941
+ let spawnError = null;
3942
+ const timeoutError = () => Object.assign(new Error(`\`${file}\` did not exit within ${timeoutMs}ms`), {
3943
+ killed: true
3944
+ });
3945
+ const finish = (err, code) => {
3946
+ if (settled) return;
3947
+ settled = true;
3948
+ clearTimeout(deadline);
3949
+ clearTimeout(backup);
3950
+ if (err) reject(err);
3951
+ else resolvePromise({ stdout, code });
3952
+ };
3953
+ const killChild = () => {
3954
+ if (child.exitCode !== null || child.signalCode !== null) return;
3955
+ try {
3956
+ child.kill("SIGKILL");
3957
+ } catch {
3958
+ }
3959
+ };
3960
+ let backup;
3961
+ const deadline = setTimeout(() => {
3962
+ timedOut = true;
3963
+ killChild();
3964
+ backup = setTimeout(() => finish(timeoutError(), null), 1e3);
3965
+ }, timeoutMs);
3966
+ child.stdout?.setEncoding("utf8");
3967
+ child.stderr?.on("data", () => {
3968
+ });
3969
+ child.stdout?.on("data", (chunk) => {
3970
+ stdout += chunk;
3971
+ if (stdout.length > maxBuffer) {
3972
+ overflow = true;
3973
+ killChild();
3974
+ }
3975
+ });
3976
+ child.on("error", (err) => {
3977
+ spawnError = err;
3978
+ killChild();
3979
+ });
3980
+ child.on("close", (code) => {
3981
+ if (timedOut) finish(timeoutError(), code);
3982
+ else if (overflow)
3983
+ finish(new Error(`\`${file}\` exceeded maxBuffer ${maxBuffer}`), code);
3984
+ else if (spawnError && !stdout) finish(spawnError, code);
3985
+ else finish(null, code);
3986
+ });
3987
+ })
3988
+ );
3989
+ }
3990
+ var FALLBACK_PORTS = [
3991
+ 8081,
3992
+ 8082,
3993
+ 8083,
3994
+ 8084,
3995
+ 8085,
3996
+ 8086,
3997
+ 3e3,
3998
+ 3001,
3999
+ 19e3
4000
+ ].map((port) => ({ port, pid: 0 }));
4001
+ var LISTING_TIMEOUT_MS = 1e4;
4002
+ function wasKilledByTimeout(err) {
4003
+ return !!(err && typeof err === "object" && err.killed);
4004
+ }
4005
+ var LISTENER_CACHE_MS = 2e3;
4006
+ var listenerCache = null;
4007
+ var inflightListing = null;
4008
+ var listenerHolds = 0;
4009
+ function cachedPidsAlive(scan) {
4010
+ if (scan.state !== "looked") return true;
4011
+ return scan.processes.every((entry) => entry.pid <= 0 || pidIsAlive(entry.pid));
4012
+ }
4013
+ async function cachedPortsStillHeld(scan) {
4014
+ if (scan.state !== "looked") return true;
4015
+ const owned = scan.processes.filter((entry) => entry.pid > 0);
4016
+ if (owned.length === 0) return true;
4017
+ const pids = [...new Set(owned.map((entry) => entry.pid))];
4018
+ try {
4019
+ const { stdout, code } = await spawnReaped(
4020
+ "lsof",
4021
+ ["-nP", "-b", "-w", "-a", "-p", pids.join(","), "-iTCP", "-sTCP:LISTEN", "-Fpcn"],
4022
+ 8e3,
4023
+ 16 * 1024 * 1024
4024
+ );
4025
+ if (code !== 0 && code !== 1) return false;
4026
+ const live = new Set(
4027
+ parseLsofListeners(stdout).map((entry) => `${entry.port}:${entry.pid}`)
4028
+ );
4029
+ return owned.every((entry) => live.has(`${entry.port}:${entry.pid}`));
4030
+ } catch {
4031
+ return false;
4032
+ }
4033
+ }
4034
+ function listListenersShared() {
4035
+ inflightListing ??= loadListeners().finally(() => {
4036
+ inflightListing = null;
4037
+ });
4038
+ return inflightListing;
4039
+ }
4040
+ async function loadListeners() {
4041
+ const cached = listenerCache;
4042
+ if (cached && (listenerHolds > 0 || Date.now() - cached.at < LISTENER_CACHE_MS) && cachedPidsAlive(cached.scan) && await cachedPortsStillHeld(cached.scan)) {
4043
+ return cached.scan;
4044
+ }
4045
+ listenerCache = null;
4046
+ const scan = await listListeners();
4047
+ listenerCache = { at: Date.now(), scan };
4048
+ return scan;
4049
+ }
4050
+ function isSpawnMissing(err) {
4051
+ return !!(err && typeof err === "object" && err.code === "ENOENT");
4052
+ }
4053
+ function parseLsofListeners(stdout) {
4054
+ const seen = /* @__PURE__ */ new Map();
4055
+ let pid = 0;
4056
+ let command = "";
4057
+ for (const line of stdout.split("\n")) {
4058
+ if (line.startsWith("p")) {
4059
+ pid = Number(line.slice(1));
4060
+ command = "";
4061
+ continue;
4062
+ }
4063
+ if (line.startsWith("c")) {
4064
+ command = line.slice(1);
4065
+ continue;
4066
+ }
4067
+ if (!line.startsWith("n") || pid <= 0) continue;
4068
+ if (!/^(node|bun|peach|vite)/.test(command)) continue;
4069
+ const match = line.match(/:(\d+)$/);
4070
+ if (!match) continue;
4071
+ const port = Number(match[1]);
4072
+ if (!seen.has(port)) seen.set(port, pid);
4073
+ }
4074
+ return [...seen.entries()].map(([port, owner]) => ({ port, pid: owner }));
4075
+ }
4076
+ function parseSsListeners(stdout) {
4077
+ const seen = /* @__PURE__ */ new Map();
4078
+ for (const line of stdout.split("\n")) {
4079
+ if (!/"(node|bun|peach|vite)/.test(line)) continue;
4080
+ const portMatch = line.match(/:(\d+)\s/);
4081
+ const pidMatch = line.match(/pid=(\d+)/);
4082
+ if (!portMatch) continue;
4083
+ const port = Number(portMatch[1]);
4084
+ const pid = pidMatch ? Number(pidMatch[1]) : 0;
4085
+ if (!seen.has(port)) seen.set(port, pid);
4086
+ }
4087
+ return [...seen.entries()].map(([port, pid]) => ({ port, pid }));
4088
+ }
4089
+ async function listListeners() {
4090
+ let timedOut = false;
4091
+ try {
4092
+ const { stdout, code } = await spawnReaped(
4093
+ "lsof",
4094
+ [
4095
+ "-nP",
4096
+ "-b",
4097
+ "-w",
4098
+ "-a",
4099
+ "-c",
4100
+ "node",
4101
+ "-c",
4102
+ "bun",
4103
+ "-c",
4104
+ "peach",
4105
+ "-c",
4106
+ "vite",
4107
+ "-iTCP",
4108
+ "-sTCP:LISTEN",
4109
+ "-Fpcn"
4110
+ ],
4111
+ LISTING_TIMEOUT_MS,
4112
+ 16 * 1024 * 1024
4113
+ );
4114
+ if (code === 0 || code === 1) {
4115
+ return { state: "looked", processes: parseLsofListeners(stdout) };
4116
+ }
4117
+ } catch (err) {
4118
+ if (wasKilledByTimeout(err)) timedOut = true;
4119
+ else if (!isSpawnMissing(err)) return { state: "could-not-look" };
4120
+ }
4121
+ if (!timedOut) {
4122
+ try {
4123
+ const { stdout, code } = await spawnReaped(
4124
+ "ss",
4125
+ ["-H", "-ltnp"],
4126
+ LISTING_TIMEOUT_MS,
4127
+ 16 * 1024 * 1024
4128
+ );
4129
+ if (code === 0 || code === 1) {
4130
+ return { state: "looked", processes: parseSsListeners(stdout) };
4131
+ }
4132
+ } catch (err) {
4133
+ if (wasKilledByTimeout(err)) timedOut = true;
4134
+ else if (!isSpawnMissing(err)) return { state: "could-not-look" };
4135
+ }
4136
+ }
4137
+ if (timedOut) return { state: "could-not-look" };
4138
+ return { state: "looked", processes: FALLBACK_PORTS };
4139
+ }
4140
+ async function resolveListeningPid(port) {
4141
+ if (!Number.isInteger(port) || port <= 0) return null;
4142
+ const scan = await listListenersShared();
4143
+ if (scan.state !== "looked") return null;
4144
+ const pids = [
4145
+ ...new Set(
4146
+ scan.processes.filter((entry) => entry.port === port && entry.pid > 0).map((entry) => entry.pid)
4147
+ )
4148
+ ];
4149
+ return pids.length === 1 && pids[0] !== void 0 ? pids[0] : null;
4150
+ }
4151
+ var cwdByPid = /* @__PURE__ */ new Map();
4152
+ var cwdQueue = [];
4153
+ var cwdFlushing = false;
4154
+ function kickCwdFlush() {
4155
+ if (cwdFlushing || cwdQueue.length === 0) return;
4156
+ cwdFlushing = true;
4157
+ void flushCwdQueue().finally(() => {
4158
+ cwdFlushing = false;
4159
+ kickCwdFlush();
4160
+ });
4161
+ }
4162
+ async function flushCwdQueue() {
4163
+ await Promise.resolve();
4164
+ while (cwdQueue.length > 0) {
4165
+ const batch = cwdQueue.splice(0, cwdQueue.length);
4166
+ const pending = [...new Set(batch.map((waiter) => waiter.pid))].filter(
4167
+ (pid) => !cwdByPid.has(pid)
4168
+ );
4169
+ const needLsof = [];
4170
+ for (const pid of pending) {
4171
+ try {
4172
+ const cwd = await (0, import_promises.readlink)(`/proc/${pid}/cwd`);
4173
+ if (cwd) {
4174
+ cwdByPid.set(pid, cwd);
4175
+ continue;
4176
+ }
4177
+ } catch {
4178
+ }
4179
+ needLsof.push(pid);
4180
+ }
4181
+ if (needLsof.length > 0) {
4182
+ let looked = false;
4183
+ try {
4184
+ const { stdout, code } = await spawnReaped(
4185
+ "lsof",
4186
+ ["-b", "-w", "-nP", "-a", "-d", "cwd", "-p", needLsof.join(","), "-Fn"],
4187
+ 8e3,
4188
+ 4 * 1024 * 1024
4189
+ );
4190
+ if (code === 0 || code === 1) {
4191
+ looked = true;
4192
+ let current = 0;
4193
+ for (const line of stdout.split("\n")) {
4194
+ if (line.startsWith("p")) {
4195
+ current = Number(line.slice(1));
4196
+ continue;
4197
+ }
4198
+ if (!line.startsWith("n") || line.length <= 1 || !needLsof.includes(current))
4199
+ continue;
4200
+ const cwd = line.slice(1).trim();
4201
+ if (cwd) cwdByPid.set(current, cwd);
4202
+ }
4203
+ }
4204
+ } catch {
4205
+ }
4206
+ if (looked) {
4207
+ for (const pid of needLsof) {
4208
+ if (!cwdByPid.has(pid)) cwdByPid.set(pid, null);
4209
+ }
4210
+ }
4211
+ }
4212
+ for (const waiter of batch) waiter.resolve(cwdByPid.get(waiter.pid) ?? null);
4213
+ }
4214
+ }
4215
+ function resolveProcessCwd(pid) {
4216
+ if (pid <= 0) return Promise.resolve(null);
4217
+ if (cwdByPid.has(pid)) return Promise.resolve(cwdByPid.get(pid) ?? null);
4218
+ return new Promise((resolveCwd) => {
4219
+ cwdQueue.push({ pid, resolve: resolveCwd });
4220
+ kickCwdFlush();
4221
+ });
4222
+ }
4223
+
4224
+ // src/metro-project-root.ts
4225
+ async function resolveMetroProjectRoot(bundleUrl) {
4226
+ const origin = loopbackOriginOf(bundleUrl);
4227
+ if (!origin) return null;
4228
+ const controller = new AbortController();
4229
+ const timer = setTimeout(() => controller.abort(), MANIFEST_PROBE_TIMEOUT_MS);
4230
+ let servedManifest = false;
4231
+ let metroRunning = false;
4232
+ try {
4233
+ const status = await fetch(`${origin}/status`, { signal: controller.signal });
4234
+ const advertisedRoot = status.headers.get("X-React-Native-Project-Root");
4235
+ if (status.ok && advertisedRoot) return decodeURI(advertisedRoot);
4236
+ metroRunning = status.ok && (await status.text()).trim() === "packager-status:running";
4237
+ const res = await fetch(`${origin}/`, {
4238
+ headers: { "expo-platform": "ios", Accept: "application/json" },
4239
+ signal: controller.signal
4240
+ });
4241
+ if (res.ok) {
4242
+ const manifest = parseExpoManifestBody(await res.text());
4243
+ servedManifest = true;
4244
+ let root = manifest;
4245
+ for (const key of ["extra", "expoClient", "_internal", "projectRoot"]) {
4246
+ root = typeof root === "object" && root !== null ? Reflect.get(root, key) : void 0;
4247
+ }
4248
+ if (typeof root === "string" && root.length > 0) return root;
4249
+ }
4250
+ } catch {
4251
+ if (controller.signal.aborted)
4252
+ throw new Error(
4253
+ `Metro project root request timed out after ${MANIFEST_PROBE_TIMEOUT_MS / 1e3}s: ${origin}. Wait for the dev server to finish starting or pass --project-root.`
4254
+ );
4255
+ } finally {
4256
+ clearTimeout(timer);
4257
+ }
4258
+ if (servedManifest || !metroRunning) return null;
4259
+ const port = Number(new URL(origin).port);
4260
+ if (!Number.isFinite(port) || port <= 0) return null;
4261
+ const pid = await resolveListeningPid(port);
4262
+ return pid === null ? null : resolveProcessCwd(pid);
4263
+ }
4264
+
4265
+ // src/host/dev-server-package-versions.ts
4266
+ async function readDevServerPackageVersions(bundleUrl) {
4267
+ if (!bundleUrl.pathname.endsWith(".bundle")) return null;
4268
+ const projectRoot = await resolveMetroProjectRoot(bundleUrl.href);
4269
+ if (!projectRoot) return null;
4270
+ try {
4271
+ await import_fs3.default.promises.access(import_path3.default.join(projectRoot, "package.json"));
4272
+ } catch {
4273
+ return null;
4274
+ }
4275
+ return readInstalledNativePackageVersionsAsync(projectRoot);
4276
+ }
4277
+
4278
+ // src/host/fetch-proxy-overrides.ts
4279
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4280
+ var FETCH_PROXY_NATIVE_USER_AGENT_HEADER = "x-sootsim-native-user-agent";
4281
+ var FETCH_PROXY_FAILURE_PARAM = "peachFailure";
4282
+ var FETCH_PROXY_FAILURE_HEADER = "x-peach-upstream-failure";
4283
+ var FETCH_PROXY_RESPONSE_URL_HEADER = "x-peach-response-url";
4284
+ var FETCH_PROXY_NATIVE_COOKIE_HEADER = "x-peach-native-cookie";
4285
+ var FETCH_PROXY_NATIVE_COOKIE_RESPONSE_HEADER = "x-peach-native-cookie-response";
4286
+ function nativeCookieHopHeader(hop) {
4287
+ return encodeURIComponent(JSON.stringify(hop));
4288
+ }
4289
+ function isNativeCookieRedirect(hop) {
4290
+ return hop.location !== null && [301, 302, 303, 307, 308].includes(hop.status);
4291
+ }
4292
+ function resolveRedirectUrl(location, from) {
4293
+ const next = new URL(location, from);
4294
+ if (!location.includes("#")) next.hash = from.hash;
4295
+ return next;
4296
+ }
4297
+ var HOST_HEADER_OVERRIDES = [
4298
+ {
4299
+ hostSuffix: "uniswap.org",
4300
+ headers: {
4301
+ origin: "https://app.uniswap.org",
4302
+ referer: "https://app.uniswap.org/"
4303
+ }
4304
+ }
4305
+ ];
4306
+ function headerOverridesFor(hostname) {
4307
+ const host = hostname.toLowerCase();
4308
+ for (const override of HOST_HEADER_OVERRIDES) {
4309
+ if (host === override.hostSuffix || host.endsWith(`.${override.hostSuffix}`)) {
4310
+ return override;
4311
+ }
4312
+ }
4313
+ return void 0;
4314
+ }
4315
+ var PUBLIC_RPC_TENANT = "rnx-public-rpc";
4316
+ var QUICKNODE_HOST_SUFFIX = ".quiknode.pro";
4317
+ var PUBLIC_RPC_BY_QUICKNODE_CHAIN = {
4318
+ "": "https://ethereum-rpc.publicnode.com",
4319
+ "arbitrum-mainnet": "https://arbitrum-one-rpc.publicnode.com",
4320
+ "avalanche-mainnet": "https://avalanche-c-chain-rpc.publicnode.com",
4321
+ "base-mainnet": "https://base-rpc.publicnode.com",
4322
+ "blast-mainnet": "https://blast-rpc.publicnode.com",
4323
+ bsc: "https://bsc-rpc.publicnode.com",
4324
+ "celo-mainnet": "https://celo-rpc.publicnode.com",
4325
+ matic: "https://polygon-bor-rpc.publicnode.com",
4326
+ optimism: "https://optimism-rpc.publicnode.com",
4327
+ "soneium-mainnet": "https://soneium-rpc.publicnode.com",
4328
+ "unichain-mainnet": "https://unichain-rpc.publicnode.com"
4329
+ };
4330
+ function resolveFetchProxyTargetUrl(requested) {
4331
+ const host = requested.hostname.toLowerCase();
4332
+ if (!host.endsWith(QUICKNODE_HOST_SUFFIX)) return requested;
4333
+ const tenant = host.slice(0, -QUICKNODE_HOST_SUFFIX.length);
4334
+ if (tenant !== PUBLIC_RPC_TENANT && !tenant.startsWith(`${PUBLIC_RPC_TENANT}.`)) {
4335
+ return requested;
4336
+ }
4337
+ const chain = tenant === PUBLIC_RPC_TENANT ? "" : tenant.slice(PUBLIC_RPC_TENANT.length + 1);
4338
+ const replacement = PUBLIC_RPC_BY_QUICKNODE_CHAIN[chain];
4339
+ return replacement ? new URL(replacement) : requested;
4340
+ }
4341
+ var STRIP_FETCH_PROXY_REQUEST_HEADERS = /* @__PURE__ */ new Set([
4342
+ "host",
4343
+ "x-forwarded",
4344
+ "x-real-ip",
4345
+ "forwarded",
4346
+ "origin",
4347
+ "referer",
4348
+ "user-agent",
4349
+ "accept-encoding",
4350
+ "cookie",
4351
+ "connection",
4352
+ "keep-alive",
4353
+ "transfer-encoding",
4354
+ "upgrade",
4355
+ "content-length",
4356
+ "sec-fetch-site",
4357
+ "sec-fetch-mode",
4358
+ "sec-fetch-dest",
4359
+ "sec-ch-ua",
4360
+ "sec-ch-ua-mobile",
4361
+ "sec-ch-ua-platform",
4362
+ FETCH_PROXY_NATIVE_USER_AGENT_HEADER,
4363
+ FETCH_PROXY_NATIVE_COOKIE_HEADER,
4364
+ FETCH_PROXY_NATIVE_COOKIE_RESPONSE_HEADER
4365
+ ]);
4366
+ function buildFetchProxyUpstreamHeaders(requestHeaders, targetUrl) {
4367
+ const headers = {};
4368
+ let nativeUserAgent;
4369
+ let nativeCookie;
4370
+ for (const [rawKey, value] of requestHeaders) {
4371
+ const key = rawKey.toLowerCase();
4372
+ if (key === FETCH_PROXY_NATIVE_USER_AGENT_HEADER) nativeUserAgent = value;
4373
+ if (key === FETCH_PROXY_NATIVE_COOKIE_HEADER) nativeCookie = decodeURIComponent(value);
4374
+ if (key.startsWith(":") || STRIP_FETCH_PROXY_REQUEST_HEADERS.has(key) || key.startsWith("x-forwarded-")) {
4375
+ continue;
4376
+ }
4377
+ headers[key] = value;
4378
+ }
4379
+ if (!targetUrl) return headers;
4380
+ return {
4381
+ ...headers,
4382
+ "accept-encoding": "identity",
4383
+ ...nativeUserAgent ? { "user-agent": nativeUserAgent } : {},
4384
+ ...nativeCookie ? { cookie: nativeCookie } : {},
4385
+ ...headerOverridesFor(targetUrl.hostname)?.headers
4386
+ };
4387
+ }
4388
+ function nodeRequestHeaderEntries(headers) {
4389
+ const entries = [];
4390
+ for (const [key, value] of Object.entries(headers)) {
4391
+ if (!value) continue;
4392
+ entries.push([key, Array.isArray(value) ? value.join(", ") : value]);
4393
+ }
4394
+ return entries;
4395
+ }
4396
+
4397
+ // src/host/loopback-ports.ts
4398
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4399
+ var LOOPBACK_PORTS = /* @__PURE__ */ new Map();
4400
+ for (const pair of process.env.PEACH_LOOPBACK_PORTS?.split(",").filter(Boolean) ?? []) {
4401
+ const match = /^\s*([1-9][0-9]{0,4}):([1-9][0-9]{0,4})\s*$/.exec(pair);
4402
+ const from = Number(match?.[1]);
4403
+ const to = Number(match?.[2]);
4404
+ if (!match || from > 65535 || to > 65535 || LOOPBACK_PORTS.has(from)) {
4405
+ throw new Error(`PEACH_LOOPBACK_PORTS has an invalid entry: ${JSON.stringify(pair)}`);
4406
+ }
4407
+ LOOPBACK_PORTS.set(from, to);
4408
+ }
4409
+ function projectLoopbackPort(hostname, port) {
4410
+ return isLoopbackHost(hostname) ? LOOPBACK_PORTS.get(port) ?? port : port;
4411
+ }
4412
+
4413
+ // src/host/rolldown-bundle-forward.ts
4414
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4415
+ var import_stream = require("stream");
4416
+ var import_promises2 = require("stream/promises");
4417
+ init_cli_runtime();
4418
+ var ROLLDOWN_INVENTORY_HEADER = "x-peach-rolldown-inventory";
4419
+ async function forwardRolldownBundleResponse(upstream, res) {
4420
+ res.setHeader(ROLLDOWN_INVENTORY_HEADER, "1");
4421
+ if (upstream.headers[ROLLDOWN_INVENTORY_HEADER] === "1") {
4422
+ await (0, import_promises2.pipeline)(upstream, res);
4423
+ return;
4424
+ }
4425
+ const contentType = typeof upstream.headers["content-type"] === "string" ? upstream.headers["content-type"] : "";
4426
+ const inventory = getCliRuntime().rolldown_bundle_inventory;
4427
+ res.removeHeader("content-length");
4428
+ const annotate = async function* () {
4429
+ const decoder = new TextDecoder();
4430
+ let payload = "";
4431
+ let sent = 0;
4432
+ let bundleStarted = false;
4433
+ for await (const chunk of upstream) {
4434
+ payload += decoder.decode(chunk, { stream: true });
4435
+ if (bundleStarted) continue;
4436
+ const releasable = inventory.releasableMultipartPrefix(payload, contentType);
4437
+ bundleStarted = releasable.bundleStarted;
4438
+ if (releasable.length > sent) {
4439
+ yield Buffer.from(payload.slice(sent, releasable.length), "utf8");
4440
+ sent = releasable.length;
4441
+ }
4442
+ }
4443
+ payload += decoder.decode();
4444
+ let annotated;
4445
+ try {
4446
+ annotated = await inventory.attachRolldownBundleHttpPayload(payload, contentType);
4447
+ } catch (error) {
4448
+ const message = `could not attach the rolldown bundle inventory: ${error instanceof Error ? error.message : String(error)}`;
4449
+ console.error(`[peach] ${message}`);
4450
+ if (contentType.toLowerCase().includes("multipart/mixed")) {
4451
+ yield Buffer.from(
4452
+ inventory.multipartFailurePart(contentType, message, payload.slice(0, sent)),
4453
+ "utf8"
4454
+ );
4455
+ return;
4456
+ }
4457
+ res.statusCode = 500;
4458
+ res.setHeader("content-type", "application/json");
4459
+ yield Buffer.from(JSON.stringify({ message }), "utf8");
4460
+ return;
4461
+ }
4462
+ yield Buffer.from(annotated.slice(sent), "utf8");
4463
+ };
4464
+ await (0, import_promises2.pipeline)(import_stream.Readable.from(annotate(), { objectMode: false }), res);
4465
+ }
4466
+
4467
+ // src/host/fetch-proxy-handler.ts
4468
+ var fetchProxyHttpAgent = new import_http.default.Agent({ keepAlive: true, maxSockets: 256 });
4469
+ var fetchProxyHttpsAgent = new import_https.default.Agent({ keepAlive: true, maxSockets: 256 });
4470
+ function fetchProxyAgentFor(targetUrl) {
4471
+ return targetUrl.protocol === "https:" ? fetchProxyHttpsAgent : fetchProxyHttpAgent;
4472
+ }
4473
+ var FETCH_PROXY_CORS_HEADERS = {
4474
+ "access-control-allow-methods": "GET,HEAD,POST,PUT,DELETE,PATCH,OPTIONS",
4475
+ "access-control-max-age": "3600"
4476
+ };
4477
+ var APP_API_HEADER_REWRITES = /* @__PURE__ */ new Set([
4478
+ "host",
4479
+ "origin",
4480
+ "referer",
4481
+ "sec-fetch-site",
4482
+ "sec-fetch-mode",
4483
+ "sec-fetch-dest"
4484
+ ]);
4485
+ function loopbackTlsOptions(targetUrl) {
4486
+ if (targetUrl.protocol !== "https:") return {};
4487
+ return isLoopbackHost(targetUrl.hostname) ? { rejectUnauthorized: false } : {};
4488
+ }
4489
+ function applyFetchProxyCors(req, res) {
4490
+ for (const [key, value] of Object.entries(FETCH_PROXY_CORS_HEADERS)) {
4491
+ res.setHeader(key, value);
4492
+ }
4493
+ res.setHeader("access-control-allow-origin", req.headers.origin ?? "*");
4494
+ res.setHeader("access-control-allow-credentials", "true");
4495
+ res.setHeader(
4496
+ "access-control-allow-headers",
4497
+ req.headers["access-control-request-headers"] ?? "*"
4498
+ );
4499
+ res.setHeader(
4500
+ "access-control-expose-headers",
4501
+ [
4502
+ ...Object.keys(res.getHeaders()).filter(
4503
+ (name) => !name.startsWith("access-control-")
4504
+ ),
4505
+ "x-sootsim-set-cookie"
4506
+ ].join(", ")
4507
+ );
4508
+ const vary = res.getHeader("vary");
4509
+ res.setHeader(
4510
+ "vary",
4511
+ vary ? `${Array.isArray(vary) ? vary.join(", ") : vary}, Origin` : "Origin"
4512
+ );
4513
+ }
4514
+ function buildFetchProxyHeaders(reqHeaders, targetUrl) {
4515
+ return buildFetchProxyUpstreamHeaders(nodeRequestHeaderEntries(reqHeaders), targetUrl);
4516
+ }
4517
+ function buildAppApiProxyHeaders(reqHeaders, targetUrl) {
4518
+ const headers = {};
4519
+ for (const [key, value] of Object.entries(reqHeaders)) {
4520
+ if (!value) continue;
4521
+ if (key.toLowerCase() === FETCH_PROXY_NATIVE_COOKIE_HEADER || key.toLowerCase() === FETCH_PROXY_NATIVE_COOKIE_RESPONSE_HEADER || reqHeaders[FETCH_PROXY_NATIVE_COOKIE_HEADER] !== void 0 && key.toLowerCase() === "cookie" || APP_API_HEADER_REWRITES.has(key.toLowerCase()))
4522
+ continue;
4523
+ headers[key] = value;
4524
+ }
4525
+ const nativeCookie = reqHeaders[FETCH_PROXY_NATIVE_COOKIE_HEADER];
4526
+ if (typeof nativeCookie === "string" && nativeCookie)
4527
+ headers.cookie = decodeURIComponent(nativeCookie);
4528
+ headers.host = targetUrl.host;
4529
+ if (!Object.keys(headers).some((name) => name.toLowerCase() === "mobile-origin")) {
4530
+ headers.origin = targetUrl.origin;
4531
+ headers.referer = `${targetUrl.origin}/`;
4532
+ }
4533
+ return headers;
4534
+ }
4535
+ function rejectUntrustedBridgeOrigin(req, res) {
4536
+ if (isTrustedBridgeRequest(req.headers)) return false;
4537
+ res.statusCode = 403;
4538
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
4539
+ res.end(`peach bridge: origin ${req.headers.origin} may not use this bridge`);
4540
+ return true;
4541
+ }
4542
+ function isFetchProxyRequestUrl(rawUrl) {
4543
+ return rawUrl?.startsWith("/__fetch-proxy?") || rawUrl?.startsWith("/__proxy?") || false;
4544
+ }
4545
+ function isBundleProxyRequestUrl(rawUrl) {
4546
+ return rawUrl?.startsWith("/__bundle-proxy?") ?? false;
4547
+ }
4548
+ function isAppApiRequestUrl(rawUrl) {
4549
+ if (!rawUrl) return false;
4550
+ if (rawUrl.startsWith("/__app-api?")) return true;
4551
+ if (rawUrl.startsWith("/__app-api/")) return true;
4552
+ return false;
4553
+ }
4554
+ async function handleFetchProxyRequest(req, res) {
4555
+ if (req.method === "OPTIONS") {
4556
+ applyFetchProxyCors(req, res);
4557
+ res.statusCode = 204;
4558
+ res.end();
4559
+ return;
4560
+ }
4561
+ const params = new URLSearchParams((req.url || "").split("?")[1] || "");
4562
+ const targetUrl = params.get("url");
4563
+ if (!targetUrl) {
4564
+ applyFetchProxyCors(req, res);
4565
+ res.statusCode = 400;
4566
+ res.setHeader("Content-Type", "text/plain");
4567
+ res.end("missing url param");
4568
+ return;
4569
+ }
4570
+ let upstreamUrl;
4571
+ try {
4572
+ upstreamUrl = resolveFetchProxyTargetUrl(new URL(targetUrl));
4573
+ } catch {
4574
+ applyFetchProxyCors(req, res);
4575
+ res.statusCode = 400;
4576
+ res.setHeader("Content-Type", "text/plain");
4577
+ res.end("invalid url param");
4578
+ return;
4579
+ }
4580
+ const packageVersionsRead = isBundleProxyRequestUrl(req.url) && req.method === "GET" ? readDevServerPackageVersions(upstreamUrl) : null;
4581
+ packageVersionsRead?.catch(() => {
4582
+ });
4583
+ await proxyUpstream(req, res, upstreamUrl, params.has(FETCH_PROXY_FAILURE_PARAM), {
4584
+ requestHeaders: (target) => buildFetchProxyHeaders(req.headers, target),
4585
+ respond: async (upstream, setCookies) => {
4586
+ for (const [key, value] of Object.entries(upstream.headers)) {
4587
+ const lowerKey = key.toLowerCase();
4588
+ if (value === void 0 || lowerKey === "set-cookie" || lowerKey === "connection" || lowerKey === "keep-alive" || lowerKey === "proxy-authenticate" || lowerKey === "proxy-authorization" || lowerKey === "te" || lowerKey === "trailer" || lowerKey === "transfer-encoding" || lowerKey === "upgrade" || lowerKey === FETCH_PROXY_NATIVE_COOKIE_RESPONSE_HEADER || lowerKey === FETCH_PROXY_RESPONSE_URL_HEADER || lowerKey.startsWith("access-control-")) {
4589
+ continue;
4590
+ }
4591
+ res.setHeader(key, value);
4592
+ }
4593
+ if (packageVersionsRead && upstream.statusCode === 200 && !res.hasHeader(PACKAGE_VERSIONS_HEADER)) {
4594
+ const packageVersions = await packageVersionsRead;
4595
+ if (packageVersions)
4596
+ res.setHeader(PACKAGE_VERSIONS_HEADER, JSON.stringify(packageVersions));
4597
+ }
4598
+ applyFetchProxyCors(req, res);
4599
+ if (setCookies.length > 0)
4600
+ res.setHeader("x-sootsim-set-cookie", setCookies.join(", "));
4601
+ }
4602
+ });
4603
+ }
4604
+ function handleAppApiRequest(req, res) {
4605
+ const reqUrl = req.url || "";
4606
+ let targetPath = "";
4607
+ let targetOrigin = "";
4608
+ let reportFailure = false;
4609
+ if (reqUrl.startsWith("/__app-api?")) {
4610
+ const parsed = new URL(reqUrl, "http://sootsim.local");
4611
+ targetPath = parsed.searchParams.get("path") || "";
4612
+ targetOrigin = parsed.searchParams.get("origin")?.trim() || "";
4613
+ reportFailure = parsed.searchParams.has(FETCH_PROXY_FAILURE_PARAM);
4614
+ } else if (reqUrl.startsWith("/__app-api/")) {
4615
+ targetPath = reqUrl.slice("/__app-api".length);
4616
+ } else {
4617
+ return false;
4618
+ }
4619
+ if (!targetOrigin) {
4620
+ res.writeHead(400, { "Content-Type": "text/plain" });
4621
+ res.end("app-api: missing origin query param");
4622
+ return true;
4623
+ }
4624
+ if (req.method === "OPTIONS") {
4625
+ res.writeHead(204, {
4626
+ "Access-Control-Allow-Origin": req.headers.origin || "*",
4627
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
4628
+ "Access-Control-Allow-Headers": req.headers["access-control-request-headers"] || "*",
4629
+ "Access-Control-Allow-Credentials": "true",
4630
+ "Access-Control-Max-Age": "86400"
4631
+ });
4632
+ res.end();
4633
+ return true;
4634
+ }
4635
+ let targetUrl;
4636
+ try {
4637
+ targetUrl = new URL(targetPath, targetOrigin);
4638
+ } catch {
4639
+ res.writeHead(400, { "Content-Type": "text/plain" });
4640
+ res.end("app-api: invalid origin or path");
4641
+ return true;
4642
+ }
4643
+ void proxyUpstream(req, res, targetUrl, reportFailure, {
4644
+ requestHeaders: (target) => buildAppApiProxyHeaders(req.headers, target),
4645
+ respond: (upstream, setCookies) => {
4646
+ for (const [key, value] of Object.entries(upstream.headers)) {
4647
+ const lowerKey = key.toLowerCase();
4648
+ if (value === void 0 || lowerKey === "set-cookie" || lowerKey === FETCH_PROXY_NATIVE_COOKIE_RESPONSE_HEADER || lowerKey === FETCH_PROXY_RESPONSE_URL_HEADER) {
4649
+ continue;
4650
+ }
4651
+ res.setHeader(key, value);
4652
+ }
4653
+ if (setCookies.length > 0 && req.headers[FETCH_PROXY_NATIVE_COOKIE_HEADER] === void 0)
4654
+ res.setHeader("set-cookie", setCookies);
4655
+ res.setHeader("access-control-allow-origin", req.headers.origin || "*");
4656
+ res.setHeader("access-control-allow-credentials", "true");
4657
+ res.setHeader(
4658
+ "access-control-expose-headers",
4659
+ Object.keys(res.getHeaders()).filter((name) => !name.startsWith("access-control-") && name !== "set-cookie").join(", ")
4660
+ );
4661
+ }
4662
+ });
4663
+ return true;
4664
+ }
4665
+ function serveBrowserProxyRoute(req, res) {
4666
+ if (isBundleProxyRequestUrl(req.url) || isFetchProxyRequestUrl(req.url)) {
4667
+ if (!rejectUntrustedBridgeOrigin(req, res)) void handleFetchProxyRequest(req, res);
4668
+ return true;
4669
+ }
4670
+ if (isAppApiRequestUrl(req.url)) {
4671
+ if (rejectUntrustedBridgeOrigin(req, res)) return true;
4672
+ return handleAppApiRequest(req, res);
4673
+ }
4674
+ return false;
4675
+ }
4676
+ async function proxyUpstream(req, res, upstreamUrl, reportFailure, route) {
4677
+ const originalMethod = req.method || "GET";
4678
+ const proxy = async (targetUrl, method, nextBody, redirects, setCookies) => {
4679
+ const transport = targetUrl.protocol === "https:" ? import_https.default : import_http.default;
4680
+ const targetHeaders = route.requestHeaders(targetUrl);
4681
+ if (targetUrl.origin !== upstreamUrl.origin) {
4682
+ delete targetHeaders.authorization;
4683
+ delete targetHeaders["proxy-authorization"];
4684
+ }
4685
+ if (method === "GET" || method === "HEAD") {
4686
+ delete targetHeaders["content-length"];
4687
+ delete targetHeaders["content-type"];
4688
+ } else if (nextBody) {
4689
+ delete targetHeaders["transfer-encoding"];
4690
+ targetHeaders["content-length"] = String(nextBody.byteLength);
4691
+ }
4692
+ const port = projectLoopbackPort(
4693
+ targetUrl.hostname,
4694
+ Number(targetUrl.port || (targetUrl.protocol === "https:" ? 443 : 80))
4695
+ );
4696
+ let clientAborted = false;
4697
+ const markAborted = () => {
4698
+ clientAborted = true;
4699
+ };
4700
+ req.once("aborted", markAborted);
4701
+ const send = () => new Promise((resolve3, reject) => {
4702
+ let responded = false;
4703
+ const proxyReq = transport.request(
4704
+ {
4705
+ hostname: normalizeHostname(targetUrl.hostname),
4706
+ port,
4707
+ path: targetUrl.pathname + targetUrl.search,
4708
+ method,
4709
+ headers: targetHeaders,
4710
+ agent: fetchProxyAgentFor(targetUrl),
4711
+ ...loopbackTlsOptions(targetUrl)
4712
+ },
4713
+ (upstream) => {
4714
+ responded = true;
4715
+ resolve3(upstream);
4716
+ }
4717
+ );
4718
+ const abort = () => proxyReq.destroy();
4719
+ req.once("aborted", abort);
4720
+ proxyReq.once("close", () => req.off("aborted", abort));
4721
+ let failed = false;
4722
+ proxyReq.on("error", (err) => {
4723
+ if (failed) return;
4724
+ failed = true;
4725
+ if (proxyReq.reusedSocket && !responded && !clientAborted && err.code === "ECONNRESET")
4726
+ resolve3(send());
4727
+ else reject(err);
4728
+ });
4729
+ if (nextBody === void 0) proxyReq.end();
4730
+ else proxyReq.end(nextBody);
4731
+ });
4732
+ const proxyRes = await send().finally(() => req.off("aborted", markAborted));
4733
+ const status = proxyRes.statusCode ?? 502;
4734
+ const location = proxyRes.headers.location;
4735
+ const hopCookies = [...setCookies, ...proxyRes.headers["set-cookie"] ?? []];
4736
+ if (req.headers[FETCH_PROXY_NATIVE_COOKIE_HEADER] !== void 0) {
4737
+ const hop = {
4738
+ url: upstreamUrl.href,
4739
+ status,
4740
+ location: location ?? null,
4741
+ cookies: hopCookies,
4742
+ redirectLimit: 10
4743
+ };
4744
+ res.setHeader(FETCH_PROXY_NATIVE_COOKIE_RESPONSE_HEADER, nativeCookieHopHeader(hop));
4745
+ await route.respond(proxyRes, hopCookies);
4746
+ if (isNativeCookieRedirect(hop)) res.removeHeader("location");
4747
+ res.statusCode = isNativeCookieRedirect(hop) ? 200 : status;
4748
+ await (0, import_promises3.pipeline)(proxyRes, res);
4749
+ return;
4750
+ }
4751
+ if (location && (status === 301 || status === 302 || status === 303 || status === 307 || status === 308)) {
4752
+ if (redirects >= 10) {
4753
+ proxyRes.destroy();
4754
+ throw new Error("too many redirects");
4755
+ }
4756
+ const switchToGet = (status === 301 || status === 302) && method === "POST" || status === 303 && method !== "GET" && method !== "HEAD";
4757
+ const redirectUrl = resolveRedirectUrl(location, targetUrl);
4758
+ proxyRes.resume();
4759
+ await (0, import_promises3.finished)(proxyRes);
4760
+ await proxy(
4761
+ redirectUrl,
4762
+ switchToGet ? "GET" : method,
4763
+ switchToGet ? void 0 : nextBody,
4764
+ redirects + 1,
4765
+ hopCookies
4766
+ );
4767
+ return;
4768
+ }
4769
+ if (redirects > 0) res.setHeader(FETCH_PROXY_RESPONSE_URL_HEADER, targetUrl.href);
4770
+ await route.respond(proxyRes, hopCookies);
4771
+ res.statusCode = status;
4772
+ if (isBundleProxyRequestUrl(req.url) && method === "GET" && status === 200 && targetUrl.pathname.endsWith(".bundle")) {
4773
+ await forwardRolldownBundleResponse(proxyRes, res);
4774
+ return;
4775
+ }
4776
+ await (0, import_promises3.pipeline)(proxyRes, res);
4777
+ };
4778
+ let body;
4779
+ try {
4780
+ if (req.method !== "GET" && req.method !== "HEAD") {
4781
+ const chunks = [];
4782
+ for await (const chunk of req) {
4783
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
4784
+ }
4785
+ if (chunks.length > 0) {
4786
+ body = Buffer.concat(chunks);
4787
+ }
4788
+ }
4789
+ await proxy(upstreamUrl, originalMethod, body, 0, []);
4790
+ } catch (err) {
4791
+ const norm = normalizeHostname(upstreamUrl.hostname);
4792
+ if (!res.headersSent && isLoopbackHost(norm) && err?.code === "ECONNREFUSED") {
4793
+ const altHosts = norm === "::1" ? ["127.0.0.1"] : norm === "127.0.0.1" ? ["[::1]"] : ["[::1]", "127.0.0.1"];
4794
+ for (const altHost of altHosts) {
4795
+ try {
4796
+ const altUrl = new URL(upstreamUrl.href);
4797
+ altUrl.hostname = altHost;
4798
+ await proxy(altUrl, originalMethod, body, 0, []);
4799
+ return;
4800
+ } catch {
4801
+ }
4802
+ }
4803
+ }
4804
+ if (!res.headersSent && reportFailure) {
4805
+ const code = err?.code;
4806
+ res.statusCode = 502;
4807
+ res.setHeader(
4808
+ FETCH_PROXY_FAILURE_HEADER,
4809
+ typeof code === "string" ? code : "unknown"
4810
+ );
4811
+ applyFetchProxyCors(req, res);
4812
+ res.end();
4813
+ return;
4814
+ }
4815
+ if (req instanceof import_node_http2.Http2ServerRequest)
4816
+ req.stream.destroy(new Error("fetch proxy upstream failed", { cause: err }));
4817
+ else req.socket.destroy();
4818
+ }
4819
+ }
4820
+
4821
+ // src/host/replacement-module-handler.ts
4822
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4823
+ var import_node_fs5 = require("node:fs");
4824
+ var import_promises4 = __toESM(require("node:fs/promises"), 1);
4825
+ var import_node_path5 = __toESM(require("node:path"), 1);
4826
+
4827
+ // ../contrast-bundler/src/replacementModule.ts
4828
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4829
+ var import_dist = require("sucrase/dist/index.js");
4830
+ var import_parser = require("sucrase/dist/parser/index.js");
4831
+ var import_types = require("sucrase/dist/parser/tokenizer/types.js");
4832
+
4833
+ // ../contrast-bundler/src/posixPath.ts
4834
+ init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4835
+ var sep = "/";
4836
+ var delimiter = ":";
4837
+ function isAbsolute(p) {
4838
+ return p.charCodeAt(0) === 47;
4839
+ }
4840
+ function normalizeSegments(parts, allowAboveRoot) {
4841
+ const out = [];
4842
+ for (const part of parts) {
4843
+ if (part === "" || part === ".") continue;
4844
+ if (part === "..") {
4845
+ if (out.length > 0 && out[out.length - 1] !== "..") out.pop();
4846
+ else if (allowAboveRoot) out.push("..");
4847
+ continue;
4848
+ }
4849
+ out.push(part);
4850
+ }
4851
+ return out;
4852
+ }
4853
+ function normalize(p) {
4854
+ if (p.length === 0) return ".";
4855
+ const absolute = isAbsolute(p);
4856
+ const trailingSlash = p.charCodeAt(p.length - 1) === 47;
4857
+ const segments = normalizeSegments(p.split("/"), !absolute);
4858
+ let joined = segments.join("/");
4859
+ if (joined.length === 0) {
4860
+ if (absolute) return "/";
4861
+ return trailingSlash ? "./" : ".";
4862
+ }
4863
+ if (trailingSlash) joined += "/";
4864
+ return absolute ? "/" + joined : joined;
4865
+ }
4866
+ function join3(...parts) {
4867
+ const present = parts.filter((part) => part.length > 0);
4868
+ if (present.length === 0) return ".";
4869
+ return normalize(present.join("/"));
4870
+ }
4871
+ function resolve2(...parts) {
4872
+ let resolved = "";
4873
+ let absolute = false;
4874
+ for (let i = parts.length - 1; i >= 0 && !absolute; i--) {
4875
+ const part = parts[i];
4876
+ if (part.length === 0) continue;
4877
+ resolved = resolved.length > 0 ? `${part}/${resolved}` : part;
4878
+ absolute = isAbsolute(part);
4879
+ }
4880
+ if (!absolute)
4881
+ throw new Error(
4882
+ `posixPath.resolve needs an absolute segment, got: ${parts.join(", ")}`
4883
+ );
4884
+ const normalized = normalizeSegments(resolved.split("/"), false).join("/");
4885
+ return normalized.length > 0 ? "/" + normalized : "/";
4886
+ }
4887
+ function dirname(p) {
4888
+ const idx = p.lastIndexOf("/");
4889
+ if (idx < 0) return ".";
4890
+ if (idx === 0) return "/";
4891
+ return p.slice(0, idx);
4892
+ }
4893
+ function basename(p, ext) {
4894
+ const idx = p.lastIndexOf("/");
4895
+ const base = idx < 0 ? p : p.slice(idx + 1);
4896
+ if (ext != null && ext.length < base.length && base.endsWith(ext)) {
4897
+ return base.slice(0, base.length - ext.length);
4898
+ }
4899
+ return base;
4900
+ }
4901
+ function extname(p) {
4902
+ const base = basename(p);
4903
+ const idx = base.lastIndexOf(".");
4904
+ if (idx <= 0) return "";
4905
+ return base.slice(idx);
4906
+ }
4907
+ function relative(from, to) {
4908
+ if (from === to) return "";
4909
+ const fromParts = normalizeSegments(from.split("/"), false);
4910
+ const toParts = normalizeSegments(to.split("/"), false);
4911
+ let shared = 0;
4912
+ while (shared < fromParts.length && shared < toParts.length && fromParts[shared] === toParts[shared]) {
4913
+ shared++;
4914
+ }
4915
+ const up = new Array(fromParts.length - shared).fill("..");
4916
+ return [...up, ...toParts.slice(shared)].join("/");
4917
+ }
4918
+ var posix = {
4919
+ sep,
4920
+ delimiter,
4921
+ isAbsolute,
4922
+ normalize,
4923
+ join: join3,
4924
+ resolve: resolve2,
4925
+ dirname,
4926
+ basename,
4927
+ extname,
4928
+ relative
4929
+ };
4930
+ var posixPath_default = { ...posix, posix };
4931
+
4932
+ // ../contrast-bundler/src/replacementModule.ts
4933
+ var REPLACEMENT_MODULE_EXTENSIONS = [".js", ".jsx", ".ts", ".tsx"];
4934
+ var IMPORT_KEYWORD = import_types.TokenType["_import"];
4935
+ var EXPORT_KEYWORD = import_types.TokenType["_export"];
4936
+ var REACT_BRIDGE = "globalThis.__sootsim_react_bridge";
4937
+ var REACT_NATIVE_BRIDGE = "globalThis.__sootsim_components__";
4938
+ var PACKAGE_BRIDGES = "globalThis.__sootsim_config_package_modules";
4939
+ var JSX_RUNTIME_SPECIFIERS = /* @__PURE__ */ new Set(["react/jsx-runtime", "react/jsx-dev-runtime"]);
4940
+ function transformsFor(filePath) {
4941
+ switch (extname(filePath).toLowerCase()) {
4942
+ case ".ts":
4943
+ return ["typescript"];
4944
+ case ".tsx":
4945
+ return ["typescript", "jsx"];
4946
+ case ".js":
4947
+ case ".jsx":
4948
+ return ["jsx"];
4949
+ default:
4950
+ throw new Error(
4951
+ `replacement files must be ${REPLACEMENT_MODULE_EXTENSIONS.join(", ")}`
4952
+ );
4953
+ }
4954
+ }
4955
+ function isLocalSpecifier(specifier) {
4956
+ return specifier.startsWith("./") || specifier.startsWith("../");
4957
+ }
4958
+ function isPeachKitSpecifier(specifier) {
4959
+ return specifier === "peach-kit" || specifier.startsWith("peach-kit/");
4960
+ }
4961
+ function unsupportedSpecifier(specifier) {
4962
+ return new Error(
4963
+ `replacement modules may only import react, react-native, peach-kit, the packages rnx stubs for this app, and other project files by relative path; '${specifier}' is none of those. vendor the code into a project file, or add the package to peach.config so the simulator bridges it.`
4964
+ );
4965
+ }
4966
+ function bridgeDeclaration(name, specifier) {
4967
+ const notReady = (what) => JSON.stringify(`[peach] replacement ${what} bridge is not ready`);
4968
+ if (specifier === "react") {
4969
+ return `const ${name} = ${REACT_BRIDGE}; if (!${name}) throw new Error(${notReady("React")});`;
4970
+ }
4971
+ if (specifier === "react-native") {
4972
+ return `const ${name} = ${REACT_NATIVE_BRIDGE}; if (!${name}) throw new Error(${notReady("React Native")});`;
4973
+ }
4974
+ if (isPeachKitSpecifier(specifier)) {
4975
+ return `const ${name} = (globalThis.__peach_kit_modules && globalThis.__peach_kit_modules[${JSON.stringify(specifier)}]) || (${PACKAGE_BRIDGES} || {})[${JSON.stringify(specifier)}]; if (!${name}) throw new Error(${JSON.stringify(`[peach] replacement package bridge ${specifier} is not ready`)});`;
4976
+ }
4977
+ if (JSX_RUNTIME_SPECIFIERS.has(specifier)) {
4978
+ return `const ${name} = (() => { const react = ${REACT_BRIDGE}; if (!react) throw new Error(${notReady("React")}); const jsx = (type, props, key) => react.createElement(type, key === undefined ? props : { ...props, key }); return { Fragment: react.Fragment, jsx, jsxs: jsx, jsxDEV: jsx }; })();`;
4979
+ }
4980
+ return `const ${name} = (${PACKAGE_BRIDGES} || {})[${JSON.stringify(specifier)}]; if (!${name}) throw new Error(${JSON.stringify(`[peach] replacement package bridge ${specifier} is not ready`)});`;
4981
+ }
4982
+ var DEFAULT_INTEROP = "__rnxReplacementDefault";
4983
+ var DEFAULT_INTEROP_DECLARATION = `const ${DEFAULT_INTEROP} = (bridge) => (bridge && bridge.__esModule ? bridge.default : bridge);`;
4984
+ function compileReplacementModule(input) {
4985
+ const transformed = (0, import_dist.transform)(input.source, {
4986
+ transforms: transformsFor(input.filePath),
4987
+ filePath: input.filePath,
4988
+ // the automatic runtime, as @react-native/babel-preset and babel-preset-expo
4989
+ // compile the app's own files: jsx needs no React import.
4990
+ jsxRuntime: "automatic",
4991
+ production: true,
4992
+ sourceMapOptions: { compiledFilename: input.filePath }
4993
+ });
4994
+ const code = transformed.code;
4995
+ const sourceMap = transformed.sourceMap;
4996
+ if (!sourceMap) throw new Error("sucrase compiled the replacement with no source map");
4997
+ const { tokens } = (0, import_parser.parse)(code, false, false, false);
4998
+ const read = (token) => code.slice(token.start, token.end);
4999
+ const readSpecifier = (token) => {
5000
+ if (token.type !== import_types.TokenType.string) {
5001
+ throw new Error("replacement module import has no string specifier");
5002
+ }
5003
+ return code.slice(token.start + 1, token.end - 1);
5004
+ };
5005
+ const bridgeNames = /* @__PURE__ */ new Map();
5006
+ const bareSpecifiers = /* @__PURE__ */ new Set();
5007
+ const declarations = [];
5008
+ let needsDefaultInterop = false;
5009
+ const bridgeFor = (specifier) => {
5010
+ const existing = bridgeNames.get(specifier);
5011
+ if (existing) return existing;
5012
+ const name = `__rnxReplacementBridge${bridgeNames.size}`;
5013
+ bridgeNames.set(specifier, name);
5014
+ declarations.push(bridgeDeclaration(name, specifier));
5015
+ return name;
5016
+ };
5017
+ const edits = [];
5018
+ const pointAtLocalModule = (specifierToken, specifier) => {
5019
+ edits.push({
5020
+ start: specifierToken.start,
5021
+ end: specifierToken.end,
5022
+ text: JSON.stringify(input.localModuleUrl(specifier))
5023
+ });
5024
+ };
5025
+ for (let index = 0; index < tokens.length; index++) {
5026
+ const token = tokens[index];
5027
+ if (token.type === EXPORT_KEYWORD) {
5028
+ const after2 = tokens[index + 1];
5029
+ let fromAt = -1;
5030
+ if (after2?.type === import_types.TokenType.star) {
5031
+ fromAt = read(tokens[index + 2]) === "from" ? index + 2 : index + 4;
5032
+ } else if (after2?.type === import_types.TokenType.braceL) {
5033
+ let depth = 1;
5034
+ let cursor2 = index + 2;
5035
+ while (cursor2 < tokens.length && depth > 0) {
5036
+ if (tokens[cursor2].type === import_types.TokenType.braceL) depth++;
5037
+ else if (tokens[cursor2].type === import_types.TokenType.braceR) depth--;
5038
+ cursor2++;
5039
+ }
5040
+ fromAt = cursor2;
5041
+ }
5042
+ if (fromAt > 0 && tokens[fromAt] && read(tokens[fromAt]) === "from" && tokens[fromAt + 1]?.type === import_types.TokenType.string) {
5043
+ const specifier2 = readSpecifier(tokens[fromAt + 1]);
5044
+ if (isLocalSpecifier(specifier2)) {
5045
+ pointAtLocalModule(tokens[fromAt + 1], specifier2);
5046
+ continue;
5047
+ }
5048
+ throw new Error(
5049
+ `a replacement module cannot re-export from another module, and this one re-exports from '${specifier2}'. import what you need and export the binding.`
5050
+ );
5051
+ }
5052
+ continue;
5053
+ }
5054
+ if (token.type !== IMPORT_KEYWORD) continue;
5055
+ const after = tokens[index + 1];
5056
+ if (!after || after.type === import_types.TokenType.parenL || after.type === import_types.TokenType.dot) continue;
5057
+ const bindings = [];
5058
+ let cursor = index + 1;
5059
+ if (after.type !== import_types.TokenType.string) {
5060
+ while (cursor < tokens.length) {
5061
+ const clause = tokens[cursor];
5062
+ if (clause.type === import_types.TokenType.name && read(clause) === "from") break;
5063
+ if (clause.type === import_types.TokenType.comma) {
5064
+ cursor++;
5065
+ continue;
5066
+ }
5067
+ if (clause.type === import_types.TokenType.star) {
5068
+ bindings.push({ local: read(tokens[cursor + 2]), imported: null });
5069
+ cursor += 3;
5070
+ continue;
5071
+ }
5072
+ if (clause.type === import_types.TokenType.braceL) {
5073
+ cursor++;
5074
+ while (cursor < tokens.length && tokens[cursor].type !== import_types.TokenType.braceR) {
5075
+ if (tokens[cursor].type === import_types.TokenType.comma) {
5076
+ cursor++;
5077
+ continue;
5078
+ }
5079
+ const nameToken = tokens[cursor];
5080
+ const imported = nameToken.type === import_types.TokenType.string ? readSpecifier(nameToken) : read(nameToken);
5081
+ let local = imported;
5082
+ if (tokens[cursor + 1] && read(tokens[cursor + 1]) === "as") {
5083
+ local = read(tokens[cursor + 2]);
5084
+ cursor += 2;
5085
+ }
5086
+ bindings.push({ local, imported });
5087
+ cursor++;
5088
+ }
5089
+ cursor++;
5090
+ continue;
5091
+ }
5092
+ bindings.push({ local: read(clause), imported: "default" });
5093
+ cursor++;
5094
+ }
5095
+ cursor++;
5096
+ }
5097
+ const specifierToken = tokens[cursor];
5098
+ if (!specifierToken) throw new Error("replacement module import is unterminated");
5099
+ const specifier = readSpecifier(specifierToken);
5100
+ if (isLocalSpecifier(specifier)) {
5101
+ pointAtLocalModule(specifierToken, specifier);
5102
+ continue;
5103
+ }
5104
+ if (specifier !== "react" && specifier !== "react-native" && !JSX_RUNTIME_SPECIFIERS.has(specifier) && !isPeachKitSpecifier(specifier) && !input.runtimePackages.has(specifier)) {
5105
+ throw unsupportedSpecifier(specifier);
5106
+ }
5107
+ bareSpecifiers.add(specifier);
5108
+ const bridge = bindings.length > 0 ? bridgeFor(specifier) : null;
5109
+ const replacement = bindings.map((binding) => {
5110
+ if (binding.imported === null) return `const ${binding.local} = ${bridge};`;
5111
+ if (binding.imported === "default") {
5112
+ needsDefaultInterop = true;
5113
+ return `const ${binding.local} = ${DEFAULT_INTEROP}(${bridge});`;
5114
+ }
5115
+ return `const ${binding.local} = ${bridge}[${JSON.stringify(binding.imported)}];`;
5116
+ }).join(" ");
5117
+ const start = token.start;
5118
+ const end = specifierToken.end;
5119
+ const newlines = code.slice(start, end).split("\n").length - 1;
5120
+ edits.push({ start, end, text: replacement + "\n".repeat(newlines) });
5121
+ }
5122
+ let out = code;
5123
+ for (const edit of edits.reverse()) {
5124
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
5125
+ }
5126
+ if (needsDefaultInterop) declarations.unshift(DEFAULT_INTEROP_DECLARATION);
5127
+ const preamble = declarations.join(" ");
5128
+ return {
5129
+ code: preamble ? `${preamble} ${out}` : out,
5130
+ bareSpecifiers: [...bareSpecifiers],
5131
+ sourceMap: { ...sourceMap, sourcesContent: [input.source] }
5132
+ };
5133
+ }
5134
+
5135
+ // src/host/replacement-module-handler.ts
5136
+ var REPLACEMENT_MODULE_ROUTE = "/__sootsim-replacement-module";
5137
+ function sendJavaScript(req, res, source) {
5138
+ const origin = req.headers.origin;
5139
+ let allowedOrigin;
5140
+ if (origin) {
5141
+ try {
5142
+ if (isLoopbackHost(new URL(origin).hostname)) allowedOrigin = origin;
5143
+ } catch {
5144
+ }
5145
+ }
5146
+ res.writeHead(200, {
5147
+ "Content-Type": "application/javascript; charset=utf-8",
5148
+ "Cache-Control": "no-cache",
5149
+ ...allowedOrigin ? { "Access-Control-Allow-Origin": allowedOrigin, Vary: "Origin" } : {}
5150
+ });
5151
+ res.end(req.method === "HEAD" ? void 0 : source);
5152
+ }
5153
+ function resolveReplacementModuleFile(fromFile, specifier) {
5154
+ const base = import_node_path5.default.resolve(import_node_path5.default.dirname(fromFile), specifier);
5155
+ const candidates = [
5156
+ ...REPLACEMENT_MODULE_EXTENSIONS.some(
5157
+ (ext) => ext === import_node_path5.default.extname(base).toLowerCase()
5158
+ ) ? [base] : [],
5159
+ ...REPLACEMENT_MODULE_EXTENSIONS.map((ext) => base + ext),
5160
+ ...REPLACEMENT_MODULE_EXTENSIONS.map((ext) => import_node_path5.default.join(base, `index${ext}`))
5161
+ ];
5162
+ const found = candidates.find(
5163
+ (candidate) => (0, import_node_fs5.statSync)(candidate, { throwIfNoEntry: false })?.isFile()
5164
+ );
5165
+ if (!found) {
5166
+ throw new Error(
5167
+ `'${specifier}' imported by ${fromFile} matches no ${REPLACEMENT_MODULE_EXTENSIONS.join(", ")} file`
5168
+ );
5169
+ }
5170
+ return found;
5171
+ }
5172
+ function isInsideAny(roots, file) {
5173
+ return roots.some((root) => {
5174
+ const relative2 = import_node_path5.default.relative(root, file);
5175
+ return !relative2.startsWith("..") && !import_node_path5.default.isAbsolute(relative2);
5176
+ });
5177
+ }
5178
+ async function handleReplacementModuleRequest(req, res, options = {}) {
5179
+ const rawUrl = req.url || "";
5180
+ let url;
5181
+ try {
5182
+ url = new URL(rawUrl, "http://peach.local");
5183
+ } catch {
5184
+ return false;
5185
+ }
5186
+ if (url.pathname !== REPLACEMENT_MODULE_ROUTE) return false;
5187
+ if (options.requireLoopbackOrigin) {
5188
+ const origin = req.headers.origin;
5189
+ const remoteAddress = req.socket.remoteAddress?.replace(/^::ffff:/, "");
5190
+ let allowed = Boolean(remoteAddress && isLoopbackHost(remoteAddress));
5191
+ if (allowed && origin) {
5192
+ try {
5193
+ allowed = isLoopbackHost(new URL(origin).hostname);
5194
+ } catch {
5195
+ allowed = false;
5196
+ }
5197
+ }
5198
+ if (!allowed) {
5199
+ res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
5200
+ res.end("replacement modules are available only to loopback origins");
5201
+ return true;
5202
+ }
5203
+ }
5204
+ if (options.requestToken && url.searchParams.get("token") !== options.requestToken) {
5205
+ res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
5206
+ res.end("replacement module request token is invalid");
5207
+ return true;
5208
+ }
5209
+ const targetPath = url.searchParams.get("path");
5210
+ if (!targetPath) {
5211
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
5212
+ res.end("missing path param");
5213
+ return true;
5214
+ }
5215
+ const extension = import_node_path5.default.extname(targetPath).toLowerCase();
5216
+ if (!REPLACEMENT_MODULE_EXTENSIONS.some((allowed) => allowed === extension)) {
5217
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
5218
+ res.end(`replacement files must be ${REPLACEMENT_MODULE_EXTENSIONS.join(", ")}`);
5219
+ return true;
5220
+ }
5221
+ if (!import_node_path5.default.isAbsolute(targetPath)) {
5222
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
5223
+ res.end("replacement file path must be absolute");
5224
+ return true;
5225
+ }
5226
+ const runtimePackages = new Set(url.searchParams.getAll("runtimePackage"));
5227
+ const servedRoots = options.servedRoots?.map((root) => import_node_path5.default.resolve(root));
5228
+ if (servedRoots && !isInsideAny(servedRoots, targetPath)) {
5229
+ res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
5230
+ res.end("replacement file must be inside a folder the bundler serves");
5231
+ return true;
5232
+ }
5233
+ let resolvedTargetPath;
3945
5234
  try {
3946
- return parseManifest(import_fs2.default.readFileSync(step.path, "utf8"));
5235
+ resolvedTargetPath = await import_promises4.default.realpath(targetPath);
3947
5236
  } catch (error) {
3948
- if (isMissing(error)) return null;
3949
- throw error;
3950
- }
3951
- }
3952
- function runSync(walk) {
3953
- for (let step = walk.next(); ; ) {
3954
- if (step.done) return step.value;
3955
- step = walk.next(answerSync(step.value));
5237
+ const message = error instanceof Error ? error.message : String(error);
5238
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
5239
+ res.end(`replacement file not found: ${message}`);
5240
+ return true;
3956
5241
  }
3957
- }
3958
- function createInstalledPackageReader() {
3959
- const hasModules = /* @__PURE__ */ new Map();
3960
- const manifests = /* @__PURE__ */ new Map();
3961
- return function* readInstalledPackage(fromDir, name) {
3962
- for (let dir = fromDir; ; ) {
3963
- if (import_path2.default.basename(dir) !== "node_modules") {
3964
- const modules = import_path2.default.join(dir, "node_modules");
3965
- let present = hasModules.get(dir);
3966
- if (present === void 0) {
3967
- present = yield* exists(modules);
3968
- hasModules.set(dir, present);
3969
- }
3970
- if (present) {
3971
- const root = import_path2.default.join(modules, name);
3972
- let installed = manifests.get(root);
3973
- if (installed === void 0) {
3974
- const manifest = yield* readManifest(import_path2.default.join(root, "package.json"));
3975
- installed = manifest ? { root, manifest } : null;
3976
- manifests.set(root, installed);
3977
- }
3978
- if (installed) return installed;
3979
- }
3980
- }
3981
- const parent = import_path2.default.dirname(dir);
3982
- if (parent === dir) return null;
3983
- dir = parent;
5242
+ if (servedRoots) {
5243
+ const realRoots = (await Promise.all(servedRoots.map((root) => import_promises4.default.realpath(root).catch(() => null)))).filter((root) => root !== null);
5244
+ if (!isInsideAny(realRoots, resolvedTargetPath)) {
5245
+ res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
5246
+ res.end("replacement file must be inside a folder the bundler serves");
5247
+ return true;
3984
5248
  }
3985
- };
3986
- }
3987
- function* installedVersionsWalk(projectRoot, names) {
3988
- const readInstalledPackage = createInstalledPackageReader();
3989
- const versions = {};
3990
- for (const name of [...names].sort()) {
3991
- const installed = yield* readInstalledPackage(projectRoot, name);
3992
- const version = installed && Reflect.get(installed.manifest, "version");
3993
- if (typeof version === "string" && version.length > 0) versions[name] = version;
3994
- }
3995
- return versions;
3996
- }
3997
- function* nativePackageVersionsWalk(projectRoot) {
3998
- const appRoot = yield* realpath(projectRoot);
3999
- const nativeNames = /* @__PURE__ */ new Set();
4000
- for (const specifier of [
4001
- "react-native",
4002
- ...NATIVE_RUNTIME_PACKAGE_NAMES,
4003
- ...LAZY_STUB_PATTERNS,
4004
- ...Object.values(COMPAT_STUBS).map((entry) => entry.specifier)
4005
- ]) {
4006
- const name = extractPackageFromPath(`node_modules/${specifier}`);
4007
- if (name) nativeNames.add(name);
4008
5249
  }
4009
- const manifest = yield* readManifest(import_path2.default.join(appRoot, "package.json"));
4010
- if (!manifest) throw new Error("app package.json must contain an object");
4011
- const readInstalledPackage = createInstalledPackageReader();
4012
- const pending = [{ root: appRoot, manifest }];
4013
- const visited = /* @__PURE__ */ new Set();
4014
- const needed = /* @__PURE__ */ new Set();
4015
- for (let next = pending.pop(); next; next = pending.pop()) {
4016
- const root = yield* realpath(next.root);
4017
- if (visited.has(root)) continue;
4018
- visited.add(root);
4019
- const fields = ["dependencies", "optionalDependencies", "peerDependencies"];
4020
- if (root === appRoot) fields.push("devDependencies");
4021
- const peers = Reflect.get(next.manifest, "peerDependenciesMeta");
4022
- for (const field of fields) {
4023
- const dependencies = Reflect.get(next.manifest, field);
4024
- if (typeof dependencies !== "object" || dependencies === null) continue;
4025
- for (const name of Object.keys(dependencies)) {
4026
- if (field === "peerDependencies" && typeof peers === "object" && peers !== null) {
4027
- const peer = Reflect.get(peers, name);
4028
- if (typeof peer === "object" && peer !== null && Reflect.get(peer, "optional"))
4029
- continue;
4030
- }
4031
- const installed = yield* readInstalledPackage(root, name);
4032
- if (!installed) continue;
4033
- if (nativeNames.has(name)) needed.add(name);
4034
- pending.push(installed);
5250
+ try {
5251
+ const compiled = compileReplacementModule({
5252
+ filePath: resolvedTargetPath,
5253
+ source: await import_promises4.default.readFile(resolvedTargetPath, "utf8"),
5254
+ runtimePackages,
5255
+ // the imported file's url is this request's with only its path changed,
5256
+ // so the token, cache key and runtime packages carry over.
5257
+ localModuleUrl: (specifier) => {
5258
+ const local = new URL(url.href);
5259
+ local.searchParams.set(
5260
+ "path",
5261
+ resolveReplacementModuleFile(targetPath, specifier)
5262
+ );
5263
+ return `${local.pathname}${local.search}`;
4035
5264
  }
4036
- }
5265
+ });
5266
+ const map = Buffer.from(JSON.stringify(compiled.sourceMap), "utf8").toString("base64");
5267
+ sendJavaScript(
5268
+ req,
5269
+ res,
5270
+ compiled.code + "\n//# sourceMappingURL=data:application/json;base64," + map + "\n"
5271
+ );
5272
+ } catch (error) {
5273
+ const message = error instanceof Error ? error.message : String(error);
5274
+ res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
5275
+ res.end(`replacement compile failed: ${message}`);
4037
5276
  }
4038
- return yield* installedVersionsWalk(projectRoot, needed);
4039
- }
4040
- function readInstalledNativePackageVersions(projectRoot) {
4041
- return runSync(nativePackageVersionsWalk(projectRoot));
5277
+ return true;
4042
5278
  }
4043
5279
 
4044
5280
  // src/one-widget-metadata.ts
4045
5281
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4046
5282
  var import_node_child_process2 = require("node:child_process");
4047
5283
  var import_node_crypto3 = require("node:crypto");
4048
- var import_node_fs6 = __toESM(require("node:fs"), 1);
5284
+ var import_node_fs7 = __toESM(require("node:fs"), 1);
4049
5285
  var import_node_module2 = require("node:module");
4050
- var import_node_path6 = __toESM(require("node:path"), 1);
5286
+ var import_node_path7 = __toESM(require("node:path"), 1);
4051
5287
  var import_node_util = require("node:util");
4052
5288
 
4053
5289
  // cli/internal-child.ts
4054
5290
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4055
5291
  var RNX_FORKED_SCRIPT_ENV = "PEACH_RUNS_FORKED_SCRIPTS";
4056
5292
 
4057
- // src/is-record.ts
4058
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4059
- function isRecord(value) {
4060
- return typeof value === "object" && value !== null && !Array.isArray(value);
4061
- }
4062
-
4063
- // src/oneWidgetContract.ts
4064
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4065
-
4066
- // src/native-dev-bundle-url.ts
4067
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4068
-
4069
- // src/oneWidgetContract.ts
4070
- var HOME_WIDGET_FAMILIES = [
4071
- "systemSmall",
4072
- "systemMedium",
4073
- "systemLarge",
4074
- "systemExtraLargePortrait"
4075
- ];
4076
- function isHomeWidgetFamily(value) {
4077
- return HOME_WIDGET_FAMILIES.some((family) => family === value);
4078
- }
4079
-
4080
5293
  // src/swift-source-file.ts
4081
5294
  init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4082
- var import_node_fs5 = __toESM(require("node:fs"), 1);
4083
- var import_node_path5 = __toESM(require("node:path"), 1);
5295
+ var import_node_fs6 = __toESM(require("node:fs"), 1);
5296
+ var import_node_path6 = __toESM(require("node:path"), 1);
4084
5297
  function readPackageFile(root, file, maxBytes) {
4085
- const canonicalRoot = import_node_fs5.default.realpathSync(root);
4086
- const relative2 = import_node_path5.default.relative(canonicalRoot, import_node_fs5.default.realpathSync(file));
4087
- if (relative2 === ".." || relative2.startsWith(`..${import_node_path5.default.sep}`) || import_node_path5.default.isAbsolute(relative2)) {
5298
+ const canonicalRoot = import_node_fs6.default.realpathSync(root);
5299
+ const relative2 = import_node_path6.default.relative(canonicalRoot, import_node_fs6.default.realpathSync(file));
5300
+ if (relative2 === ".." || relative2.startsWith(`..${import_node_path6.default.sep}`) || import_node_path6.default.isAbsolute(relative2)) {
4088
5301
  throw new Error(`swift input escapes the selected package: ${file}`);
4089
5302
  }
4090
- let ancestor = import_node_path5.default.resolve(file);
5303
+ let ancestor = import_node_path6.default.resolve(file);
4091
5304
  while (ancestor !== canonicalRoot) {
4092
- if (import_node_fs5.default.lstatSync(ancestor).isSymbolicLink()) {
5305
+ if (import_node_fs6.default.lstatSync(ancestor).isSymbolicLink()) {
4093
5306
  throw new Error(`swift input is a symlink: ${ancestor}`);
4094
5307
  }
4095
- const parent = import_node_path5.default.dirname(ancestor);
5308
+ const parent = import_node_path6.default.dirname(ancestor);
4096
5309
  if (parent === ancestor)
4097
5310
  throw new Error(`swift input escapes the selected package: ${file}`);
4098
5311
  ancestor = parent;
4099
5312
  }
4100
- const expected = import_node_fs5.default.statSync(file);
4101
- const fd = import_node_fs5.default.openSync(file, import_node_fs5.default.constants.O_RDONLY | import_node_fs5.default.constants.O_NOFOLLOW);
5313
+ const expected = import_node_fs6.default.statSync(file);
5314
+ const fd = import_node_fs6.default.openSync(file, import_node_fs6.default.constants.O_RDONLY | import_node_fs6.default.constants.O_NOFOLLOW);
4102
5315
  try {
4103
- const stat = import_node_fs5.default.fstatSync(fd);
5316
+ const stat = import_node_fs6.default.fstatSync(fd);
4104
5317
  if (stat.dev !== expected.dev || stat.ino !== expected.ino) {
4105
5318
  throw new Error(`swift input changed while opening: ${file}`);
4106
5319
  }
@@ -4110,16 +5323,16 @@ function readPackageFile(root, file, maxBytes) {
4110
5323
  const bytes = Buffer.alloc(stat.size + 1);
4111
5324
  let offset = 0;
4112
5325
  while (offset < bytes.length) {
4113
- const count = import_node_fs5.default.readSync(fd, bytes, offset, bytes.length - offset, null);
5326
+ const count = import_node_fs6.default.readSync(fd, bytes, offset, bytes.length - offset, null);
4114
5327
  if (count === 0) break;
4115
5328
  offset += count;
4116
5329
  }
4117
- if (offset !== stat.size || import_node_fs5.default.fstatSync(fd).size !== stat.size) {
5330
+ if (offset !== stat.size || import_node_fs6.default.fstatSync(fd).size !== stat.size) {
4118
5331
  throw new Error(`swift input changed while reading: ${file}`);
4119
5332
  }
4120
5333
  return bytes.subarray(0, offset);
4121
5334
  } finally {
4122
- import_node_fs5.default.closeSync(fd);
5335
+ import_node_fs6.default.closeSync(fd);
4123
5336
  }
4124
5337
  }
4125
5338
 
@@ -4166,8 +5379,8 @@ fs.writeFileSync(process.argv[2], JSON.stringify({
4166
5379
  function configStamp(files) {
4167
5380
  return JSON.stringify(
4168
5381
  files.map((file) => {
4169
- if (!import_node_fs6.default.existsSync(file)) return [file, null];
4170
- const stat = import_node_fs6.default.statSync(file);
5382
+ if (!import_node_fs7.default.existsSync(file)) return [file, null];
5383
+ const stat = import_node_fs7.default.statSync(file);
4171
5384
  return [file, stat.mtimeMs, stat.ctimeMs, stat.size];
4172
5385
  })
4173
5386
  );
@@ -4178,13 +5391,13 @@ async function readConfig(root) {
4178
5391
  const reading = reads.get(root);
4179
5392
  if (reading) return reading;
4180
5393
  const promise = (async () => {
4181
- (0, import_node_module2.createRequire)(import_node_path6.default.join(root, "package.json")).resolve("one/vite");
4182
- const cache = import_node_path6.default.join(root, "node_modules/.cache/peach-widget-config");
4183
- import_node_fs6.default.mkdirSync(cache, { recursive: true });
4184
- const directory = import_node_fs6.default.mkdtempSync(import_node_path6.default.join(cache, "read-"));
4185
- const script = import_node_path6.default.join(directory, "read.mjs");
4186
- const result = import_node_path6.default.join(directory, "result.json");
4187
- import_node_fs6.default.writeFileSync(script, CONFIG_CHILD);
5394
+ (0, import_node_module2.createRequire)(import_node_path7.default.join(root, "package.json")).resolve("one/vite");
5395
+ const cache = import_node_path7.default.join(root, "node_modules/.cache/peach-widget-config");
5396
+ import_node_fs7.default.mkdirSync(cache, { recursive: true });
5397
+ const directory = import_node_fs7.default.mkdtempSync(import_node_path7.default.join(cache, "read-"));
5398
+ const script = import_node_path7.default.join(directory, "read.mjs");
5399
+ const result = import_node_path7.default.join(directory, "result.json");
5400
+ import_node_fs7.default.writeFileSync(script, CONFIG_CHILD);
4188
5401
  try {
4189
5402
  await run(process.execPath, [script, result], {
4190
5403
  cwd: root,
@@ -4192,7 +5405,7 @@ async function readConfig(root) {
4192
5405
  timeout: 3e4,
4193
5406
  maxBuffer: 1024 * 1024
4194
5407
  });
4195
- const value = JSON.parse(import_node_fs6.default.readFileSync(result, "utf8"));
5408
+ const value = JSON.parse(import_node_fs7.default.readFileSync(result, "utf8"));
4196
5409
  if (!isRecord(value) || !Array.isArray(value.watched) || !value.watched.every((file) => typeof file === "string"))
4197
5410
  throw new Error("One config loader returned invalid dependencies");
4198
5411
  if (!Array.isArray(value.urlSchemes) || !value.urlSchemes.every(
@@ -4215,8 +5428,8 @@ async function readConfig(root) {
4215
5428
  }
4216
5429
  const watched = [
4217
5430
  .../* @__PURE__ */ new Set([
4218
- import_node_path6.default.join(root, "package.json"),
4219
- ...value.watched.map((file) => import_node_path6.default.resolve(root, file))
5431
+ import_node_path7.default.join(root, "package.json"),
5432
+ ...value.watched.map((file) => import_node_path7.default.resolve(root, file))
4220
5433
  ])
4221
5434
  ];
4222
5435
  const loaded2 = {
@@ -4228,7 +5441,7 @@ async function readConfig(root) {
4228
5441
  configs.set(root, loaded2);
4229
5442
  return loaded2;
4230
5443
  } finally {
4231
- import_node_fs6.default.rmSync(directory, { recursive: true, force: true });
5444
+ import_node_fs7.default.rmSync(directory, { recursive: true, force: true });
4232
5445
  }
4233
5446
  })();
4234
5447
  reads.set(root, promise);
@@ -4249,13 +5462,13 @@ function declaredFamilies(source) {
4249
5462
  return home;
4250
5463
  }
4251
5464
  async function readOneWidgetSources(appRoot) {
4252
- const root = import_node_fs6.default.realpathSync(appRoot);
5465
+ const root = import_node_fs7.default.realpathSync(appRoot);
4253
5466
  const config = await readConfig(root);
4254
5467
  if (!config.widget) return null;
4255
5468
  const widget = config.widget;
4256
5469
  const sourceFiles = {
4257
- "OneWidget.swift": import_node_path6.default.join(root, "ios/OneWidgets/OneWidget.swift"),
4258
- "OneWidgetContract.swift": import_node_path6.default.join(
5470
+ "OneWidget.swift": import_node_path7.default.join(root, "ios/OneWidgets/OneWidget.swift"),
5471
+ "OneWidgetContract.swift": import_node_path7.default.join(
4259
5472
  root,
4260
5473
  "ios",
4261
5474
  widget.appName,
@@ -4265,14 +5478,14 @@ async function readOneWidgetSources(appRoot) {
4265
5478
  const files = /* @__PURE__ */ new Map();
4266
5479
  const sources = {};
4267
5480
  for (const [name, file] of Object.entries(sourceFiles)) {
4268
- if (!import_node_fs6.default.existsSync(file))
5481
+ if (!import_node_fs7.default.existsSync(file))
4269
5482
  throw new Error(`missing One widget prebuild source ${file}; run one prebuild`);
4270
5483
  const bytes = readPackageFile(root, file, MAX_SWIFT_COMPILE_SOURCE_BYTES);
4271
5484
  const text = bytes.toString("utf8");
4272
5485
  if (!Buffer.from(text).equals(bytes))
4273
5486
  throw new Error(`One widget prebuild source is not UTF-8: ${file}`);
4274
5487
  files.set(name, text);
4275
- sources[import_node_path6.default.relative(root, file).split(import_node_path6.default.sep).join("/")] = (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex");
5488
+ sources[import_node_path7.default.relative(root, file).split(import_node_path7.default.sep).join("/")] = (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex");
4276
5489
  }
4277
5490
  const contract = files.get("OneWidgetContract.swift") ?? "";
4278
5491
  const source = files.get("OneWidget.swift") ?? "";
@@ -4303,77 +5516,6 @@ async function configuredOneWidget(appRoot, bundleUrl) {
4303
5516
  };
4304
5517
  }
4305
5518
 
4306
- // src/packageVersionsContract.ts
4307
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4308
-
4309
- // src/bundleGlobalFooter.ts
4310
- init_define_SWIFT_COVERAGE_SOURCE_DIGESTS();
4311
- function findBundleFooter(source, prefix) {
4312
- let end = source.length;
4313
- while (end > 0) {
4314
- const newline = source.lastIndexOf("\n", end - 1);
4315
- if (newline < 0) return -1;
4316
- const line = newline + 1;
4317
- if (source.startsWith(prefix, line)) return newline;
4318
- if (!isFooterBlockLine(source, line, end)) return -1;
4319
- end = newline;
4320
- }
4321
- return -1;
4322
- }
4323
- function isFooterBlockLine(source, line, end) {
4324
- return line === end || source.startsWith("globalThis.", line) || source.startsWith("//", line);
4325
- }
4326
- function readFooter(source, prefix, suffix, name) {
4327
- const start = findBundleFooter(source, prefix);
4328
- if (start < 0) return null;
4329
- const end = source.indexOf("\n", start + 1);
4330
- const line = source.slice(start + 1, end < 0 ? void 0 : end);
4331
- if (!line.endsWith(suffix)) throw new Error(`${name} footer is truncated`);
4332
- const value = JSON.parse(
4333
- line.slice(prefix.length, suffix ? -suffix.length : void 0)
4334
- );
4335
- if (value === null) throw new Error(`${name} footer has no metadata`);
4336
- return value;
4337
- }
4338
- function detachFooter(source, prefix, suffix, name) {
4339
- const start = findBundleFooter(source, prefix);
4340
- if (start < 0) return { source, value: null };
4341
- const value = readFooter(source, prefix, suffix, name);
4342
- const end = source.indexOf("\n", start + 1);
4343
- return { source: source.slice(0, start) + (end < 0 ? "" : source.slice(end)), value };
4344
- }
4345
- function insertBundleGlobalFooter(source, name, value) {
4346
- return insertFooter(source, `globalThis.${name}=`, ";", name, value);
4347
- }
4348
- function insertFooter(source, prefix, suffix, name, value) {
4349
- source = detachFooter(source, prefix, suffix, name).source;
4350
- const json = JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/<\//g, "<\\/");
4351
- const footer = `
4352
- ${prefix}${json}${suffix}`;
4353
- const identity = findBundleFooter(source, "globalThis.__sootsimModulePaths=");
4354
- return identity < 0 ? source + footer : source.slice(0, identity) + footer + source.slice(identity);
4355
- }
4356
-
4357
- // src/packageVersionsContract.ts
4358
- var PACKAGE_VERSIONS_HEADER = "X-Peach-Package-Versions";
4359
- var FOOTER = "__peachPackageVersions";
4360
- function readPackageVersions(value) {
4361
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
4362
- throw new Error("invalid package versions");
4363
- }
4364
- const versions = {};
4365
- for (const [name, version] of Object.entries(value)) {
4366
- if (name.length === 0 || typeof version !== "string" || version.length === 0) {
4367
- throw new Error("invalid package versions");
4368
- }
4369
- versions[name] = version;
4370
- }
4371
- return versions;
4372
- }
4373
- function insertPackageVersionsFooter(source, versions) {
4374
- return insertBundleGlobalFooter(source, FOOTER, readPackageVersions(versions));
4375
- }
4376
-
4377
5519
  // src/vite-plugin-one.ts
4378
5520
  init_runtime_assets();
4379
5521
 
@@ -4510,7 +5652,7 @@ function peachPlugin(options = {}) {
4510
5652
  }
4511
5653
  res.setHeader(key, value);
4512
5654
  }
4513
- const forward = res.statusCode === 200 ? forwardRolldownBundleResponse(upstream, res) : (0, import_promises3.pipeline)(upstream, res);
5655
+ const forward = res.statusCode === 200 ? forwardRolldownBundleResponse(upstream, res) : (0, import_promises5.pipeline)(upstream, res);
4514
5656
  forward.catch(
4515
5657
  (error) => res.destroy(error instanceof Error ? error : new Error(String(error)))
4516
5658
  );
@@ -4529,11 +5671,11 @@ function peachPlugin(options = {}) {
4529
5671
  let swiftModuleRoot;
4530
5672
  const moduleRootFor = () => {
4531
5673
  if (swiftModuleRoot === void 0) {
4532
- const moduleRoot = import_path3.default.resolve(
4533
- import_path3.default.dirname((0, import_node_url.fileURLToPath)(__sootsim_import_meta_url)),
5674
+ const moduleRoot = import_path4.default.resolve(
5675
+ import_path4.default.dirname((0, import_node_url.fileURLToPath)(__sootsim_import_meta_url)),
4534
5676
  "../../sootsim-swift"
4535
5677
  );
4536
- swiftModuleRoot = import_fs3.default.existsSync(import_path3.default.join(moduleRoot, "toolchain.json")) ? moduleRoot : null;
5678
+ swiftModuleRoot = import_fs4.default.existsSync(import_path4.default.join(moduleRoot, "toolchain.json")) ? moduleRoot : null;
4537
5679
  }
4538
5680
  return swiftModuleRoot ?? void 0;
4539
5681
  };
@@ -4618,15 +5760,15 @@ function peachPlugin(options = {}) {
4618
5760
  });
4619
5761
  }
4620
5762
  server.watcher.on("add", (file) => {
4621
- if (import_path3.default.basename(file) === "Package.swift") swiftPackages = void 0;
5763
+ if (import_path4.default.basename(file) === "Package.swift") swiftPackages = void 0;
4622
5764
  });
4623
5765
  server.watcher.on("unlink", (file) => {
4624
- if (import_path3.default.basename(file) === "Package.swift") swiftPackages = void 0;
5766
+ if (import_path4.default.basename(file) === "Package.swift") swiftPackages = void 0;
4625
5767
  });
4626
5768
  let kotlinModuleRoot;
4627
5769
  server.watcher.on("all", (_event, file) => {
4628
5770
  if (!kotlinModuleRoot) return;
4629
- if (file.endsWith(".kt") || file.startsWith(`${kotlinModuleRoot}${import_path3.default.sep}`))
5771
+ if (file.endsWith(".kt") || file.startsWith(`${kotlinModuleRoot}${import_path4.default.sep}`))
4630
5772
  sendSwiftChange({ type: "kotlin", packageName: "kotlin" });
4631
5773
  });
4632
5774
  server.middlewares.use((req, res, next) => {
@@ -4637,7 +5779,7 @@ function peachPlugin(options = {}) {
4637
5779
  const root = host.peachKotlinModuleRoot();
4638
5780
  kotlinModuleRoot = root;
4639
5781
  server.watcher.add(
4640
- ["sdk.tar.gz", "toolchain.json"].map((file) => import_path3.default.join(root, file))
5782
+ ["sdk.tar.gz", "toolchain.json"].map((file) => import_path4.default.join(root, file))
4641
5783
  );
4642
5784
  }
4643
5785
  const served = await host.serveKotlinRequest(pathname, res, {
@@ -4668,7 +5810,7 @@ function peachPlugin(options = {}) {
4668
5810
  for (const packageName of activeSwiftPackages) {
4669
5811
  const packagePath = packages.get(packageName);
4670
5812
  const widgetChanged = packageName === "OneWidgets" && widgetPackage?.watched.includes(file);
4671
- if (!widgetChanged && !(packagePath && file.startsWith(`${packagePath}${import_path3.default.sep}`)) && !(moduleRoot && file.startsWith(`${moduleRoot}${import_path3.default.sep}`)))
5813
+ if (!widgetChanged && !(packagePath && file.startsWith(`${packagePath}${import_path4.default.sep}`)) && !(moduleRoot && file.startsWith(`${moduleRoot}${import_path4.default.sep}`)))
4672
5814
  continue;
4673
5815
  void packageMetadata(packageName, moduleRoot).then((metadata) => {
4674
5816
  sendSwiftChange({
@@ -4738,7 +5880,7 @@ function peachPlugin(options = {}) {
4738
5880
  );
4739
5881
  };
4740
5882
  const buildShellHtml = (runtimeRoot, origin) => {
4741
- const html = import_fs3.default.readFileSync(import_path3.default.join(runtimeRoot, "index.html"), "utf8");
5883
+ const html = import_fs4.default.readFileSync(import_path4.default.join(runtimeRoot, "index.html"), "utf8");
4742
5884
  const lock = readDaemonLockfile();
4743
5885
  const bridgePort = lock && isDaemonLockfileFresh(lock) && lock.bridgePort > 0 ? lock.bridgePort : DEFAULT_SOOTSIM_BRIDGE_PORT;
4744
5886
  const inject = `<script>(function(){var u=new URL(location.href);var b=${JSON.stringify(bundleForOrigin(origin))};if(!u.searchParams.has('bundle'))u.searchParams.set('bundle',b);window.__sootsimBridgePort=${bridgePort};window.__peachPageServingAuthority='contributor';history.replaceState(null,'','${prefix}/'+u.search)})()</script>`;
@@ -4803,6 +5945,7 @@ function peachPlugin(options = {}) {
4803
5945
  });
4804
5946
  });
4805
5947
  server.middlewares.use((req, res, next) => {
5948
+ if (serveBrowserProxyRoute(req, res)) return;
4806
5949
  const url = req.url || "";
4807
5950
  const pathname = url.split("?")[0];
4808
5951
  const runtimeRoot = resolveRuntimeRootForRequestHost(req.headers.host);
@@ -4823,8 +5966,7 @@ function peachPlugin(options = {}) {
4823
5966
  }
4824
5967
  }
4825
5968
  if (pathname === prefix || pathname === prefix + "/") {
4826
- res.setHeader("content-type", "text/html");
4827
- res.end(buildShellHtml(runtimeRoot, requestOrigin(req)));
5969
+ sendShellHtml(res, buildShellHtml(runtimeRoot, requestOrigin(req)));
4828
5970
  return;
4829
5971
  }
4830
5972
  if (pathname.startsWith(prefix + "/")) {
@@ -4836,10 +5978,9 @@ function peachPlugin(options = {}) {
4836
5978
  serveRuntimeFile(req, res, fullPath);
4837
5979
  return;
4838
5980
  }
4839
- const ext = import_path3.default.extname(pathname);
5981
+ const ext = import_path4.default.extname(pathname);
4840
5982
  if (!ext) {
4841
- res.setHeader("content-type", "text/html");
4842
- res.end(buildShellHtml(runtimeRoot, requestOrigin(req)));
5983
+ sendShellHtml(res, buildShellHtml(runtimeRoot, requestOrigin(req)));
4843
5984
  return;
4844
5985
  }
4845
5986
  }