peachsim 0.1.730 → 0.1.745

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 (105) hide show
  1. package/cli/bridge-flow-runner.ts +15 -2
  2. package/cli/commands/control.ts +13 -3
  3. package/cli/commands/desktop.ts +1 -0
  4. package/cli/commands/electron.ts +12 -8
  5. package/cli/commands/flow.ts +1 -3
  6. package/cli/commands/install-desktop.ts +105 -66
  7. package/cli/commands/logout.ts +5 -1
  8. package/cli/commands/no-bridge-hint.ts +2 -2
  9. package/cli/commands/swift.ts +26 -9
  10. package/cli/desktop-companion.ts +36 -9
  11. package/cli/drivers/desktop.ts +65 -0
  12. package/cli/drivers/electron.ts +4 -66
  13. package/cli/drivers/index.ts +1 -0
  14. package/cli/drivers/playwright.ts +3 -3
  15. package/cli/drivers/registry.ts +7 -2
  16. package/cli/drivers/types.ts +4 -3
  17. package/cli/maestro-js.ts +10 -0
  18. package/cli/outbound-endpoints.ts +2 -2
  19. package/dist-lib/agent-daemon-client.cjs +1 -1
  20. package/dist-lib/agent-events.cjs +1 -1
  21. package/dist-lib/agent-identity.cjs +1 -1
  22. package/dist-lib/agent-sessions.cjs +1 -1
  23. package/dist-lib/attached-projects.cjs +1 -1
  24. package/dist-lib/auth/shared-session.cjs +39 -9
  25. package/dist-lib/backend-origin.cjs +1 -1
  26. package/dist-lib/beta.cjs +1 -1
  27. package/dist-lib/beta.mjs +1 -1
  28. package/dist-lib/bridge-constants.cjs +1 -1
  29. package/dist-lib/bridge-contract-input.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.mjs +1 -1
  31. package/dist-lib/bridge-contract.cjs +1 -1
  32. package/dist-lib/bridge-contract.mjs +1 -1
  33. package/dist-lib/capture-contract.cjs +13 -19
  34. package/dist-lib/capture-contract.mjs +13 -19
  35. package/dist-lib/cli-constants.cjs +1 -1
  36. package/dist-lib/cloud-contract.cjs +1 -1
  37. package/dist-lib/cloud-contract.mjs +1 -1
  38. package/dist-lib/cloud-test-args.cjs +1 -1
  39. package/dist-lib/cloud-test-args.mjs +1 -1
  40. package/dist-lib/cloud.cjs +1 -1
  41. package/dist-lib/cloud.mjs +1 -1
  42. package/dist-lib/config.cjs +1 -1
  43. package/dist-lib/detox/index.cjs +20 -2
  44. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  45. package/dist-lib/home-paths.cjs +32 -1
  46. package/dist-lib/host/bridge-host.cjs +1616 -532
  47. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  48. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  49. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  50. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  51. package/dist-lib/host/websocket-proxy.cjs +1 -1
  52. package/dist-lib/index.cjs +14 -19
  53. package/dist-lib/jump-to-source-babel.cjs +1 -1
  54. package/dist-lib/jump-to-source-native.cjs +1 -1
  55. package/dist-lib/kotlin-host.cjs +1 -1
  56. package/dist-lib/menu.cjs +1 -1
  57. package/dist-lib/menu.mjs +1 -1
  58. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  59. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  60. package/dist-lib/metro-production-bundle.cjs +1 -1
  61. package/dist-lib/metro-production-bundle.mjs +1 -1
  62. package/dist-lib/metro.cjs +1 -1
  63. package/dist-lib/native-app-identity.cjs +1 -1
  64. package/dist-lib/native-app-identity.mjs +1 -1
  65. package/dist-lib/native-firebase-metadata.cjs +1 -1
  66. package/dist-lib/native-firebase-metadata.mjs +1 -1
  67. package/dist-lib/plist.cjs +1 -1
  68. package/dist-lib/plist.mjs +1 -1
  69. package/dist-lib/profiles.cjs +1 -1
  70. package/dist-lib/public-brand.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.cjs +1 -1
  72. package/dist-lib/react-native-host-modules.mjs +1 -1
  73. package/dist-lib/render-mode.cjs +1 -1
  74. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  75. package/dist-lib/sdk.cjs +2 -1
  76. package/dist-lib/sdk.mjs +2 -1
  77. package/dist-lib/skills.cjs +2306 -1067
  78. package/dist-lib/swift-compile.cjs +317 -60
  79. package/dist-lib/swift-compile.mjs +313 -61
  80. package/dist-lib/swift-package.cjs +146 -9
  81. package/dist-lib/swift-package.mjs +144 -9
  82. package/dist-lib/swift-submit.cjs +2 -2
  83. package/dist-lib/swift-submit.mjs +2 -2
  84. package/dist-lib/swift-toolchain.cjs +1 -1
  85. package/dist-lib/swift.cjs +1 -1
  86. package/dist-lib/vite-swift.cjs +1310 -226
  87. package/dist-lib/vite.cjs +1 -1
  88. package/package.json +1 -1
  89. package/skills/contrast/SKILL.md +1 -1
  90. package/src/auth/shared-session.ts +45 -9
  91. package/src/bridge-constants.ts +7 -7
  92. package/src/capture-contract.ts +18 -33
  93. package/src/desktop-host-delivery.ts +81 -0
  94. package/src/home-paths.ts +30 -0
  95. package/src/host/bridge-host.ts +11 -6
  96. package/src/native-seam-manifest.ts +0 -11
  97. package/src/sim-client.ts +1 -0
  98. package/src/swift-compile.ts +403 -68
  99. package/src/swift-distribution.lock.json +11 -11
  100. package/src/swift-host.ts +316 -43
  101. package/src/swift-package.ts +204 -19
  102. package/src/swift-remote-packages.ts +255 -0
  103. package/src/swift-submit.ts +4 -1
  104. package/src/vite-plugin.ts +19 -8
  105. package/src/xcode-project.ts +527 -0
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.730 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.745 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  let __sootsim_import_meta_url = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
@@ -45,8 +45,8 @@ __export(vite_plugin_swift_exports, {
45
45
  swiftPlugin: () => swiftPlugin
46
46
  });
47
47
  module.exports = __toCommonJS(vite_plugin_swift_exports);
48
- var import_node_fs8 = __toESM(require("node:fs"), 1);
49
- var import_node_path9 = __toESM(require("node:path"), 1);
48
+ var import_node_fs10 = __toESM(require("node:fs"), 1);
49
+ var import_node_path11 = __toESM(require("node:path"), 1);
50
50
 
51
51
  // ../sootsim-swift/src/entryModule.ts
52
52
  function nativeExportLines(args, commonjs) {
@@ -251,14 +251,24 @@ function swiftImplicitResourcePaths(paths) {
251
251
  ) || /(?:^|\/)[^/]+\.lproj\/[^/]+$/.test(file))
252
252
  ).sort();
253
253
  }
254
- function swiftManifestTargets(manifest, resourcePaths = []) {
255
- const implicitResources = swiftImplicitResourcePaths(resourcePaths);
256
- const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
257
- const targets = [];
258
- const pattern = /\.(executableTarget|target)\s*\(/g;
254
+ var MANIFEST_DECLARATIONS = [
255
+ "executableTarget",
256
+ "testTarget",
257
+ "binaryTarget",
258
+ "systemLibrary",
259
+ "macro",
260
+ "plugin",
261
+ "target",
262
+ "library",
263
+ "executable",
264
+ "package"
265
+ ];
266
+ function manifestCalls(manifest, kinds) {
267
+ const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"])\/\/[^\n]*/g, "$1");
268
+ const calls = [];
269
+ const pattern = new RegExp(`\\.(${MANIFEST_DECLARATIONS.join("|")})\\s*\\(`, "g");
259
270
  let match;
260
271
  while ((match = pattern.exec(code)) !== null) {
261
- const executable = match[1] === "executableTarget";
262
272
  let depth = 1;
263
273
  const start = pattern.lastIndex;
264
274
  let i = start;
@@ -286,18 +296,141 @@ function swiftManifestTargets(manifest, resourcePaths = []) {
286
296
  }
287
297
  i++;
288
298
  }
299
+ if (kinds.includes(match[1]))
300
+ calls.push({ kind: match[1], flat, call: code.slice(start, i) });
301
+ pattern.lastIndex = i;
302
+ }
303
+ return calls;
304
+ }
305
+ var NAME = /\bname\s*:\s*"([^"]+)"/;
306
+ function listArgument(call, label) {
307
+ const start = new RegExp(`\\b${label}\\s*:\\s*\\[`).exec(call);
308
+ if (!start) return [];
309
+ const items = [];
310
+ let depth = 0;
311
+ let inString = false;
312
+ let item = "";
313
+ for (let i = start.index + start[0].length; i < call.length; i++) {
314
+ const ch = call[i];
315
+ if (inString) {
316
+ item += ch;
317
+ if (ch === '"' && call[i - 1] !== "\\") inString = false;
318
+ continue;
319
+ }
320
+ if (ch === '"') inString = true;
321
+ else if (ch === "(" || ch === "[") depth++;
322
+ else if (ch === ")" || ch === "]") {
323
+ if (depth === 0) break;
324
+ depth--;
325
+ } else if (ch === "," && depth === 0) {
326
+ items.push(item.trim());
327
+ item = "";
328
+ continue;
329
+ }
330
+ item += ch;
331
+ }
332
+ if (item.trim()) items.push(item.trim());
333
+ return items;
334
+ }
335
+ function swiftPackageIdentity(url) {
336
+ return (url.split("/").pop() ?? url).replace(/\.git$/, "").toLowerCase();
337
+ }
338
+ function swiftManifestGraph(manifest) {
339
+ const graph = {
340
+ products: /* @__PURE__ */ new Map(),
341
+ dependencies: /* @__PURE__ */ new Map(),
342
+ binaryTargets: /* @__PURE__ */ new Set(),
343
+ systemLibraries: /* @__PURE__ */ new Set(),
344
+ packageURLs: /* @__PURE__ */ new Map(),
345
+ packagePaths: []
346
+ };
347
+ for (const { kind, flat, call } of manifestCalls(manifest, [
348
+ "library",
349
+ "executableTarget",
350
+ "target",
351
+ "binaryTarget",
352
+ "systemLibrary",
353
+ "package"
354
+ ])) {
355
+ if (kind === "package") {
356
+ const local = /\bpath\s*:\s*"([^"]+)"/.exec(flat)?.[1];
357
+ if (local) graph.packagePaths.push(local);
358
+ const url = /\burl\s*:\s*"([^"]+)"/.exec(flat)?.[1];
359
+ if (!url) continue;
360
+ graph.packageURLs.set(swiftPackageIdentity(url), url);
361
+ const name2 = NAME.exec(flat)?.[1];
362
+ if (name2) graph.packageURLs.set(name2.toLowerCase(), url);
363
+ continue;
364
+ }
365
+ const name = NAME.exec(flat)?.[1];
366
+ if (!name) continue;
367
+ if (kind === "library") {
368
+ graph.products.set(
369
+ name,
370
+ listArgument(call, "targets").flatMap(
371
+ (item) => /^"([^"]+)"$/.exec(item)?.[1] ?? []
372
+ )
373
+ );
374
+ continue;
375
+ }
376
+ if (kind === "binaryTarget") graph.binaryTargets.add(name);
377
+ if (kind === "systemLibrary") graph.systemLibraries.add(name);
378
+ const dependencies = [];
379
+ for (const item of listArgument(call, "dependencies")) {
380
+ const platforms = /condition\s*:\s*\.when\(\s*platforms\s*:\s*\[([^\]]*)\]/.exec(
381
+ item
382
+ )?.[1];
383
+ if (platforms !== void 0 && !/\.iOS\b/.test(platforms)) continue;
384
+ if (/condition\s*:\s*\.when\([^)]*\btraits\s*:/.test(item)) continue;
385
+ const plain = /^"([^"]+)"$/.exec(item)?.[1];
386
+ const product = /^\.product(?:Item)?\(\s*name\s*:\s*"([^"]+)"\s*,\s*package\s*:\s*"([^"]+)"/.exec(
387
+ item
388
+ );
389
+ const target = /^\.(?:target|byName)(?:Item)?\(\s*name\s*:\s*"([^"]+)"/.exec(
390
+ item
391
+ )?.[1];
392
+ if (plain) dependencies.push({ kind: "target", name: plain });
393
+ else if (product)
394
+ dependencies.push({
395
+ kind: "product",
396
+ name: product[1],
397
+ package: product[2].toLowerCase()
398
+ });
399
+ else if (target) dependencies.push({ kind: "target", name: target });
400
+ }
401
+ graph.dependencies.set(name, dependencies);
402
+ }
403
+ for (const dependencies of graph.dependencies.values()) {
404
+ for (const [index, dependency] of dependencies.entries()) {
405
+ if (dependency.kind === "target" && !graph.dependencies.has(dependency.name))
406
+ dependencies[index] = {
407
+ kind: "product",
408
+ name: dependency.name,
409
+ package: dependency.name.toLowerCase()
410
+ };
411
+ }
412
+ }
413
+ return graph;
414
+ }
415
+ function swiftManifestTargets(manifest, resourcePaths = []) {
416
+ const implicitResources = swiftImplicitResourcePaths(resourcePaths);
417
+ const targets = [];
418
+ for (const { kind, flat, call } of manifestCalls(manifest, [
419
+ "executableTarget",
420
+ "target"
421
+ ])) {
422
+ const executable = kind === "executableTarget";
289
423
  const name = /\bname\s*:\s*"([^"]+)"/.exec(flat)?.[1];
290
424
  if (!name) continue;
291
425
  const rawPath = /\bpath\s*:\s*"([^"]*)"/.exec(flat)?.[1];
292
426
  const targetPath = rawPath == null || rawPath === "" ? `Sources/${name}` : rawPath.replace(/^\.\//, "").replace(/\/+$/, "");
293
- const call = code.slice(start, i);
294
427
  const languageMode = Number(
295
428
  /\.swiftLanguageMode\(\s*\.v(\d+)\s*\)/.exec(call)?.[1] ?? "5"
296
429
  );
297
430
  const mainActorIsolation = /\.defaultIsolation\(\s*MainActor\.self\s*\)/.test(call);
298
431
  const excluded = [
299
432
  ...(/\bexclude\s*:\s*\[([^\]]*)\]/.exec(flat)?.[1] ?? "").matchAll(/"([^"]+)"/g)
300
- ].map((match2) => match2[1].replace(/^\.\//, "").replace(/\/+$/, ""));
433
+ ].map((match) => match[1].replace(/^\.\//, "").replace(/\/+$/, ""));
301
434
  const prefix = targetPath === "." ? "" : `${targetPath}/`;
302
435
  const resources = /\bresources\s*:/.test(flat) || implicitResources.some((file) => {
303
436
  if (!file.startsWith(prefix)) return false;
@@ -352,14 +485,14 @@ function swiftModuleInputFiles(root) {
352
485
  "scripts/contrast-app-Package.swift",
353
486
  "toolchain.json"
354
487
  ];
355
- const walk = (dir) => {
488
+ const walk2 = (dir) => {
356
489
  for (const entry of (0, import_node_fs2.readdirSync)(import_node_path2.default.join(root, dir), { withFileTypes: true })) {
357
490
  const relative = `${dir}/${entry.name}`;
358
- if (entry.isDirectory()) walk(relative);
491
+ if (entry.isDirectory()) walk2(relative);
359
492
  else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative);
360
493
  }
361
494
  };
362
- walk("Sources");
495
+ walk2("Sources");
363
496
  return files.sort();
364
497
  }
365
498
  async function ensureMacroPlugins(moduleRoot, toolchainBin) {
@@ -441,6 +574,9 @@ var OPTIONAL_FRAMEWORK_DEPENDENCIES = {
441
574
  CryptoKit: [],
442
575
  CommonCrypto: [],
443
576
  CoreText: [],
577
+ Compression: ["PeachCodec"],
578
+ zlib: ["PeachCodec"],
579
+ PeachCodec: [],
444
580
  Security: ["CryptoKit"],
445
581
  TikTokBusinessSDK: [],
446
582
  nSure: [],
@@ -451,6 +587,66 @@ var OPTIONAL_FRAMEWORK_DEPENDENCIES = {
451
587
  DatadogTrace: ["DatadogCore"]
452
588
  };
453
589
  var OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES));
590
+ var SWIFT_IMPORT = /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/;
591
+ function swiftImportNames(contents, unconditional = false) {
592
+ const names = [];
593
+ let depth = 0;
594
+ for (const line of contents.split("\n")) {
595
+ const directive = /^\s*#(if|endif)\b/.exec(line)?.[1];
596
+ if (directive === "if") depth++;
597
+ else if (directive === "endif") depth = Math.max(0, depth - 1);
598
+ if (unconditional && depth > 0) continue;
599
+ const name = SWIFT_IMPORT.exec(line)?.[1];
600
+ if (name) names.push(name);
601
+ }
602
+ return names;
603
+ }
604
+ function swiftPeachModules(moduleRoot) {
605
+ const distribution = swiftDistributionAt(moduleRoot);
606
+ return distribution ? distribution.modules : [
607
+ ...(0, import_node_fs2.readFileSync)(import_node_path2.default.join(moduleRoot, "Package.swift"), "utf8").matchAll(
608
+ /\.(?:target|systemLibrary)\(\s*name:\s*"([^"]+)"/g
609
+ )
610
+ ].map((match) => match[1]);
611
+ }
612
+ var availableModules = /* @__PURE__ */ new Map();
613
+ function swiftAvailableModules(moduleRoot, toolchainBin) {
614
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId;
615
+ const key = `${moduleRoot}\0${sdk}`;
616
+ const cached = availableModules.get(key);
617
+ if (cached) return cached;
618
+ const modules = new Set(swiftPeachModules(moduleRoot));
619
+ const configuration = (0, import_node_child_process2.execFileSync)(
620
+ import_node_path2.default.join(toolchainBin, "swift"),
621
+ ["sdk", "configure", "--show-configuration", sdk, "wasm32-unknown-wasip1"],
622
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }
623
+ );
624
+ const resources = /^swiftResourcesPath:\s*(.+)$/m.exec(configuration)?.[1]?.trim();
625
+ if (!resources) throw new Error(`swift sdk ${sdk} reports no swiftResourcesPath`);
626
+ for (const entry of (0, import_node_fs2.readdirSync)(import_node_path2.default.join(resources, "wasi"))) {
627
+ if (entry.endsWith(".swiftmodule"))
628
+ modules.add(entry.slice(0, -".swiftmodule".length));
629
+ }
630
+ for (const entry of (0, import_node_fs2.readdirSync)(resources)) {
631
+ const map = import_node_path2.default.join(resources, entry, "module.modulemap");
632
+ if (!(0, import_node_fs2.existsSync)(map)) continue;
633
+ for (const match of (0, import_node_fs2.readFileSync)(map, "utf8").matchAll(/^module\s+([A-Za-z_]\w*)/gm))
634
+ modules.add(match[1]);
635
+ }
636
+ availableModules.set(key, modules);
637
+ return modules;
638
+ }
639
+ function missingSwiftModules(files, available) {
640
+ const missing = /* @__PURE__ */ new Map();
641
+ for (const [file, contents] of Object.entries(files)) {
642
+ if (!file.endsWith(".swift") || file === "Package.swift") continue;
643
+ for (const name of new Set(swiftImportNames(contents, true))) {
644
+ if (available.has(name)) continue;
645
+ missing.set(name, [...missing.get(name) ?? [], file]);
646
+ }
647
+ }
648
+ return new Map([...missing].sort(([left], [right]) => left.localeCompare(right)));
649
+ }
454
650
  function swiftTargetDependencies(files, targets) {
455
651
  const names = /* @__PURE__ */ new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)]);
456
652
  const siblings = /* @__PURE__ */ new Map();
@@ -463,10 +659,8 @@ function swiftTargetDependencies(files, targets) {
463
659
  (candidate) => candidate.name !== target.name && candidate.path !== "." && candidate.path.startsWith(prefix) && file.startsWith(`${candidate.path}/`)
464
660
  ))
465
661
  continue;
466
- for (const match of contents.matchAll(
467
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm
468
- )) {
469
- if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1]);
662
+ for (const name of swiftImportNames(contents)) {
663
+ if (names.has(name) && name !== target.name) deps.add(name);
470
664
  }
471
665
  }
472
666
  siblings.set(target.name, [...deps].sort());
@@ -476,16 +670,14 @@ function swiftTargetDependencies(files, targets) {
476
670
  var ONE_PRODUCT = '.product(name: "One", package: "sootsim-swift")';
477
671
  var SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")';
478
672
  var importsSpriteKit = (files) => Object.entries(files).some(
479
- ([file, contents]) => file.endsWith(".swift") && /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
480
- contents
481
- )
673
+ ([file, contents]) => file.endsWith(".swift") && swiftImportNames(contents).includes("SpriteKit")
482
674
  );
483
- var FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"';
675
+ var FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking", "-Xfrontend", "-import-module", "-Xfrontend", "WASILibc", "-Xfrontend", "-import-module", "-Xfrontend", "wasi_pthread"';
484
676
  var ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"';
485
- var MULTI_MANIFEST_VERSION = 10;
677
+ var MULTI_MANIFEST_VERSION = 11;
486
678
  function swiftArtifactHash(input, release, moduleRoot) {
487
679
  const hash = (0, import_node_crypto2.createHash)("sha256");
488
- hash.update(`swift-compile/v14
680
+ hash.update(`swift-compile/v16
489
681
  ${release}
490
682
  `);
491
683
  if (input.oneModule) hash.update("one-module\n");
@@ -594,15 +786,15 @@ function emitSwiftPackageManifest(args) {
594
786
  }
595
787
  function syncSwiftTree(base, files) {
596
788
  (0, import_node_fs2.mkdirSync)(base, { recursive: true });
597
- const walk = (dir) => {
789
+ const walk2 = (dir) => {
598
790
  for (const entry of (0, import_node_fs2.readdirSync)(dir, { withFileTypes: true })) {
599
791
  const full = import_node_path2.default.join(dir, entry.name);
600
792
  if (dir === base && entry.name === ".build") continue;
601
- if (entry.isDirectory()) walk(full);
793
+ if (entry.isDirectory()) walk2(full);
602
794
  else if (!files.has(full)) (0, import_node_fs2.rmSync)(full, { force: true });
603
795
  }
604
796
  };
605
- walk(base);
797
+ walk2(base);
606
798
  for (const [full, contents] of files) {
607
799
  if ((0, import_node_fs2.existsSync)(full) && (0, import_node_fs2.readFileSync)(full, "utf8") === contents) continue;
608
800
  (0, import_node_fs2.mkdirSync)(import_node_path2.default.dirname(full), { recursive: true });
@@ -657,23 +849,98 @@ function forwardedArguments(parameters) {
657
849
  }
658
850
  return args.join(", ");
659
851
  }
660
- function liftExtensionOverrides(source) {
852
+ function closingBrace(source, tokens, open) {
853
+ let depth = 0;
854
+ for (const at of tokens) {
855
+ if (at < open) continue;
856
+ if (source[at] === "{") depth++;
857
+ else if (source[at] === "}" && --depth === 0) return at + 1;
858
+ }
859
+ return source.length;
860
+ }
861
+ function scanObjCExtensionMembers(source, tokens, records) {
862
+ const masked = swiftCodeMask(source);
863
+ const found = /* @__PURE__ */ new Map();
864
+ const member = /\b(func|var)\s+([A-Za-z_]\w*)/g;
865
+ for (const record of records) {
866
+ const close = closingBrace(source, tokens, record.open);
867
+ const body = masked.slice(record.open, close);
868
+ member.lastIndex = 0;
869
+ for (let match = member.exec(body); match; match = member.exec(body)) {
870
+ const at = record.open + match.index + match[0].indexOf(match[1]);
871
+ let depth = 0;
872
+ for (const token of tokens) {
873
+ if (token <= record.open) continue;
874
+ if (token >= at) break;
875
+ if (source[token] === "{") depth++;
876
+ else if (source[token] === "}") depth--;
877
+ }
878
+ if (depth > 0) continue;
879
+ const head = masked.slice(record.open, at);
880
+ const bound = Math.max(
881
+ head.lastIndexOf(";"),
882
+ head.lastIndexOf("{"),
883
+ head.lastIndexOf("}")
884
+ );
885
+ const prefix = head.slice(bound + 1);
886
+ if (/(?:^|[^A-Za-z0-9_$])(?:private|fileprivate|static|class)(?:[^A-Za-z0-9_$]|$)/.test(
887
+ prefix
888
+ ))
889
+ continue;
890
+ if (!/@objc\b/.test(prefix) && !/@IBAction\b/.test(prefix) && !record.objcMembers)
891
+ continue;
892
+ const members = found.get(record.type) ?? /* @__PURE__ */ new Set();
893
+ members.add(match[2]);
894
+ found.set(record.type, members);
895
+ }
896
+ }
897
+ return found;
898
+ }
899
+ function objcExtensionMemberIndex(sources) {
900
+ const index = /* @__PURE__ */ new Map();
901
+ for (const source of sources) {
902
+ const { tokens } = swiftCodeScan(source);
903
+ const masked = swiftCodeMask(source);
904
+ const records = [];
905
+ let pending = null;
906
+ for (const at of tokens) {
907
+ const rest = source.slice(at, at + 600);
908
+ if (rest.startsWith("{")) {
909
+ if (pending) records.push({ ...pending, open: at });
910
+ pending = null;
911
+ continue;
912
+ }
913
+ if (rest.startsWith("}")) continue;
914
+ const extended = EXTENSION_DECL.exec(rest);
915
+ if (extended) {
916
+ const lines = source.lastIndexOf("\n", source.lastIndexOf("\n", at - 1) - 1) + 1;
917
+ pending = {
918
+ type: extended[1].split(".").pop(),
919
+ objcMembers: /@objcMembers\b/.test(masked.slice(lines, at))
920
+ };
921
+ }
922
+ }
923
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, records)) {
924
+ const into = index.get(type) ?? /* @__PURE__ */ new Set();
925
+ for (const member of members) into.add(member);
926
+ index.set(type, into);
927
+ }
928
+ }
929
+ return index;
930
+ }
931
+ function liftExtensionOverrides(source, extraObjCExtensions) {
661
932
  const { tokens } = swiftCodeScan(source);
933
+ const masked = swiftCodeMask(source);
662
934
  const stack = [];
663
935
  let pending = null;
664
936
  const classes = /* @__PURE__ */ new Map();
665
937
  let declaredBase = null;
666
938
  let declaredObjCMembers = false;
939
+ const extensions = [];
940
+ let declaredExtObjCMembers = false;
667
941
  const lifted = [];
668
- const closing = (open) => {
669
- let depth = 0;
670
- for (const at of tokens) {
671
- if (at < open) continue;
672
- if (source[at] === "{") depth++;
673
- else if (source[at] === "}" && --depth === 0) return at + 1;
674
- }
675
- return source.length;
676
- };
942
+ const overrides = [];
943
+ const closing = (open) => closingBrace(source, tokens, open);
677
944
  for (const at of tokens) {
678
945
  const rest = source.slice(at, at + 600);
679
946
  if (rest.startsWith("{")) {
@@ -684,6 +951,12 @@ function liftExtensionOverrides(source) {
684
951
  base: declaredBase,
685
952
  objcMembers: declaredObjCMembers
686
953
  });
954
+ if (frame.kind === "extension")
955
+ extensions.push({
956
+ type: frame.name,
957
+ open: at,
958
+ objcMembers: declaredExtObjCMembers
959
+ });
687
960
  stack.push(frame);
688
961
  pending = null;
689
962
  continue;
@@ -703,12 +976,39 @@ function liftExtensionOverrides(source) {
703
976
  const extended = EXTENSION_DECL.exec(rest);
704
977
  if (extended) {
705
978
  pending = { kind: "extension", name: extended[1].split(".").pop() };
979
+ const lines = source.lastIndexOf("\n", source.lastIndexOf("\n", at - 1) - 1) + 1;
980
+ declaredExtObjCMembers = /@objcMembers\b/.test(masked.slice(lines, at));
706
981
  continue;
707
982
  }
708
983
  const top = stack.at(-1);
709
- if (!rest.startsWith("override") || top?.kind !== "extension" || pending) continue;
984
+ if (!rest.startsWith("override") || pending) continue;
710
985
  const line = source.slice(source.lastIndexOf("\n", at - 1) + 1, at);
711
986
  const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim());
987
+ if (top?.kind === "class") {
988
+ let member;
989
+ let nameAt = 0;
990
+ const direct = OVERRIDE_FUNC.exec(rest);
991
+ if (direct) {
992
+ member = direct[2];
993
+ nameAt = at + rest.indexOf(
994
+ member,
995
+ rest.indexOf("func", "override".length + direct[1].length) + 4
996
+ );
997
+ } else {
998
+ const property2 = OVERRIDE_VAR.exec(rest);
999
+ if (property2) {
1000
+ const open = at + property2[0].length - 1;
1001
+ if (!/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) {
1002
+ member = property2[2];
1003
+ nameAt = at + rest.indexOf(member, rest.indexOf("var"));
1004
+ }
1005
+ }
1006
+ }
1007
+ if (member !== void 0 && !modifiers.includes("private") && !modifiers.includes("fileprivate"))
1008
+ overrides.push({ type: top.name, member, at, nameAt });
1009
+ continue;
1010
+ }
1011
+ if (top?.kind !== "extension") continue;
712
1012
  const func = OVERRIDE_FUNC.exec(rest);
713
1013
  if (func) {
714
1014
  const name = func[2];
@@ -726,20 +1026,18 @@ function liftExtensionOverrides(source) {
726
1026
  if (args === null) continue;
727
1027
  const call = (clause.includes("->") ? "return " : "") + (/\b(?:throws|rethrows)\b/.test(clause) ? "try " : "") + (/\basync\b/.test(clause) ? "await " : "") + `__peach_ext_${name}(${args})`;
728
1028
  const signature = `func ${name}${func[3] ?? ""}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ""}`;
1029
+ const nameAt = at + rest.indexOf(name, rest.indexOf("func", "override".length + func[1].length) + 4);
729
1030
  lifted.push({
730
1031
  type: top.name,
731
1032
  member: name,
732
- stub: `${[...modifiers, "override"].join(" ")} ${signature} { ${call} };`,
1033
+ at,
1034
+ modifiers,
1035
+ decl: signature,
1036
+ forward: `{ ${call} };`,
1037
+ nameAt,
733
1038
  edits: [
734
1039
  [at, "override".length, " ".repeat("override".length)],
735
- [
736
- at + rest.indexOf(
737
- name,
738
- rest.indexOf("func", "override".length + func[1].length) + 4
739
- ),
740
- 0,
741
- "__peach_ext_"
742
- ]
1040
+ [nameAt, 0, "__peach_ext_"]
743
1041
  ]
744
1042
  });
745
1043
  continue;
@@ -749,42 +1047,79 @@ function liftExtensionOverrides(source) {
749
1047
  const open = at + property[0].length - 1;
750
1048
  if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue;
751
1049
  const name = property[2];
1050
+ const nameAt = at + rest.indexOf(name, rest.indexOf("var"));
752
1051
  lifted.push({
753
1052
  type: top.name,
754
1053
  member: name,
755
- stub: `${[...modifiers, "override"].join(" ")} var ${name}: ${property[3].trim()} { __peach_ext_${name} };`,
1054
+ at,
1055
+ modifiers,
1056
+ decl: `var ${name}: ${property[3].trim()}`,
1057
+ forward: `{ __peach_ext_${name} };`,
1058
+ nameAt,
756
1059
  edits: [
757
1060
  [at, "override".length, " ".repeat("override".length)],
758
- [at + rest.indexOf(name, rest.indexOf("var")), 0, "__peach_ext_"]
1061
+ [nameAt, 0, "__peach_ext_"]
759
1062
  ]
760
1063
  });
761
1064
  }
762
1065
  }
763
- const overridesObjC = (type, member) => {
1066
+ const extIndex = /* @__PURE__ */ new Map();
1067
+ if (extraObjCExtensions)
1068
+ for (const [type, members] of extraObjCExtensions)
1069
+ extIndex.set(type, new Set(members));
1070
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, extensions)) {
1071
+ const into = extIndex.get(type) ?? /* @__PURE__ */ new Set();
1072
+ for (const member of members) into.add(member);
1073
+ extIndex.set(type, into);
1074
+ }
1075
+ const overrideKind = (type, member) => {
764
1076
  let base = classes.get(type)?.base ?? null;
765
1077
  while (base !== null) {
766
- if (APPLE_CLASS.test(base)) return true;
767
1078
  const declaredClass = classes.get(base);
768
- if (!declaredClass) return false;
769
- const body = source.slice(declaredClass.brace, closing(declaredClass.brace));
770
- const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body);
771
- if (found) {
772
- const line = body.slice(body.lastIndexOf("\n", found.index) + 1, found.index);
773
- return declaredClass.objcMembers || /@objc\b/.test(line);
774
- }
775
- base = declaredClass.base;
1079
+ if (declaredClass) {
1080
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace));
1081
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body);
1082
+ if (found) {
1083
+ const line = body.slice(body.lastIndexOf("\n", found.index) + 1, found.index);
1084
+ return declaredClass.objcMembers || /@objc\b/.test(line) ? "objc" : "plain";
1085
+ }
1086
+ if (extIndex.get(base)?.has(member)) return "ext";
1087
+ base = declaredClass.base;
1088
+ } else if (extIndex.get(base)?.has(member)) return "ext";
1089
+ else if (APPLE_CLASS.test(base)) return "apple";
1090
+ else return "unknown";
776
1091
  }
777
- return false;
1092
+ return "unknown";
778
1093
  };
1094
+ const rename = (at, nameAt) => [
1095
+ [at, "override".length, " ".repeat("override".length)],
1096
+ [nameAt, 0, "__peach_ovr_"]
1097
+ ];
779
1098
  const edits = [];
780
1099
  const stubs = /* @__PURE__ */ new Map();
781
1100
  for (const entry of lifted) {
782
1101
  const brace = classes.get(entry.type)?.brace;
783
- if (brace === void 0 || !overridesObjC(entry.type, entry.member)) continue;
1102
+ if (brace === void 0) continue;
1103
+ const kind = overrideKind(entry.type, entry.member);
1104
+ if (kind !== "apple" && kind !== "objc" && kind !== "ext") continue;
1105
+ if (kind === "ext" && (entry.modifiers.includes("private") || entry.modifiers.includes("fileprivate")))
1106
+ continue;
1107
+ if (kind === "ext") {
1108
+ edits.push(...rename(entry.at, entry.nameAt));
1109
+ continue;
1110
+ }
784
1111
  edits.push(...entry.edits);
785
- stubs.set(brace, [...stubs.get(brace) ?? [], entry.stub]);
1112
+ const head = [...entry.modifiers, "override"].filter((word) => word !== "").join(" ");
1113
+ stubs.set(brace, [
1114
+ ...stubs.get(brace) ?? [],
1115
+ `${head} ${entry.decl} ${entry.forward}`
1116
+ ]);
1117
+ }
1118
+ for (const candidate of overrides) {
1119
+ if (overrideKind(candidate.type, candidate.member) !== "ext") continue;
1120
+ edits.push(...rename(candidate.at, candidate.nameAt));
786
1121
  }
787
- for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(" ")}`]);
1122
+ for (const [brace, list2] of stubs) edits.push([brace + 1, 0, ` ${list2.join(" ")}`]);
788
1123
  let out = source;
789
1124
  for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
790
1125
  out = out.slice(0, at) + insert + out.slice(at + remove);
@@ -964,8 +1299,8 @@ function swiftCodeMask(source) {
964
1299
  scanCode(0, false);
965
1300
  return chars.join("");
966
1301
  }
967
- function swiftSourceAsIOS(original) {
968
- const source = liftExtensionOverrides(original);
1302
+ function swiftSourceAsIOS(original, extraObjCExtensions) {
1303
+ const source = liftExtensionOverrides(original, extraObjCExtensions);
969
1304
  const { lineStarts, tokens } = swiftCodeScan(source);
970
1305
  let offset = 0;
971
1306
  const conditioned = source.split("\n").map((line) => {
@@ -1134,7 +1469,7 @@ function swiftCodeScan(source) {
1134
1469
  }
1135
1470
  return { lineStarts: starts, tokens };
1136
1471
  }
1137
- var compiledSource = (file, contents) => file.endsWith(".swift") ? swiftSourceAsIOS(contents) : contents;
1472
+ var compiledSource = (file, contents, extraObjCExtensions) => file.endsWith(".swift") ? swiftSourceAsIOS(contents, extraObjCExtensions) : contents;
1138
1473
  function writeSwiftProject(layout, input, moduleRoot) {
1139
1474
  const resourceTargets = swiftManifestTargets(
1140
1475
  input.files["Package.swift"] ?? "",
@@ -1167,10 +1502,16 @@ function writeSwiftProject(layout, input, moduleRoot) {
1167
1502
  // sootsim-swift files ${modulePlan.digest("hex").slice(0, 16)}
1168
1503
  // resource accessors ${resourcePlan}
1169
1504
  `;
1505
+ const objcExtensions = objcExtensionMemberIndex(
1506
+ Object.entries(input.files).filter(([file]) => file.endsWith(".swift")).map(([, contents]) => contents)
1507
+ );
1170
1508
  if (targets.length === 0) {
1171
1509
  for (const [file, contents] of Object.entries(input.files)) {
1172
1510
  if (file === "Package.swift") continue;
1173
- files.set(import_node_path2.default.join(layout.sources, file), compiledSource(file, contents));
1511
+ files.set(
1512
+ import_node_path2.default.join(layout.sources, file),
1513
+ compiledSource(file, contents, objcExtensions)
1514
+ );
1174
1515
  }
1175
1516
  let manifest = (0, import_node_fs2.readFileSync)(
1176
1517
  import_node_path2.default.join(moduleRoot, "scripts/contrast-app-Package.swift"),
@@ -1216,7 +1557,7 @@ function writeSwiftProject(layout, input, moduleRoot) {
1216
1557
  const base = layout.multi ? layout.root : layout.sources;
1217
1558
  for (const [file, contents] of Object.entries(input.files)) {
1218
1559
  if (file === "Package.swift") continue;
1219
- files.set(import_node_path2.default.join(base, file), compiledSource(file, contents));
1560
+ files.set(import_node_path2.default.join(base, file), compiledSource(file, contents, objcExtensions));
1220
1561
  }
1221
1562
  files.set(
1222
1563
  import_node_path2.default.join(layout.root, "Package.swift"),
@@ -1357,9 +1698,9 @@ function compileSwiftProjectUnit(input, options) {
1357
1698
 
1358
1699
  // src/swift-host.ts
1359
1700
  var import_node_crypto4 = require("node:crypto");
1360
- var import_node_fs7 = __toESM(require("node:fs"), 1);
1701
+ var import_node_fs9 = __toESM(require("node:fs"), 1);
1361
1702
  var import_node_os5 = __toESM(require("node:os"), 1);
1362
- var import_node_path8 = __toESM(require("node:path"), 1);
1703
+ var import_node_path10 = __toESM(require("node:path"), 1);
1363
1704
 
1364
1705
  // ../sootsim-swift/src/bundleAssets.ts
1365
1706
  var import_svgpath = __toESM(require("svgpath"), 1);
@@ -1393,15 +1734,15 @@ function pickImagesetFile(images) {
1393
1734
  scale: pick.scale === "2x" ? 2 : pick.scale === "3x" ? 3 : 1
1394
1735
  };
1395
1736
  }
1396
- function flatScale(path9) {
1397
- const match = /@([23])x\.[^./]+$/.exec(path9);
1737
+ function flatScale(path11) {
1738
+ const match = /@([23])x\.[^./]+$/.exec(path11);
1398
1739
  return match ? Number(match[1]) : 1;
1399
1740
  }
1400
1741
  function providesNamespace(text) {
1401
1742
  if (text === null) return false;
1402
1743
  try {
1403
- const parsed = JSON.parse(text);
1404
- return parsed?.properties?.["provides-namespace"] === true;
1744
+ const parsed2 = JSON.parse(text);
1745
+ return parsed2?.properties?.["provides-namespace"] === true;
1405
1746
  } catch {
1406
1747
  return false;
1407
1748
  }
@@ -1421,25 +1762,25 @@ function catalogEntryName(contentsPath, kind, readText) {
1421
1762
  }
1422
1763
  return segments.join("/");
1423
1764
  }
1424
- function isFlatResourceImage(path9) {
1425
- return path9.split("/").includes("Resources") && RASTER_EXTENSIONS.has(extOf(path9));
1765
+ function isFlatResourceImage(path11) {
1766
+ return path11.split("/").includes("Resources") && RASTER_EXTENSIONS.has(extOf(path11));
1426
1767
  }
1427
1768
  function enumerateBundleImages(paths, readText) {
1428
1769
  const table = [];
1429
1770
  const seen = /* @__PURE__ */ new Set();
1430
- const catalogs = paths.filter((path9) => baseOf(path9) === "Contents.json");
1771
+ const catalogs = paths.filter((path11) => baseOf(path11) === "Contents.json");
1431
1772
  for (const contentsPath of catalogs) {
1432
1773
  const name = catalogEntryName(contentsPath, ".imageset", readText);
1433
1774
  if (name === null || seen.has(name)) continue;
1434
- let parsed;
1775
+ let parsed2;
1435
1776
  try {
1436
1777
  const text = readText(contentsPath);
1437
1778
  if (text === null) continue;
1438
- parsed = JSON.parse(text);
1779
+ parsed2 = JSON.parse(text);
1439
1780
  } catch {
1440
1781
  continue;
1441
1782
  }
1442
- const images = parsed?.images;
1783
+ const images = parsed2?.images;
1443
1784
  if (!Array.isArray(images)) continue;
1444
1785
  const dir = contentsPath.split("/").slice(0, -1).join("/");
1445
1786
  const pick = pickImagesetFile(images);
@@ -1448,19 +1789,19 @@ function enumerateBundleImages(paths, readText) {
1448
1789
  seen.add(name);
1449
1790
  table.push({ name, file: `${dir}/${pick.filename}`, scale: pick.scale });
1450
1791
  }
1451
- for (const path9 of paths) {
1452
- if (!isFlatResourceImage(path9)) continue;
1453
- const name = baseOf(path9).slice(0, -extOf(path9).length);
1792
+ for (const path11 of paths) {
1793
+ if (!isFlatResourceImage(path11)) continue;
1794
+ const name = baseOf(path11).slice(0, -extOf(path11).length);
1454
1795
  if (name === "" || seen.has(name)) continue;
1455
1796
  seen.add(name);
1456
- table.push({ name, file: path9, scale: flatScale(path9) });
1797
+ table.push({ name, file: path11, scale: flatScale(path11) });
1457
1798
  }
1458
1799
  return table;
1459
1800
  }
1460
1801
  function colorComponent(value) {
1461
1802
  if (typeof value !== "string") return null;
1462
- const parsed = value.startsWith("0x") ? Number.parseInt(value.slice(2), 16) / 255 : value.includes(".") ? Number.parseFloat(value) : Number.parseInt(value, 10) / 255;
1463
- return Number.isFinite(parsed) ? parsed : null;
1803
+ const parsed2 = value.startsWith("0x") ? Number.parseInt(value.slice(2), 16) / 255 : value.includes(".") ? Number.parseFloat(value) : Number.parseInt(value, 10) / 255;
1804
+ return Number.isFinite(parsed2) ? parsed2 : null;
1464
1805
  }
1465
1806
  function colorsetValue(color) {
1466
1807
  if (typeof color !== "object" || color === null) return null;
@@ -1482,7 +1823,7 @@ function colorsetValue(color) {
1482
1823
  }
1483
1824
  function enumerateBundleColors(paths, readText) {
1484
1825
  const table = {};
1485
- for (const contentsPath of paths.filter((path9) => baseOf(path9) === "Contents.json")) {
1826
+ for (const contentsPath of paths.filter((path11) => baseOf(path11) === "Contents.json")) {
1486
1827
  const name = catalogEntryName(contentsPath, ".colorset", readText);
1487
1828
  if (name === null || name in table) continue;
1488
1829
  let colors;
@@ -1501,12 +1842,12 @@ function enumerateBundleColors(paths, readText) {
1501
1842
  const idiom = Reflect.get(entry, "idiom");
1502
1843
  if (idiom !== "universal" && idiom !== "iphone") continue;
1503
1844
  const appearances = Reflect.get(entry, "appearances");
1504
- const list = Array.isArray(appearances) ? appearances : [];
1505
- if (list.some((item) => Reflect.get(item, "appearance") === "contrast")) continue;
1506
- const isDark = list.some(
1845
+ const list2 = Array.isArray(appearances) ? appearances : [];
1846
+ if (list2.some((item) => Reflect.get(item, "appearance") === "contrast")) continue;
1847
+ const isDark = list2.some(
1507
1848
  (item) => Reflect.get(item, "appearance") === "luminosity" && Reflect.get(item, "value") === "dark"
1508
1849
  );
1509
- if (list.length > 0 && !isDark) continue;
1850
+ if (list2.length > 0 && !isDark) continue;
1510
1851
  const value = colorsetValue(Reflect.get(entry, "color"));
1511
1852
  if (value === null) continue;
1512
1853
  if (isDark) dark = value;
@@ -1547,8 +1888,8 @@ function axisExtremes(points) {
1547
1888
  function pathBounds(d) {
1548
1889
  const xs = [];
1549
1890
  const ys = [];
1550
- for (const path9 of d)
1551
- (0, import_svgpath.default)(path9).abs().unshort().unarc().iterate((segment, _index, x, y) => {
1891
+ for (const path11 of d)
1892
+ (0, import_svgpath.default)(path11).abs().unshort().unarc().iterate((segment, _index, x, y) => {
1552
1893
  const [command, ...args] = segment;
1553
1894
  if (command === "M" || command === "L") {
1554
1895
  xs.push(Number(args[0]));
@@ -1575,7 +1916,7 @@ function guide(svg, id, axis) {
1575
1916
  }
1576
1917
  function enumerateBundleSymbols(paths, readText) {
1577
1918
  const table = {};
1578
- for (const contentsPath of paths.filter((path9) => baseOf(path9) === "Contents.json")) {
1919
+ for (const contentsPath of paths.filter((path11) => baseOf(path11) === "Contents.json")) {
1579
1920
  const name = catalogEntryName(contentsPath, ".symbolset", readText);
1580
1921
  if (name === null || name in table) continue;
1581
1922
  let symbols;
@@ -1608,8 +1949,8 @@ function enumerateBundleSymbols(paths, readText) {
1608
1949
  viewBox: "0 0 24 24",
1609
1950
  advance,
1610
1951
  box: [12 - advance / 2, 12 - tall / 2, advance, tall],
1611
- layers: d.map((path9) => ({
1612
- d: (0, import_svgpath.default)(path9).abs().scale(scale).translate(translateX, translateY).round(3).toString()
1952
+ layers: d.map((path11) => ({
1953
+ d: (0, import_svgpath.default)(path11).abs().scale(scale).translate(translateX, translateY).round(3).toString()
1613
1954
  }))
1614
1955
  };
1615
1956
  }
@@ -1619,7 +1960,7 @@ function enumerateBundleJson(paths) {
1619
1960
  const found = [];
1620
1961
  const seen = /* @__PURE__ */ new Set();
1621
1962
  const ordered = [...paths].filter(
1622
- (path9) => path9.split("/").includes("Resources") && path9.split("/").every((segment) => segment !== "" && segment !== "..") && (extOf(path9) === ".json" || extOf(path9) === ".xcstrings")
1963
+ (path11) => path11.split("/").includes("Resources") && path11.split("/").every((segment) => segment !== "" && segment !== "..") && (extOf(path11) === ".json" || extOf(path11) === ".xcstrings")
1623
1964
  ).sort((a, b) => {
1624
1965
  const aDepth = a.split("/").length;
1625
1966
  const bDepth = b.split("/").length;
@@ -1727,8 +2068,8 @@ function readSharedDesktopAuthSession() {
1727
2068
  const filepath = getSharedDesktopAuthFilePath();
1728
2069
  if (!(0, import_node_fs3.existsSync)(filepath)) return null;
1729
2070
  try {
1730
- const parsed = JSON.parse((0, import_node_fs3.readFileSync)(filepath, "utf8"));
1731
- const normalized = normalizeSession(parsed);
2071
+ const parsed2 = JSON.parse((0, import_node_fs3.readFileSync)(filepath, "utf8"));
2072
+ const normalized = normalizeSession(parsed2);
1732
2073
  if (!normalized) {
1733
2074
  (0, import_node_fs3.rmSync)(filepath, { force: true });
1734
2075
  return null;
@@ -1825,9 +2166,9 @@ function resolveContrastBackendOrigin(currentOrigin) {
1825
2166
  const origin = currentOrigin?.trim();
1826
2167
  if (!origin) return DEFAULT_CONTRAST_BACKEND_ORIGIN;
1827
2168
  try {
1828
- const parsed = new URL(origin);
1829
- if (isLoopbackHost(parsed.hostname) || isContrastBackendHost(parsed.hostname)) {
1830
- return parsed.origin;
2169
+ const parsed2 = new URL(origin);
2170
+ if (isLoopbackHost(parsed2.hostname) || isContrastBackendHost(parsed2.hostname)) {
2171
+ return parsed2.origin;
1831
2172
  }
1832
2173
  } catch {
1833
2174
  }
@@ -1849,7 +2190,7 @@ var import_promises = require("node:stream/promises");
1849
2190
  async function installVerifiedTarball(tarball) {
1850
2191
  const { url, digest, destDir, installedMarker, label } = tarball;
1851
2192
  const downloadDir = import_node_fs4.default.mkdtempSync(import_node_path5.default.join(import_node_os3.default.tmpdir(), "runtime-delivery-download-"));
1852
- const archivePath = import_node_path5.default.join(downloadDir, "archive.tar.gz");
2193
+ const archivePath = import_node_path5.default.join(downloadDir, "archive");
1853
2194
  import_node_fs4.default.mkdirSync(import_node_path5.default.dirname(destDir), { recursive: true });
1854
2195
  const tmpDir = import_node_fs4.default.mkdtempSync(
1855
2196
  import_node_path5.default.join(import_node_path5.default.dirname(destDir), `.installing-${import_node_path5.default.basename(destDir)}-`)
@@ -1862,7 +2203,8 @@ async function installVerifiedTarball(tarball) {
1862
2203
  `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
1863
2204
  );
1864
2205
  }
1865
- await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
2206
+ if (new URL(url).pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir);
2207
+ else await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
1866
2208
  if (!import_node_fs4.default.existsSync(import_node_path5.default.join(tmpDir, installedMarker))) {
1867
2209
  throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
1868
2210
  }
@@ -1924,41 +2266,47 @@ function digestFile(filePath, algorithm, encoding) {
1924
2266
  stream.on("end", () => resolve2(hash.digest(encoding)));
1925
2267
  });
1926
2268
  }
2269
+ function extractZip(zipPath, destDir) {
2270
+ return runExtractor("ditto", ["-x", "-k", zipPath, destDir]);
2271
+ }
1927
2272
  function extractTarball(tarPath, destDir, stripComponents) {
2273
+ const args = ["-xzf", tarPath, "-C", destDir];
2274
+ if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
2275
+ return runExtractor("tar", args);
2276
+ }
2277
+ function runExtractor(command, args) {
1928
2278
  return new Promise((resolve2, reject) => {
1929
- const args = ["-xzf", tarPath, "-C", destDir];
1930
- if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
1931
- const child = (0, import_node_child_process3.spawn)("tar", args, {
2279
+ const child = (0, import_node_child_process3.spawn)(command, args, {
1932
2280
  stdio: ["ignore", "inherit", "inherit"]
1933
2281
  });
1934
2282
  child.on("error", reject);
1935
2283
  child.on("exit", (code) => {
1936
2284
  if (code === 0) resolve2();
1937
- else reject(new Error(`tar exited with code ${code}`));
2285
+ else reject(new Error(`${command} exited with code ${code}`));
1938
2286
  });
1939
2287
  });
1940
2288
  }
1941
2289
 
1942
2290
  // src/swift-distribution.lock.json
1943
2291
  var swift_distribution_lock_default = {
1944
- id: "42c53105b2e06d39",
2292
+ id: "d27a9b6d2aee64d4",
1945
2293
  release: "swift-6.3-RELEASE",
1946
- wasmSdkId: "swift-6.3-RELEASE_wasm-peach-728c7263",
1947
- wasmSdkUrl: "https://r2.sootsim.com/swift-wasm-sdk/swift-6.3-RELEASE_wasm-peach-728c7263.artifactbundle.tar.gz",
1948
- wasmSdkChecksum: "5df8ab7be805d67d69d8dcd3ef7eec940b4eb1f3261410eba09d891ee170c559",
1949
- source: "d8c4bd1a0ffb45a9cad3fd15de02bc0d93e459fc",
2294
+ wasmSdkId: "swift-6.3-RELEASE_wasm-peach-41921598-peach-26be2317",
2295
+ wasmSdkUrl: "https://r2.sootsim.com/swift-wasm-sdk/swift-6.3-RELEASE_wasm-peach-41921598-peach-26be2317.artifactbundle.tar.gz",
2296
+ wasmSdkChecksum: "f34f29d9426f42b04d1c38585d61cf38ecb5357f4287c4843870bec63de6b08c",
2297
+ source: "8f9873608a950d832ec49cf4bbc32fb65689e5f7",
1950
2298
  hosts: {
1951
2299
  "darwin-arm64": {
1952
- sha256: "d58abb1193369130460267e9cc57330f13de28e7a3aa404aeb7b9323cbd29384",
1953
- size: 7115901
2300
+ sha256: "b7fa68565ae1be6ee7964390b4d07949228894ac4a06fe7f58e4238dd0650197",
2301
+ size: 19319227
1954
2302
  },
1955
2303
  "linux-x64": {
1956
- sha256: "1cdd181fdd228e9f928367820cd39db2e703a7af47a819f7d26ed77b96839309",
1957
- size: 7121403
2304
+ sha256: "733ebee3a16142c97575532daf49990df57171ede17de6530a9c5906471d96ca",
2305
+ size: 19324099
1958
2306
  },
1959
2307
  "linux-arm64": {
1960
- sha256: "288e3ff43c881a63ec201856a61a90de323e8aa01714d47be65e8cac98af1738",
1961
- size: 7120448
2308
+ sha256: "84b258d95a71536392f25d2afb8c40835df771594a2c0e42049ee33781ce78ad",
2309
+ size: 19323438
1962
2310
  }
1963
2311
  }
1964
2312
  };
@@ -2089,6 +2437,190 @@ function swiftModuleToolchain(root) {
2089
2437
  };
2090
2438
  }
2091
2439
 
2440
+ // src/swift-remote-packages.ts
2441
+ var import_node_child_process5 = require("node:child_process");
2442
+ var import_node_fs7 = __toESM(require("node:fs"), 1);
2443
+ var import_node_path8 = __toESM(require("node:path"), 1);
2444
+ var REMOTE_CHECKOUTS = import_node_path8.default.join(".build", "peach", "checkouts");
2445
+ var C_FAMILY = /\.(c|cc|cpp|cxx|m|mm|s|S)$/;
2446
+ function readPins(resolved) {
2447
+ const data = JSON.parse(import_node_fs7.default.readFileSync(resolved, "utf8"));
2448
+ const pins = data && typeof data === "object" && "pins" in data && Array.isArray(data.pins) ? data.pins : null;
2449
+ if (!pins)
2450
+ throw new Error(`${resolved} has no pins; resolve packages in a current Xcode`);
2451
+ const out = /* @__PURE__ */ new Map();
2452
+ for (const pin of pins) {
2453
+ const identity = pin?.identity;
2454
+ const location = pin?.location;
2455
+ const revision = pin?.state?.revision;
2456
+ if (typeof identity === "string" && typeof location === "string" && typeof revision === "string")
2457
+ out.set(identity, { location, revision });
2458
+ }
2459
+ return out;
2460
+ }
2461
+ function walk(dir) {
2462
+ if (!import_node_fs7.default.existsSync(dir)) return [];
2463
+ const out = [];
2464
+ for (const entry of import_node_fs7.default.readdirSync(dir, { withFileTypes: true })) {
2465
+ if (entry.name.startsWith(".")) continue;
2466
+ const full = import_node_path8.default.join(dir, entry.name);
2467
+ if (entry.isDirectory()) out.push(...walk(full));
2468
+ else if (entry.isFile()) out.push(full);
2469
+ }
2470
+ return out.sort();
2471
+ }
2472
+ var verified2 = /* @__PURE__ */ new Set();
2473
+ function checkout(checkouts, identity, pin) {
2474
+ const dir = import_node_path8.default.join(checkouts, identity);
2475
+ const key = `${dir}\0${pin.revision}`;
2476
+ if (verified2.has(key)) return dir;
2477
+ const git = (...args) => (0, import_node_child_process5.execFileSync)("git", ["-C", dir, ...args], {
2478
+ encoding: "utf8",
2479
+ stdio: ["ignore", "pipe", "pipe"]
2480
+ }).trim();
2481
+ const current = import_node_fs7.default.existsSync(import_node_path8.default.join(dir, ".git")) ? git("rev-parse", "HEAD") : "";
2482
+ if (current !== pin.revision) {
2483
+ import_node_fs7.default.rmSync(dir, { recursive: true, force: true });
2484
+ import_node_fs7.default.mkdirSync(dir, { recursive: true });
2485
+ try {
2486
+ git("init", "-q");
2487
+ git("fetch", "-q", "--depth", "1", pin.location, pin.revision);
2488
+ git("checkout", "-q", "FETCH_HEAD");
2489
+ } catch (error) {
2490
+ import_node_fs7.default.rmSync(dir, { recursive: true, force: true });
2491
+ const stderr = error instanceof Error && "stderr" in error ? String(error.stderr).trim() : "";
2492
+ throw new Error(
2493
+ `could not fetch ${pin.location} at ${pin.revision}${stderr ? `: ${stderr}` : ""}`
2494
+ );
2495
+ }
2496
+ }
2497
+ verified2.add(key);
2498
+ return dir;
2499
+ }
2500
+ function resolveRemotePackages(projectDir, resolved, products, provided) {
2501
+ const result = { targets: [], unavailable: /* @__PURE__ */ new Map() };
2502
+ const wanted = products.filter((entry) => !provided.has(entry.product));
2503
+ if (wanted.length === 0) return result;
2504
+ if (!resolved) {
2505
+ for (const entry of wanted)
2506
+ result.unavailable.set(entry.product, {
2507
+ repositoryURL: entry.repositoryURL,
2508
+ reason: "no Package.resolved pins it; resolve packages in Xcode once"
2509
+ });
2510
+ return result;
2511
+ }
2512
+ const pins = readPins(resolved);
2513
+ const checkouts = import_node_path8.default.join(projectDir, REMOTE_CHECKOUTS);
2514
+ import_node_fs7.default.mkdirSync(checkouts, { recursive: true });
2515
+ import_node_fs7.default.writeFileSync(import_node_path8.default.join(import_node_path8.default.dirname(checkouts), ".gitignore"), "*\n");
2516
+ const packages = /* @__PURE__ */ new Map();
2517
+ const load2 = (identity) => {
2518
+ const cached = packages.get(identity);
2519
+ if (cached) return cached;
2520
+ const pin = pins.get(identity);
2521
+ if (!pin) return null;
2522
+ const dir = checkout(checkouts, identity, pin);
2523
+ const manifest = import_node_fs7.default.readFileSync(import_node_path8.default.join(dir, "Package.swift"), "utf8");
2524
+ const loaded = { dir, manifest, graph: swiftManifestGraph(manifest) };
2525
+ packages.set(identity, loaded);
2526
+ return loaded;
2527
+ };
2528
+ const targets = /* @__PURE__ */ new Map();
2529
+ const outcomes = /* @__PURE__ */ new Map();
2530
+ const resolveProduct = (identity, product) => {
2531
+ const key = `${identity}\0${product}`;
2532
+ if (outcomes.has(key)) return outcomes.get(key);
2533
+ outcomes.set(key, null);
2534
+ const pkg = load2(identity);
2535
+ if (!pkg) {
2536
+ outcomes.set(key, `package ${identity} is not pinned in Package.resolved`);
2537
+ return outcomes.get(key);
2538
+ }
2539
+ const roots = pkg.graph.products.get(product);
2540
+ if (!roots) {
2541
+ outcomes.set(key, `package ${identity} has no library ${product}`);
2542
+ return outcomes.get(key);
2543
+ }
2544
+ const declared = new Map(
2545
+ swiftManifestTargets(pkg.manifest).map((target) => [target.name, target])
2546
+ );
2547
+ const reached = [];
2548
+ const seen = /* @__PURE__ */ new Set();
2549
+ const pending = [...roots];
2550
+ let reason = null;
2551
+ while (pending.length > 0 && !reason) {
2552
+ const name = pending.pop();
2553
+ if (seen.has(name) || provided.has(name)) continue;
2554
+ seen.add(name);
2555
+ if (pkg.graph.binaryTargets.has(name)) {
2556
+ reason = `${name} is a binary framework`;
2557
+ break;
2558
+ }
2559
+ if (pkg.graph.systemLibraries.has(name)) {
2560
+ reason = `${name} is a system C library`;
2561
+ break;
2562
+ }
2563
+ const target = declared.get(name);
2564
+ if (!target) {
2565
+ reason = `${identity} declares no target ${name}`;
2566
+ break;
2567
+ }
2568
+ const files = walk(import_node_path8.default.join(pkg.dir, target.path));
2569
+ if (files.some((file) => C_FAMILY.test(file))) {
2570
+ reason = `${name} is a C or Objective-C target`;
2571
+ break;
2572
+ }
2573
+ reached.push(target);
2574
+ for (const dependency of pkg.graph.dependencies.get(name) ?? []) {
2575
+ if (dependency.kind === "target") pending.push(dependency.name);
2576
+ else if (!provided.has(dependency.name)) {
2577
+ const url = pkg.graph.packageURLs.get(dependency.package);
2578
+ const nested = resolveProduct(
2579
+ url ? swiftPackageIdentity(url) : dependency.package,
2580
+ dependency.name
2581
+ );
2582
+ if (nested) reason = `${dependency.name}: ${nested}`;
2583
+ }
2584
+ }
2585
+ }
2586
+ if (reason) {
2587
+ outcomes.set(key, reason);
2588
+ return reason;
2589
+ }
2590
+ const relative = reached.flatMap(
2591
+ (target) => walk(import_node_path8.default.join(pkg.dir, target.path)).map(
2592
+ (file) => import_node_path8.default.relative(pkg.dir, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep)
2593
+ )
2594
+ );
2595
+ const withResources = new Map(
2596
+ swiftManifestTargets(pkg.manifest, relative).map((target) => [target.name, target])
2597
+ );
2598
+ for (const target of reached) {
2599
+ const dir = import_node_path8.default.join(pkg.dir, target.path);
2600
+ targets.set(target.name, {
2601
+ ...withResources.get(target.name) ?? target,
2602
+ executable: false,
2603
+ dir,
2604
+ files: walk(dir)
2605
+ });
2606
+ }
2607
+ return null;
2608
+ };
2609
+ for (const entry of wanted) {
2610
+ const reason = resolveProduct(
2611
+ swiftPackageIdentity(entry.repositoryURL),
2612
+ entry.product
2613
+ );
2614
+ if (reason)
2615
+ result.unavailable.set(entry.product, {
2616
+ repositoryURL: entry.repositoryURL,
2617
+ reason
2618
+ });
2619
+ }
2620
+ result.targets = [...targets.values()];
2621
+ return result;
2622
+ }
2623
+
2092
2624
  // src/swift-submit.ts
2093
2625
  var SWIFT_COMPILE_PATH = "/api/swift-compile";
2094
2626
  var MAX_SWIFT_COMPILE_FILES = 256;
@@ -2099,7 +2631,7 @@ var MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES = 8 * 1024 * 1024;
2099
2631
  var MAX_SWIFT_COMPILE_IMAGES = 128;
2100
2632
  var MAX_SWIFT_COMPILE_IMAGE_BYTES = 4 * 1024 * 1024;
2101
2633
  var MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES = 16 * 1024 * 1024;
2102
- var SWIFT_HOST_ABI = 21;
2634
+ var SWIFT_HOST_ABI = 24;
2103
2635
  var POLL_INTERVAL_MS = 1500;
2104
2636
  function swiftNativeEntry(native, file) {
2105
2637
  return {
@@ -2225,6 +2757,383 @@ async function compileSwiftProject(submit, work, origin, signal) {
2225
2757
  }
2226
2758
  }
2227
2759
 
2760
+ // src/xcode-project.ts
2761
+ var import_node_fs8 = __toESM(require("node:fs"), 1);
2762
+ var import_node_path9 = __toESM(require("node:path"), 1);
2763
+ function parseOpenStepPlist(text) {
2764
+ let i = 0;
2765
+ const fail = (message) => {
2766
+ const line = text.slice(0, i).split("\n").length;
2767
+ throw new Error(`project.pbxproj line ${line}: ${message}`);
2768
+ };
2769
+ const skip = () => {
2770
+ for (; ; ) {
2771
+ const ch = text[i];
2772
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") i++;
2773
+ else if (ch === "/" && text[i + 1] === "*") {
2774
+ const end = text.indexOf("*/", i + 2);
2775
+ if (end < 0) fail("unterminated comment");
2776
+ i = end + 2;
2777
+ } else if (ch === "/" && text[i + 1] === "/") {
2778
+ const end = text.indexOf("\n", i);
2779
+ i = end < 0 ? text.length : end + 1;
2780
+ } else return;
2781
+ }
2782
+ };
2783
+ const quoted = () => {
2784
+ i++;
2785
+ let out = "";
2786
+ for (; ; ) {
2787
+ const ch = text[i++];
2788
+ if (ch === void 0) fail("unterminated string");
2789
+ if (ch === '"') return out;
2790
+ if (ch !== "\\") {
2791
+ out += ch;
2792
+ continue;
2793
+ }
2794
+ const next = text[i++];
2795
+ if (next === "n") out += "\n";
2796
+ else if (next === "t") out += " ";
2797
+ else if (next === "r") out += "\r";
2798
+ else if (next === "U") {
2799
+ out += String.fromCharCode(parseInt(text.slice(i, i + 4), 16));
2800
+ i += 4;
2801
+ } else out += next;
2802
+ }
2803
+ };
2804
+ const value = () => {
2805
+ skip();
2806
+ const ch = text[i];
2807
+ if (ch === "{") {
2808
+ i++;
2809
+ const dict = {};
2810
+ for (; ; ) {
2811
+ skip();
2812
+ if (text[i] === "}") {
2813
+ i++;
2814
+ return dict;
2815
+ }
2816
+ const key = value();
2817
+ if (typeof key !== "string") fail("dictionary key is not a string");
2818
+ skip();
2819
+ if (text[i++] !== "=") fail("expected =");
2820
+ dict[key] = value();
2821
+ skip();
2822
+ if (text[i++] !== ";") fail("expected ;");
2823
+ }
2824
+ }
2825
+ if (ch === "(") {
2826
+ i++;
2827
+ const list2 = [];
2828
+ for (; ; ) {
2829
+ skip();
2830
+ if (text[i] === ")") {
2831
+ i++;
2832
+ return list2;
2833
+ }
2834
+ list2.push(value());
2835
+ skip();
2836
+ if (text[i] === ",") i++;
2837
+ else if (text[i] !== ")") fail("expected , or )");
2838
+ }
2839
+ }
2840
+ if (ch === '"') return quoted();
2841
+ const start = i;
2842
+ while (i < text.length && /[A-Za-z0-9_$+/:.\-<>]/.test(text[i])) i++;
2843
+ if (i === start) fail(`unexpected ${JSON.stringify(ch ?? "end of file")}`);
2844
+ return text.slice(start, i);
2845
+ };
2846
+ if (text.startsWith("// !$*UTF8*$!")) i = text.indexOf("\n") + 1;
2847
+ const root = value();
2848
+ skip();
2849
+ if (i !== text.length) fail("trailing content");
2850
+ return root;
2851
+ }
2852
+ var isDict = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2853
+ var str = (value) => typeof value === "string" ? value : void 0;
2854
+ var list = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
2855
+ var APPLICATION = "com.apple.product-type.application";
2856
+ var NEVER_MEMBER = /(?:^|\/)(?:Info\.plist|[^/]+\.entitlements|[^/]+\.xcconfig|\.DS_Store)$/;
2857
+ var BUNDLE_DIR = /\.(xcassets|bundle|lproj|xcdatamodeld|scnassets|spriteatlas|rcproject|storyboardc|icon)$/;
2858
+ function walkFiles(dir) {
2859
+ if (!import_node_fs8.default.existsSync(dir)) return [];
2860
+ const out = [];
2861
+ for (const entry of import_node_fs8.default.readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
2862
+ if (entry.name.startsWith(".")) continue;
2863
+ const full = import_node_path9.default.join(dir, entry.name);
2864
+ if (entry.isDirectory()) out.push(...walkFiles(full));
2865
+ else if (entry.isFile()) out.push(full);
2866
+ }
2867
+ return out;
2868
+ }
2869
+ function readXcconfig(file, seen = /* @__PURE__ */ new Set()) {
2870
+ if (seen.has(file) || !import_node_fs8.default.existsSync(file)) return {};
2871
+ seen.add(file);
2872
+ const settings = {};
2873
+ for (const raw2 of import_node_fs8.default.readFileSync(file, "utf8").split("\n")) {
2874
+ const line = raw2.replace(/\/\/.*$/, "").trim();
2875
+ const include = /^#include\??\s+"([^"]+)"/.exec(line);
2876
+ if (include) {
2877
+ Object.assign(
2878
+ settings,
2879
+ readXcconfig(import_node_path9.default.resolve(import_node_path9.default.dirname(file), include[1]), seen)
2880
+ );
2881
+ continue;
2882
+ }
2883
+ const setting = /^([A-Z_][A-Z0-9_]*)(?:\[[^\]]*\])?\s*=\s*(.*)$/.exec(line);
2884
+ if (setting) settings[setting[1]] = setting[2].trim();
2885
+ }
2886
+ return settings;
2887
+ }
2888
+ function c99Identifier(name) {
2889
+ const id = name.replace(/[^A-Za-z0-9_]/g, "_");
2890
+ return /^[0-9]/.test(id) ? `_${id}` : id;
2891
+ }
2892
+ var parsed = /* @__PURE__ */ new Map();
2893
+ function readProject(pbxproj) {
2894
+ const mtimeMs = import_node_fs8.default.statSync(pbxproj).mtimeMs;
2895
+ const cached = parsed.get(pbxproj);
2896
+ if (cached?.mtimeMs === mtimeMs) return cached.root;
2897
+ const root = parseOpenStepPlist(import_node_fs8.default.readFileSync(pbxproj, "utf8"));
2898
+ if (!isDict(root) || !isDict(root.objects)) {
2899
+ throw new Error(`${pbxproj} has no objects table`);
2900
+ }
2901
+ parsed.set(pbxproj, { mtimeMs, root });
2902
+ return root;
2903
+ }
2904
+ function readXcodeAppTarget(xcodeproj, targetName) {
2905
+ const pbxproj = import_node_path9.default.join(xcodeproj, "project.pbxproj");
2906
+ if (!import_node_fs8.default.existsSync(pbxproj)) throw new Error(`${xcodeproj} has no project.pbxproj`);
2907
+ const root = readProject(pbxproj);
2908
+ const objects = root.objects;
2909
+ const object = (id) => {
2910
+ const found = id === void 0 ? void 0 : objects[id];
2911
+ return isDict(found) ? found : void 0;
2912
+ };
2913
+ const project = object(str(root.rootObject));
2914
+ if (!project || project.isa !== "PBXProject") {
2915
+ throw new Error(`${pbxproj} has no PBXProject root`);
2916
+ }
2917
+ const projectDir = import_node_fs8.default.realpathSync(
2918
+ import_node_path9.default.resolve(import_node_path9.default.dirname(xcodeproj), str(project.projectDirPath) ?? "")
2919
+ );
2920
+ const parent = /* @__PURE__ */ new Map();
2921
+ for (const [id, entry] of Object.entries(objects)) {
2922
+ if (!isDict(entry)) continue;
2923
+ if (entry.isa === "PBXGroup" || entry.isa === "PBXVariantGroup") {
2924
+ for (const child of list(entry.children)) parent.set(child, id);
2925
+ }
2926
+ }
2927
+ const resolvedPaths = /* @__PURE__ */ new Map();
2928
+ const resolvePath = (id) => {
2929
+ if (resolvedPaths.has(id)) return resolvedPaths.get(id);
2930
+ const entry = object(id);
2931
+ let result = null;
2932
+ if (entry) {
2933
+ const own = str(entry.path) ?? "";
2934
+ const tree = str(entry.sourceTree) ?? "<group>";
2935
+ if (tree === "<absolute>") result = own;
2936
+ else if (tree === "SOURCE_ROOT") result = import_node_path9.default.join(projectDir, own);
2937
+ else if (tree === "<group>") {
2938
+ const up = parent.get(id);
2939
+ const base = up ? resolvePath(up) : projectDir;
2940
+ result = base === null ? null : import_node_path9.default.join(base, own);
2941
+ }
2942
+ }
2943
+ resolvedPaths.set(id, result);
2944
+ return result;
2945
+ };
2946
+ const targets = list(project.targets).map((id) => ({ id, target: object(id) })).filter(
2947
+ (entry) => entry.target?.isa === "PBXNativeTarget"
2948
+ );
2949
+ const appTargets = targets.filter((entry) => entry.target.productType === APPLICATION);
2950
+ const appTargetNames = appTargets.map((entry) => str(entry.target.name) ?? entry.id);
2951
+ const chosen = targetName ? appTargets.find((entry) => entry.target.name === targetName) : appTargets.length === 1 ? appTargets[0] : void 0;
2952
+ if (!chosen) {
2953
+ throw new Error(
2954
+ targetName ? `${import_node_path9.default.basename(xcodeproj)} has no application target ${targetName}; it has ${appTargetNames.join(", ") || "none"}` : `${import_node_path9.default.basename(xcodeproj)} has ${appTargetNames.length} application targets (${appTargetNames.join(", ") || "none"}); pass --target`
2955
+ );
2956
+ }
2957
+ const { id: targetId, target } = chosen;
2958
+ const configSettings = (listId) => {
2959
+ const configs = list(object(listId)?.buildConfigurations).map(object);
2960
+ const config = configs.find((entry) => entry?.name === "Debug") ?? configs.find(Boolean);
2961
+ if (!config) return {};
2962
+ const base = str(config.baseConfigurationReference);
2963
+ const fromFile = base ? readXcconfig(resolvePath(base) ?? "") : {};
2964
+ const own = isDict(config.buildSettings) ? config.buildSettings : {};
2965
+ return {
2966
+ ...fromFile,
2967
+ ...Object.fromEntries(
2968
+ Object.entries(own).flatMap(
2969
+ ([key, value]) => typeof value === "string" ? [[key, value]] : []
2970
+ )
2971
+ )
2972
+ };
2973
+ };
2974
+ const settings = {
2975
+ ...configSettings(str(project.buildConfigurationList)),
2976
+ ...configSettings(str(target.buildConfigurationList))
2977
+ };
2978
+ const name = str(target.name) ?? targetId;
2979
+ const productName = (settings.PRODUCT_NAME ?? "$(TARGET_NAME)").replaceAll("$(TARGET_NAME)", name).replaceAll("${TARGET_NAME}", name);
2980
+ const moduleName = c99Identifier(
2981
+ settings.PRODUCT_MODULE_NAME && !settings.PRODUCT_MODULE_NAME.includes("$(") ? settings.PRODUCT_MODULE_NAME : productName
2982
+ );
2983
+ const sources = /* @__PURE__ */ new Set();
2984
+ const resources = /* @__PURE__ */ new Set();
2985
+ const addResource = (file) => {
2986
+ if (import_node_fs8.default.existsSync(file) && import_node_fs8.default.statSync(file).isDirectory()) {
2987
+ for (const inner of walkFiles(file)) resources.add(inner);
2988
+ } else if (import_node_fs8.default.existsSync(file)) resources.add(file);
2989
+ };
2990
+ const fileRefPaths = (refId) => {
2991
+ const ref = object(refId);
2992
+ if (!ref) return [];
2993
+ if (ref.isa === "PBXVariantGroup") {
2994
+ return list(ref.children).flatMap((child) => {
2995
+ const resolved2 = resolvePath(child);
2996
+ return resolved2 ? [resolved2] : [];
2997
+ });
2998
+ }
2999
+ const resolved = resolvePath(refId);
3000
+ return resolved ? [resolved] : [];
3001
+ };
3002
+ for (const phaseId of list(target.buildPhases)) {
3003
+ const phase = object(phaseId);
3004
+ if (phase?.isa !== "PBXSourcesBuildPhase" && phase?.isa !== "PBXResourcesBuildPhase")
3005
+ continue;
3006
+ for (const buildFileId of list(phase.files)) {
3007
+ for (const file of fileRefPaths(str(object(buildFileId)?.fileRef) ?? "")) {
3008
+ if (phase.isa === "PBXSourcesBuildPhase" && file.endsWith(".swift")) {
3009
+ if (import_node_fs8.default.existsSync(file)) sources.add(file);
3010
+ } else if (phase.isa === "PBXResourcesBuildPhase") addResource(file);
3011
+ }
3012
+ }
3013
+ }
3014
+ const addSynchronized = (folder, relative) => {
3015
+ const file = import_node_path9.default.join(folder, relative);
3016
+ if (NEVER_MEMBER.test(relative)) return;
3017
+ if (file.endsWith(".swift")) {
3018
+ if (!relative.split("/").some((segment) => BUNDLE_DIR.test(segment)))
3019
+ sources.add(file);
3020
+ } else if (/\.(h|m|mm|c|cpp|metal)$/.test(file)) {
3021
+ return;
3022
+ } else resources.add(file);
3023
+ };
3024
+ const owned = new Set(list(target.fileSystemSynchronizedGroups));
3025
+ for (const [groupId, group] of Object.entries(objects)) {
3026
+ if (!isDict(group) || group.isa !== "PBXFileSystemSynchronizedRootGroup") continue;
3027
+ const folder = resolvePath(groupId);
3028
+ if (!folder) continue;
3029
+ const exceptions = /* @__PURE__ */ new Set();
3030
+ for (const exceptionId of list(group.exceptions)) {
3031
+ const exception = object(exceptionId);
3032
+ if (exception?.target !== targetId) continue;
3033
+ for (const relative of list(exception.membershipExceptions))
3034
+ exceptions.add(relative);
3035
+ }
3036
+ if (owned.has(groupId)) {
3037
+ for (const file of walkFiles(folder)) {
3038
+ const relative = import_node_path9.default.relative(folder, file).split(import_node_path9.default.sep).join("/");
3039
+ if ([...exceptions].some(
3040
+ (exception) => relative === exception || relative.startsWith(`${exception}/`)
3041
+ ))
3042
+ continue;
3043
+ addSynchronized(folder, relative);
3044
+ }
3045
+ } else {
3046
+ for (const relative of exceptions) {
3047
+ const file = import_node_path9.default.join(folder, relative);
3048
+ if (import_node_fs8.default.existsSync(file) && import_node_fs8.default.statSync(file).isDirectory()) {
3049
+ for (const inner of walkFiles(file))
3050
+ addSynchronized(
3051
+ folder,
3052
+ import_node_path9.default.relative(folder, inner).split(import_node_path9.default.sep).join("/")
3053
+ );
3054
+ } else if (import_node_fs8.default.existsSync(file)) addSynchronized(folder, relative);
3055
+ }
3056
+ }
3057
+ }
3058
+ const localPackageDirs = Object.entries(objects).flatMap(([id, entry]) => {
3059
+ if (!isDict(entry)) return [];
3060
+ const candidate = entry.isa === "XCLocalSwiftPackageReference" ? import_node_path9.default.resolve(projectDir, str(entry.relativePath) ?? "") : entry.isa === "PBXFileReference" && entry.lastKnownFileType === "wrapper" ? resolvePath(id) : null;
3061
+ return candidate && import_node_fs8.default.existsSync(import_node_path9.default.join(candidate, "Package.swift")) ? [candidate] : [];
3062
+ });
3063
+ const graphs = /* @__PURE__ */ new Map();
3064
+ const graphOf = (dir) => {
3065
+ const cached = graphs.get(dir);
3066
+ if (cached) return cached;
3067
+ const graph = swiftManifestGraph(
3068
+ import_node_fs8.default.readFileSync(import_node_path9.default.join(dir, "Package.swift"), "utf8")
3069
+ );
3070
+ graphs.set(dir, graph);
3071
+ return graph;
3072
+ };
3073
+ const localProducts = /* @__PURE__ */ new Map();
3074
+ for (const dir of localPackageDirs) {
3075
+ for (const product of graphOf(dir).products.keys()) localProducts.set(product, dir);
3076
+ }
3077
+ const localPackages = /* @__PURE__ */ new Set();
3078
+ const remoteProducts = [];
3079
+ const unresolvedProducts = [];
3080
+ for (const dependencyId of list(target.packageProductDependencies)) {
3081
+ const dependency = object(dependencyId);
3082
+ const product = str(dependency?.productName);
3083
+ if (!dependency || !product) continue;
3084
+ const reference = object(str(dependency.package));
3085
+ if (reference?.isa === "XCRemoteSwiftPackageReference") {
3086
+ remoteProducts.push({ product, repositoryURL: str(reference.repositoryURL) ?? "" });
3087
+ } else if (reference?.isa === "XCLocalSwiftPackageReference") {
3088
+ localPackages.add(import_node_path9.default.resolve(projectDir, str(reference.relativePath) ?? ""));
3089
+ } else if (localProducts.has(product)) {
3090
+ localPackages.add(localProducts.get(product));
3091
+ } else unresolvedProducts.push(product);
3092
+ }
3093
+ const pending = [...localPackages];
3094
+ while (pending.length > 0) {
3095
+ const dir = pending.pop();
3096
+ const graph = graphOf(dir);
3097
+ for (const relative of graph.packagePaths) {
3098
+ const next = import_node_path9.default.resolve(dir, relative);
3099
+ if (localPackages.has(next) || !import_node_fs8.default.existsSync(import_node_path9.default.join(next, "Package.swift")))
3100
+ continue;
3101
+ localPackages.add(next);
3102
+ pending.push(next);
3103
+ }
3104
+ for (const dependencies of graph.dependencies.values()) {
3105
+ for (const dependency of dependencies) {
3106
+ if (dependency.kind !== "product") continue;
3107
+ const url = graph.packageURLs.get(dependency.package);
3108
+ if (url && !remoteProducts.some((entry) => entry.product === dependency.name))
3109
+ remoteProducts.push({ product: dependency.name, repositoryURL: url });
3110
+ }
3111
+ }
3112
+ }
3113
+ const packageResolved = [
3114
+ import_node_path9.default.join(xcodeproj, "project.xcworkspace"),
3115
+ ...import_node_fs8.default.readdirSync(projectDir).filter((entry) => entry.endsWith(".xcworkspace")).map((entry) => import_node_path9.default.join(projectDir, entry))
3116
+ ].map(
3117
+ (workspace) => import_node_path9.default.join(workspace, "xcshareddata", "swiftpm", "Package.resolved")
3118
+ ).find((file) => import_node_fs8.default.existsSync(file)) ?? null;
3119
+ const swiftVersion = Number.parseFloat(settings.SWIFT_VERSION ?? "5");
3120
+ return {
3121
+ projectDir,
3122
+ pbxproj,
3123
+ name,
3124
+ moduleName,
3125
+ sources: [...sources].sort(),
3126
+ resources: [...resources].sort(),
3127
+ languageMode: swiftVersion >= 6 ? 6 : 5,
3128
+ mainActorIsolation: settings.SWIFT_DEFAULT_ACTOR_ISOLATION === "MainActor",
3129
+ localPackages: [...localPackages].sort(),
3130
+ remoteProducts,
3131
+ packageResolved,
3132
+ unresolvedProducts,
3133
+ appTargets: appTargetNames
3134
+ };
3135
+ }
3136
+
2228
3137
  // src/swift-host.ts
2229
3138
  var ARTIFACT_PATH = "/__peach/swift/";
2230
3139
  var RESOURCE_PATH = "/__peach/swift-res/";
@@ -2240,17 +3149,17 @@ var SKIP_SOURCE_DIRS = /* @__PURE__ */ new Set([
2240
3149
  var NATIVE_DESCRIPTOR = ".one-native-source.json";
2241
3150
  var NATIVE_GLUE = ".one-native-source.swift.txt";
2242
3151
  function swiftPackageId(packagePath) {
2243
- return import_node_path8.default.basename(packagePath).replace(/[^A-Za-z0-9_]/g, "_").replace(/^(\d)/, "_$1");
3152
+ return import_node_path10.default.basename(packagePath).replace(/[^A-Za-z0-9_]/g, "_").replace(/^(\d)/, "_$1");
2244
3153
  }
2245
3154
  function nativeSourceDescriptor(packagePath) {
2246
- packagePath = import_node_fs7.default.realpathSync(packagePath);
2247
- const file = import_node_path8.default.join(packagePath, NATIVE_DESCRIPTOR);
2248
- if (!import_node_fs7.default.existsSync(file)) return null;
3155
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
3156
+ const file = import_node_path10.default.join(packagePath, NATIVE_DESCRIPTOR);
3157
+ if (!import_node_fs9.default.existsSync(file)) return null;
2249
3158
  const value = JSON.parse(
2250
3159
  readPackageFile(packagePath, file, MAX_SWIFT_COMPILE_SOURCE_BYTES).toString("utf8")
2251
3160
  );
2252
3161
  const invalid = () => new Error(`${file}: invalid One native source descriptor; run one typegen`);
2253
- if (!value || typeof value !== "object" || Reflect.get(value, "generatedBy") !== "one typegen" || !import_node_fs7.default.existsSync(import_node_path8.default.join(packagePath, NATIVE_GLUE))) {
3162
+ if (!value || typeof value !== "object" || Reflect.get(value, "generatedBy") !== "one typegen" || !import_node_fs9.default.existsSync(import_node_path10.default.join(packagePath, NATIVE_GLUE))) {
2254
3163
  throw invalid();
2255
3164
  }
2256
3165
  if (!isSwiftNativeModules(value) || value.packageId !== swiftPackageId(packagePath)) {
@@ -2259,12 +3168,12 @@ function nativeSourceDescriptor(packagePath) {
2259
3168
  return value;
2260
3169
  }
2261
3170
  function nativeSourceFiles(packagePath) {
2262
- packagePath = import_node_fs7.default.realpathSync(packagePath);
2263
- return [NATIVE_DESCRIPTOR, NATIVE_GLUE].map((name) => import_node_path8.default.join(packagePath, name)).filter((file) => import_node_fs7.default.existsSync(file));
3171
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
3172
+ return [NATIVE_DESCRIPTOR, NATIVE_GLUE].map((name) => import_node_path10.default.join(packagePath, name)).filter((file) => import_node_fs9.default.existsSync(file));
2264
3173
  }
2265
3174
  var projects = /* @__PURE__ */ new Map();
2266
3175
  function projectFor(packagePath, hosted) {
2267
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3176
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2268
3177
  const existing = projects.get(packagePath);
2269
3178
  if (existing) {
2270
3179
  if (hosted && !existing.hosted) {
@@ -2284,52 +3193,130 @@ function projectFor(packagePath, hosted) {
2284
3193
  projects.set(packagePath, created);
2285
3194
  return created;
2286
3195
  }
3196
+ var xcodeProjects = /* @__PURE__ */ new Map();
3197
+ function remotePackages(entry, app) {
3198
+ if (!entry.provided) return { targets: [], unavailable: /* @__PURE__ */ new Map() };
3199
+ const key = JSON.stringify([
3200
+ app.remoteProducts,
3201
+ app.packageResolved,
3202
+ app.packageResolved ? import_node_fs9.default.statSync(app.packageResolved).mtimeMs : 0
3203
+ ]);
3204
+ if (entry.remote?.key !== key) {
3205
+ entry.remote = {
3206
+ key,
3207
+ packages: resolveRemotePackages(
3208
+ import_node_fs9.default.realpathSync(app.projectDir),
3209
+ app.packageResolved,
3210
+ app.remoteProducts,
3211
+ entry.provided
3212
+ )
3213
+ };
3214
+ }
3215
+ return entry.remote.packages;
3216
+ }
3217
+ var XCODE_APP_DIR = "__app__";
3218
+ var XCODE_PACKAGES_DIR = "__packages__";
3219
+ var CHECKOUTS_PREFIX = `${REMOTE_CHECKOUTS.split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)}/`;
3220
+ function xcodeInputKey(appSources, file, relative) {
3221
+ if (appSources.has(file)) return import_node_path10.default.posix.join(XCODE_APP_DIR, relative);
3222
+ return relative.startsWith(CHECKOUTS_PREFIX) ? import_node_path10.default.posix.join(XCODE_PACKAGES_DIR, relative.slice(CHECKOUTS_PREFIX.length)) : relative;
3223
+ }
3224
+ function xcodeLayout(root) {
3225
+ const registered = xcodeProjects.get(root);
3226
+ if (!registered) return null;
3227
+ const app = readXcodeAppTarget(registered.xcodeproj, registered.target);
3228
+ const files = /* @__PURE__ */ new Set([app.pbxproj, ...app.sources, ...app.resources]);
3229
+ const targets = [];
3230
+ for (const dir of app.localPackages) {
3231
+ const manifest = import_node_path10.default.join(dir, "Package.swift");
3232
+ files.add(manifest);
3233
+ const prefix = import_node_path10.default.relative(root, dir).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep);
3234
+ const all = packageFiles(dir).map(
3235
+ (file) => import_node_path10.default.relative(dir, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
3236
+ );
3237
+ for (const target of swiftManifestTargets(import_node_fs9.default.readFileSync(manifest, "utf8"), all)) {
3238
+ if (target.executable) continue;
3239
+ targets.push({ ...target, path: import_node_path10.default.posix.join(prefix, target.path) });
3240
+ for (const relative of all) {
3241
+ if (relative.startsWith(`${target.path}/`)) files.add(import_node_path10.default.join(dir, relative));
3242
+ }
3243
+ }
3244
+ }
3245
+ const remote = remotePackages(registered, app);
3246
+ for (const target of remote.targets) {
3247
+ targets.push({
3248
+ ...target,
3249
+ path: import_node_path10.default.posix.join(
3250
+ XCODE_PACKAGES_DIR,
3251
+ import_node_path10.default.relative(import_node_path10.default.join(root, REMOTE_CHECKOUTS), target.dir).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
3252
+ )
3253
+ });
3254
+ for (const file of target.files) files.add(file);
3255
+ }
3256
+ return { app, targets, unavailable: remote.unavailable, files: [...files].sort() };
3257
+ }
3258
+ function xcodeManifest(layout) {
3259
+ const settings = (mode, mainActor) => `swiftSettings: [.swiftLanguageMode(.v${mode})${mainActor ? ", .defaultIsolation(MainActor.self)" : ""}]`;
3260
+ return [
3261
+ "// swift-tools-version: 6.2",
3262
+ "import PackageDescription",
3263
+ 'let package = Package(name: "app", targets: [',
3264
+ ` .executableTarget(name: "${layout.app.moduleName}", path: "${XCODE_APP_DIR}", ${settings(layout.app.languageMode, layout.app.mainActorIsolation)}),`,
3265
+ ...layout.targets.map(
3266
+ (target) => ` .target(name: "${target.name}", path: "${target.path}", ${target.resources ? "resources: [], " : ""}${settings(target.languageMode, target.mainActorIsolation)}),`
3267
+ ),
3268
+ "])",
3269
+ ""
3270
+ ].join("\n");
3271
+ }
2287
3272
  function packageFiles(root) {
2288
- const canonicalRoot = import_node_fs7.default.realpathSync(root);
3273
+ const canonicalRoot = import_node_fs9.default.realpathSync(root);
3274
+ const xcode = xcodeLayout(canonicalRoot);
3275
+ if (xcode) return xcode.files;
2289
3276
  const found = [];
2290
- const walk = (dir) => {
2291
- for (const entry of import_node_fs7.default.readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
3277
+ const walk2 = (dir) => {
3278
+ for (const entry of import_node_fs9.default.readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
2292
3279
  if (entry.name.startsWith(".") && entry.name !== NATIVE_DESCRIPTOR && entry.name !== NATIVE_GLUE || SKIP_SOURCE_DIRS.has(entry.name))
2293
3280
  continue;
2294
- const full = import_node_path8.default.join(dir, entry.name);
3281
+ const full = import_node_path10.default.join(dir, entry.name);
2295
3282
  if (entry.isSymbolicLink()) throw new Error(`swift input is a symlink: ${full}`);
2296
- const real = import_node_fs7.default.realpathSync(full);
2297
- const relative = import_node_path8.default.relative(canonicalRoot, real);
2298
- if (relative.startsWith(`..${import_node_path8.default.sep}`) || relative === ".." || import_node_path8.default.isAbsolute(relative)) {
3283
+ const real = import_node_fs9.default.realpathSync(full);
3284
+ const relative = import_node_path10.default.relative(canonicalRoot, real);
3285
+ if (relative.startsWith(`..${import_node_path10.default.sep}`) || relative === ".." || import_node_path10.default.isAbsolute(relative)) {
2299
3286
  throw new Error(`swift input escapes the selected package: ${full}`);
2300
3287
  }
2301
3288
  if (entry.isDirectory()) {
2302
- if (import_node_fs7.default.existsSync(import_node_path8.default.join(full, "Package.swift"))) continue;
2303
- walk(full);
3289
+ if (import_node_fs9.default.existsSync(import_node_path10.default.join(full, "Package.swift"))) continue;
3290
+ walk2(full);
2304
3291
  } else if (entry.isFile()) {
2305
3292
  found.push(full);
2306
3293
  if (found.length > 4096) throw new Error("swift package exceeds 4096 input files");
2307
3294
  }
2308
3295
  }
2309
3296
  };
2310
- walk(canonicalRoot);
3297
+ walk2(canonicalRoot);
2311
3298
  return found;
2312
3299
  }
2313
3300
  function readPackageFile(root, file, maxBytes) {
2314
- const canonicalRoot = import_node_fs7.default.realpathSync(root);
2315
- const relative = import_node_path8.default.relative(canonicalRoot, import_node_fs7.default.realpathSync(file));
2316
- if (relative === ".." || relative.startsWith(`..${import_node_path8.default.sep}`) || import_node_path8.default.isAbsolute(relative)) {
3301
+ const canonicalRoot = import_node_fs9.default.realpathSync(root);
3302
+ const relative = import_node_path10.default.relative(canonicalRoot, import_node_fs9.default.realpathSync(file));
3303
+ if (relative === ".." || relative.startsWith(`..${import_node_path10.default.sep}`) || import_node_path10.default.isAbsolute(relative)) {
2317
3304
  throw new Error(`swift input escapes the selected package: ${file}`);
2318
3305
  }
2319
- let ancestor = import_node_path8.default.resolve(file);
3306
+ let ancestor = import_node_path10.default.resolve(file);
2320
3307
  while (ancestor !== canonicalRoot) {
2321
- if (import_node_fs7.default.lstatSync(ancestor).isSymbolicLink()) {
3308
+ if (import_node_fs9.default.lstatSync(ancestor).isSymbolicLink()) {
2322
3309
  throw new Error(`swift input is a symlink: ${ancestor}`);
2323
3310
  }
2324
- const parent = import_node_path8.default.dirname(ancestor);
3311
+ const parent = import_node_path10.default.dirname(ancestor);
2325
3312
  if (parent === ancestor)
2326
3313
  throw new Error(`swift input escapes the selected package: ${file}`);
2327
3314
  ancestor = parent;
2328
3315
  }
2329
- const expected = import_node_fs7.default.statSync(file);
2330
- const fd = import_node_fs7.default.openSync(file, import_node_fs7.default.constants.O_RDONLY | import_node_fs7.default.constants.O_NOFOLLOW);
3316
+ const expected = import_node_fs9.default.statSync(file);
3317
+ const fd = import_node_fs9.default.openSync(file, import_node_fs9.default.constants.O_RDONLY | import_node_fs9.default.constants.O_NOFOLLOW);
2331
3318
  try {
2332
- const stat = import_node_fs7.default.fstatSync(fd);
3319
+ const stat = import_node_fs9.default.fstatSync(fd);
2333
3320
  if (stat.dev !== expected.dev || stat.ino !== expected.ino) {
2334
3321
  throw new Error(`swift input changed while opening: ${file}`);
2335
3322
  }
@@ -2339,28 +3326,43 @@ function readPackageFile(root, file, maxBytes) {
2339
3326
  const bytes = Buffer.alloc(stat.size + 1);
2340
3327
  let offset = 0;
2341
3328
  while (offset < bytes.length) {
2342
- const count = import_node_fs7.default.readSync(fd, bytes, offset, bytes.length - offset, null);
3329
+ const count = import_node_fs9.default.readSync(fd, bytes, offset, bytes.length - offset, null);
2343
3330
  if (count === 0) break;
2344
3331
  offset += count;
2345
3332
  }
2346
- if (offset !== stat.size || import_node_fs7.default.fstatSync(fd).size !== stat.size) {
3333
+ if (offset !== stat.size || import_node_fs9.default.fstatSync(fd).size !== stat.size) {
2347
3334
  throw new Error(`swift input changed while reading: ${file}`);
2348
3335
  }
2349
3336
  return bytes.subarray(0, offset);
2350
3337
  } finally {
2351
- import_node_fs7.default.closeSync(fd);
3338
+ import_node_fs9.default.closeSync(fd);
2352
3339
  }
2353
3340
  }
2354
3341
  function sourceFiles(root) {
2355
- const files = packageFiles(root).filter((file) => file.endsWith(".swift"));
2356
- if (files.length > MAX_SWIFT_COMPILE_FILES || files.reduce((total, file) => total + import_node_fs7.default.statSync(file).size, 0) > MAX_SWIFT_COMPILE_SOURCE_BYTES) {
2357
- throw new Error("swift sources exceed the compile service caps");
2358
- }
2359
- return files;
3342
+ return packageFiles(root).filter((file) => file.endsWith(".swift"));
2360
3343
  }
2361
3344
  function resourceCandidateFiles(root) {
2362
- return packageFiles(root).filter((file) => !file.endsWith(".swift"));
3345
+ return packageFiles(root).filter(
3346
+ (file) => !file.endsWith(".swift") && import_node_path10.default.basename(file) !== "project.pbxproj"
3347
+ );
2363
3348
  }
3349
+ var HOSTED_LIMITS = {
3350
+ resources: MAX_SWIFT_COMPILE_RESOURCES,
3351
+ resourceBytes: MAX_SWIFT_COMPILE_RESOURCE_BYTES,
3352
+ resourceTotalBytes: MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES,
3353
+ images: MAX_SWIFT_COMPILE_IMAGES,
3354
+ imageBytes: MAX_SWIFT_COMPILE_IMAGE_BYTES,
3355
+ imageTotalBytes: MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES
3356
+ };
3357
+ var LOCAL_LIMITS = {
3358
+ resources: Infinity,
3359
+ resourceBytes: Infinity,
3360
+ resourceTotalBytes: Infinity,
3361
+ images: Infinity,
3362
+ imageBytes: Infinity,
3363
+ imageTotalBytes: Infinity
3364
+ };
3365
+ var inputLimits = (hosted) => hosted ? HOSTED_LIMITS : LOCAL_LIMITS;
2364
3366
  var RESOURCE_CONTENT_TYPES = {
2365
3367
  ".avif": "image/avif",
2366
3368
  ".bmp": "image/bmp",
@@ -2372,20 +3374,19 @@ var RESOURCE_CONTENT_TYPES = {
2372
3374
  ".webp": "image/webp"
2373
3375
  };
2374
3376
  function buildSwiftResourceTable(project, baseUrl) {
3377
+ const limits = inputLimits(Boolean(project.hosted));
2375
3378
  const absolute = resourceCandidateFiles(project.packagePath);
2376
3379
  const relative = absolute.map(
2377
- (file) => import_node_path8.default.relative(project.packagePath, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep)
3380
+ (file) => import_node_path10.default.relative(project.packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
2378
3381
  );
2379
3382
  const byRelative = new Map(absolute.map((file, index) => [relative[index], file]));
2380
3383
  const readContents = (candidate) => {
2381
3384
  const file = byRelative.get(candidate);
2382
3385
  if (!file || !/(^|\/)Contents\.json$|\.symbolset\/[^/]+\.svg$/.test(candidate))
2383
3386
  return null;
2384
- return readPackageFile(
2385
- project.packagePath,
2386
- file,
2387
- MAX_SWIFT_COMPILE_RESOURCE_BYTES
2388
- ).toString("utf8");
3387
+ return readPackageFile(project.packagePath, file, limits.resourceBytes).toString(
3388
+ "utf8"
3389
+ );
2389
3390
  };
2390
3391
  const found = enumerateBundleImages(relative, readContents);
2391
3392
  const colors = enumerateBundleColors(relative, readContents);
@@ -2398,20 +3399,16 @@ function buildSwiftResourceTable(project, baseUrl) {
2398
3399
  for (const { name, file, scale } of found) {
2399
3400
  const disk = byRelative.get(file);
2400
3401
  if (!disk) continue;
2401
- if (Object.keys(images).length >= MAX_SWIFT_COMPILE_IMAGES || imageBytes + import_node_fs7.default.statSync(disk).size > MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES) {
3402
+ if (Object.keys(images).length >= limits.images || imageBytes + import_node_fs9.default.statSync(disk).size > limits.imageTotalBytes) {
2402
3403
  throw new Error("swift image pack exceeds the compile service caps");
2403
3404
  }
2404
- const bytes = readPackageFile(
2405
- project.packagePath,
2406
- disk,
2407
- MAX_SWIFT_COMPILE_IMAGE_BYTES
2408
- );
3405
+ const bytes = readPackageFile(project.packagePath, disk, limits.imageBytes);
2409
3406
  imageBytes += bytes.length;
2410
3407
  const hash = (0, import_node_crypto4.createHash)("sha256").update(bytes).digest("hex").slice(0, 16);
2411
- const ext = import_node_path8.default.posix.extname(file).toLowerCase();
3408
+ const ext = import_node_path10.default.posix.extname(file).toLowerCase();
2412
3409
  table[name] = { uri: `${baseUrl}${RESOURCE_PATH}${hash}${ext}`, scale };
2413
3410
  images[name] = {
2414
- file: import_node_path8.default.posix.basename(file),
3411
+ file: import_node_path10.default.posix.basename(file),
2415
3412
  data: bytes.toString("base64")
2416
3413
  };
2417
3414
  watched.push(file);
@@ -2434,26 +3431,24 @@ function buildSwiftResourceTable(project, baseUrl) {
2434
3431
  }
2435
3432
  return { table, images, colors, symbols, watched };
2436
3433
  }
2437
- var BUNDLE_MAX_FILES = MAX_SWIFT_COMPILE_RESOURCES;
2438
- var BUNDLE_MAX_FILE_BYTES = MAX_SWIFT_COMPILE_RESOURCE_BYTES;
2439
- var BUNDLE_MAX_TOTAL_BYTES = MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES;
2440
- function buildSwiftBundleFiles(packagePath) {
2441
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3434
+ function buildSwiftBundleFiles(packagePath, hosted) {
3435
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
3436
+ const limits = inputLimits(hosted);
2442
3437
  const relative = resourceCandidateFiles(packagePath).map(
2443
- (file) => import_node_path8.default.relative(packagePath, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep)
3438
+ (file) => import_node_path10.default.relative(packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
2444
3439
  );
2445
3440
  const files = {};
2446
3441
  const watched = [];
2447
3442
  let total = 0;
2448
3443
  for (const { base, file } of enumerateBundleJson(relative)) {
2449
3444
  watched.push(file);
2450
- const disk = import_node_path8.default.join(packagePath, ...file.split("/"));
2451
- if (Object.keys(files).length >= BUNDLE_MAX_FILES || total + import_node_fs7.default.statSync(disk).size > BUNDLE_MAX_TOTAL_BYTES) {
3445
+ const disk = import_node_path10.default.join(packagePath, ...file.split("/"));
3446
+ if (Object.keys(files).length >= limits.resources || total + import_node_fs9.default.statSync(disk).size > limits.resourceTotalBytes) {
2452
3447
  throw new Error(
2453
- `swift bundle pack exceeds ${BUNDLE_MAX_FILES} files / ${BUNDLE_MAX_TOTAL_BYTES} bytes`
3448
+ `swift bundle pack exceeds ${limits.resources} files / ${limits.resourceTotalBytes} bytes`
2454
3449
  );
2455
3450
  }
2456
- const bytes = readPackageFile(packagePath, disk, BUNDLE_MAX_FILE_BYTES);
3451
+ const bytes = readPackageFile(packagePath, disk, limits.resourceBytes);
2457
3452
  files[base] = bytes.toString("base64");
2458
3453
  total += bytes.length;
2459
3454
  }
@@ -2463,12 +3458,12 @@ function serveSwiftResource(project, key) {
2463
3458
  return project.resourceFiles.get(key) ?? project.resourcesPrevious.get(key) ?? null;
2464
3459
  }
2465
3460
  function linkedModuleRoots(packagePath) {
2466
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3461
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2467
3462
  let manifest;
2468
3463
  try {
2469
3464
  manifest = readPackageFile(
2470
3465
  packagePath,
2471
- import_node_path8.default.join(packagePath, "Package.swift"),
3466
+ import_node_path10.default.join(packagePath, "Package.swift"),
2472
3467
  MAX_SWIFT_COMPILE_SOURCE_BYTES
2473
3468
  ).toString("utf8");
2474
3469
  } catch {
@@ -2477,8 +3472,8 @@ function linkedModuleRoots(packagePath) {
2477
3472
  const roots = /* @__PURE__ */ new Set();
2478
3473
  const dependency = /\.package\(\s*path:\s*"([^"]+)"\s*\)/g;
2479
3474
  for (const match of manifest.replace(/^\s*\/\/.*$/gm, "").matchAll(dependency)) {
2480
- const root = import_node_path8.default.resolve(packagePath, match[1]);
2481
- if (import_node_fs7.default.existsSync(import_node_path8.default.join(root, "Package.swift"))) roots.add(root);
3475
+ const root = import_node_path10.default.resolve(packagePath, match[1]);
3476
+ if (import_node_fs9.default.existsSync(import_node_path10.default.join(root, "Package.swift"))) roots.add(root);
2482
3477
  }
2483
3478
  return [...roots].sort();
2484
3479
  }
@@ -2487,46 +3482,43 @@ function sourceStamp(packagePath, moduleRootOverride, hosted = false) {
2487
3482
  hash.update(packagePath);
2488
3483
  const projectInputs = new Set(packageFiles(packagePath));
2489
3484
  for (const file of [...projectInputs].sort()) {
2490
- hash.update(import_node_path8.default.relative(packagePath, file));
2491
- const stat = import_node_fs7.default.statSync(file);
3485
+ hash.update(import_node_path10.default.relative(packagePath, file));
3486
+ const stat = import_node_fs9.default.statSync(file);
2492
3487
  hash.update(`${stat.mtimeMs}/${stat.ctimeMs}/${stat.size}`);
2493
3488
  }
2494
3489
  const moduleRoot = hosted ? void 0 : moduleRootOverride ?? linkedModuleRoots(packagePath).find(
2495
- (root) => import_node_fs7.default.existsSync(import_node_path8.default.join(root, "toolchain.json"))
3490
+ (root) => import_node_fs9.default.existsSync(import_node_path10.default.join(root, "toolchain.json"))
2496
3491
  );
2497
3492
  if (moduleRoot) {
2498
3493
  hash.update(moduleRoot);
2499
3494
  for (const relative of swiftModuleInputFiles(moduleRoot)) {
2500
3495
  hash.update(relative);
2501
- hash.update(String(import_node_fs7.default.statSync(import_node_path8.default.join(moduleRoot, relative)).mtimeMs));
3496
+ hash.update(String(import_node_fs9.default.statSync(import_node_path10.default.join(moduleRoot, relative)).mtimeMs));
2502
3497
  }
2503
3498
  }
2504
3499
  return hash.digest("hex").slice(0, 16);
2505
3500
  }
2506
3501
  function entryRootId(packagePath, file) {
2507
- const relative = import_node_path8.default.relative(packagePath, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep);
2508
- return `${import_node_path8.default.basename(packagePath)}${import_node_path8.default.posix.sep}${relative}`;
3502
+ const relative = import_node_path10.default.relative(packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep);
3503
+ return `${import_node_path10.default.basename(packagePath)}${import_node_path10.default.posix.sep}${relative}`;
2509
3504
  }
2510
3505
  function icuUrl(origin, artifact) {
2511
3506
  return "url" in artifact.icu ? artifact.icu.url : `${origin}${ICU_PATH}${artifact.icu.sha256}`;
2512
3507
  }
2513
3508
  function packageSources(packagePath) {
2514
- const sources = sourceFiles(packagePath);
2515
- if (sources.length > MAX_SWIFT_COMPILE_FILES)
2516
- throw new Error("swift source file cap exceeded");
2517
- let total = 0;
2518
- for (const file of sources) total += import_node_fs7.default.statSync(file).size;
2519
- if (total > MAX_SWIFT_COMPILE_SOURCE_BYTES)
2520
- throw new Error("swift source byte cap exceeded");
3509
+ const xcode = xcodeLayout(packagePath);
3510
+ const appSources = new Set(xcode?.app.sources);
2521
3511
  const files = {};
2522
- for (const file of sources) {
2523
- const relative = import_node_path8.default.relative(packagePath, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep);
2524
- files[relative] = readPackageFile(
3512
+ for (const file of sourceFiles(packagePath)) {
3513
+ const relative = import_node_path10.default.relative(packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep);
3514
+ if (xcode && import_node_path10.default.basename(file) === "Package.swift") continue;
3515
+ files[xcode ? xcodeInputKey(appSources, file, relative) : relative] = readPackageFile(
2525
3516
  packagePath,
2526
3517
  file,
2527
3518
  MAX_SWIFT_COMPILE_SOURCE_BYTES
2528
3519
  ).toString("utf8");
2529
3520
  }
3521
+ if (xcode) files["Package.swift"] = xcodeManifest(xcode);
2530
3522
  return files;
2531
3523
  }
2532
3524
  function packageSnapshot(project) {
@@ -2536,16 +3528,16 @@ function packageSnapshot(project) {
2536
3528
  files,
2537
3529
  resourcePaths: swiftImplicitResourcePaths(
2538
3530
  resourceCandidateFiles(project.packagePath).map(
2539
- (file) => import_node_path8.default.relative(project.packagePath, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep)
3531
+ (file) => import_node_path10.default.relative(project.packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
2540
3532
  )
2541
3533
  ),
2542
3534
  resources: buildSwiftResourceTable(project, ""),
2543
- bundleFiles: buildSwiftBundleFiles(project.packagePath),
3535
+ bundleFiles: buildSwiftBundleFiles(project.packagePath, Boolean(project.hosted)),
2544
3536
  native,
2545
3537
  ...native ? {
2546
3538
  glue: readPackageFile(
2547
3539
  project.packagePath,
2548
- import_node_path8.default.join(project.packagePath, NATIVE_GLUE),
3540
+ import_node_path10.default.join(project.packagePath, NATIVE_GLUE),
2549
3541
  MAX_SWIFT_COMPILE_SOURCE_BYTES
2550
3542
  ).toString("utf8")
2551
3543
  } : {}
@@ -2584,7 +3576,7 @@ async function compile(packagePath, entry, stamp, moduleRootOverride, hosted, sn
2584
3576
  package: content
2585
3577
  };
2586
3578
  const moduleRoot = moduleRootOverride ?? linkedModuleRoots(packagePath).find(
2587
- (root) => import_node_fs7.default.existsSync(import_node_path8.default.join(root, "toolchain.json"))
3579
+ (root) => import_node_fs9.default.existsSync(import_node_path10.default.join(root, "toolchain.json"))
2588
3580
  ) ?? await swiftDistributionRoot();
2589
3581
  if (!moduleRoot)
2590
3582
  return {
@@ -2593,27 +3585,112 @@ async function compile(packagePath, entry, stamp, moduleRootOverride, hosted, sn
2593
3585
  package: content
2594
3586
  };
2595
3587
  const toolchain = swiftModuleToolchain(moduleRoot);
2596
- const artifact = await compileSwiftProjectUnit(snapshotCompileInput(snapshot, entry), {
3588
+ const input = snapshotCompileInput(snapshot, entry);
3589
+ const targets = compileTargets(input).map((target) => target.name);
3590
+ const missing = missingSwiftModules(
3591
+ input.files,
3592
+ /* @__PURE__ */ new Set([
3593
+ ...swiftAvailableModules(moduleRoot, toolchain.toolchainBin),
3594
+ // a project without a manifest compiles as the template's one App target
3595
+ ...targets.length > 0 ? targets : ["App"]
3596
+ ])
3597
+ );
3598
+ if (missing.size > 0) throw new Error(missingModulesMessage(packagePath, missing));
3599
+ const artifact = await compileSwiftProjectUnit(input, {
2597
3600
  // the compile rewrites Sources/App in its root before swiftpm builds, and
2598
3601
  // its lock orders one process only: two vites on one root (a lane's dev
2599
3602
  // server and a capture, or two checkouts) build each other's sources. so
2600
3603
  // each app and module checkout gets its own root, which keeps the same
2601
3604
  // app's incremental build across restarts.
2602
- buildRoot: process.env.CONTRAST_SWIFT_BUILD_ROOT ?? import_node_path8.default.join(
3605
+ buildRoot: process.env.CONTRAST_SWIFT_BUILD_ROOT ?? import_node_path10.default.join(
2603
3606
  import_node_os5.default.tmpdir(),
2604
3607
  "contrast-swift-build",
2605
- (0, import_node_crypto4.createHash)("sha256").update(`${moduleRoot}\0${import_node_path8.default.resolve(packagePath)}`).digest("hex").slice(0, 16)
3608
+ (0, import_node_crypto4.createHash)("sha256").update(`${moduleRoot}\0${import_node_path10.default.resolve(packagePath)}`).digest("hex").slice(0, 16)
2606
3609
  ),
2607
3610
  moduleRoot,
2608
3611
  ...toolchain
3612
+ }).catch((error) => {
3613
+ const report = error instanceof Error ? swiftApiGapReport(error.message) : null;
3614
+ throw report ? new Error(`${error instanceof Error ? error.message : ""}
3615
+
3616
+ ${report}`, {
3617
+ cause: error
3618
+ }) : error;
2609
3619
  });
2610
3620
  return { ...artifact, stamp, package: content };
2611
3621
  }
3622
+ var API_GAP_PATTERNS = [
3623
+ [/^cannot find (?:type )?'([^']+)' in scope/, (match) => match[1]],
3624
+ // a typealias reports its aliased type after `aka`, which is the api's owner
3625
+ [
3626
+ /^(?:value of )?type '([^']+)'(?: \(aka '([^']+)'\))? has no member '([^']+)'/,
3627
+ (match) => `${(match[2] ?? match[1]).replace(/^Optional<(.+)>$/, "$1").replace(/\?$/, "")}.${match[3]}`
3628
+ ],
3629
+ [
3630
+ /^module '([^']+)' has no member named '([^']+)'/,
3631
+ (match) => `${match[1]}.${match[2]}`
3632
+ ],
3633
+ [/^'([^']+)' is unavailable/, (match) => match[1]],
3634
+ [/^no such module '([^']+)'/, (match) => `module ${match[1]}`]
3635
+ ];
3636
+ function swiftApiGapReport(output) {
3637
+ const gaps = /* @__PURE__ */ new Map();
3638
+ const other = /* @__PURE__ */ new Map();
3639
+ const seen = /* @__PURE__ */ new Set();
3640
+ for (const line of output.split("\n")) {
3641
+ const diagnostic = /^(\S[^:]*\.swift):(\d+):(\d+): error: (.+)$/.exec(line);
3642
+ if (!diagnostic || seen.has(line)) continue;
3643
+ seen.add(line);
3644
+ const file = diagnostic[1].replace(new RegExp(`^${XCODE_APP_DIR}/`), "").replace(new RegExp(`^${XCODE_PACKAGES_DIR}/`), "");
3645
+ const message = diagnostic[4];
3646
+ const rule = API_GAP_PATTERNS.find(([pattern]) => pattern.test(message));
3647
+ const key = rule ? rule[1](rule[0].exec(message)) : message;
3648
+ const table = rule ? gaps : other;
3649
+ const entry = table.get(key) ?? { errors: 0, files: /* @__PURE__ */ new Set() };
3650
+ entry.errors++;
3651
+ entry.files.add(file);
3652
+ table.set(key, entry);
3653
+ }
3654
+ if (gaps.size === 0) return null;
3655
+ const rows = (table) => {
3656
+ const sorted = [...table].sort(
3657
+ ([left, a], [right, b]) => b.errors - a.errors || left.localeCompare(right)
3658
+ );
3659
+ const width = Math.min(48, Math.max(...sorted.map(([key]) => key.length)));
3660
+ return sorted.map(
3661
+ ([key, entry]) => ` ${key.padEnd(width)} ${String(entry.errors).padStart(3)} error${entry.errors === 1 ? " " : "s"} ${[...entry.files].sort().join(", ")}`
3662
+ );
3663
+ };
3664
+ const errors = [...gaps.values()].reduce((sum, entry) => sum + entry.errors, 0);
3665
+ return [
3666
+ `Peach lacks ${gaps.size} API${gaps.size === 1 ? "" : "s"} this app uses (${errors} error${errors === 1 ? "" : "s"}):`,
3667
+ ...rows(gaps),
3668
+ ...other.size > 0 ? ["other errors, often caused by the ones above:", ...rows(other)] : []
3669
+ ].join("\n");
3670
+ }
3671
+ function missingModulesMessage(packagePath, missing) {
3672
+ const layout = xcodeLayout(packagePath);
3673
+ const remote = new Map(
3674
+ (layout?.app.remoteProducts ?? []).map((entry) => [
3675
+ entry.product,
3676
+ entry.repositoryURL
3677
+ ])
3678
+ );
3679
+ const width = Math.max(...[...missing.keys()].map((name) => name.length));
3680
+ return [
3681
+ `Peach does not provide ${missing.size} module${missing.size === 1 ? "" : "s"} this app imports:`,
3682
+ ...[...missing].map(([name, files]) => {
3683
+ const source = remote.get(name);
3684
+ const reason = layout?.unavailable.get(name)?.reason;
3685
+ return ` ${name.padEnd(width)} ${files.length} file${files.length === 1 ? "" : "s"}${source ? `, package ${source}` : ""}${reason ? ` (${reason})` : ""}`;
3686
+ })
3687
+ ].join("\n");
3688
+ }
2612
3689
  async function compileRemote(packagePath, entry, snapshot, hosted) {
2613
3690
  const auth = hosted ? null : resolveCliAuth();
2614
3691
  if (!hosted && (!auth || auth.kind === "github")) {
2615
3692
  throw new Error(
2616
- `compiling ${import_node_path8.default.basename(packagePath)} for Peach needs \`peach login\` or PEACH_API_KEY: this peachsim has no local SwiftUI module, so Contrast compiles it`
3693
+ `compiling ${import_node_path10.default.basename(packagePath)} for Peach needs \`peach login\` or PEACH_API_KEY: this peachsim has no local SwiftUI module, so Contrast compiles it`
2617
3694
  );
2618
3695
  }
2619
3696
  const origin = hosted?.origin ?? resolveContrastBackendOrigin(auth?.kind === "session" ? auth.origin : null);
@@ -2628,6 +3705,13 @@ async function compileRemote(packagePath, entry, snapshot, hosted) {
2628
3705
  signal
2629
3706
  });
2630
3707
  if (!submit) throw new Error("swift compile: no credential to submit with");
3708
+ const sources = Object.values(snapshot.files);
3709
+ const bytes = sources.reduce((total2, text) => total2 + Buffer.byteLength(text), 0);
3710
+ if (sources.length > MAX_SWIFT_COMPILE_FILES || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES) {
3711
+ throw new Error(
3712
+ `${import_node_path10.default.basename(packagePath)} has ${sources.length} Swift files (${bytes} bytes), over Contrast's compile limits of ${MAX_SWIFT_COMPILE_FILES} files and ${MAX_SWIFT_COMPILE_SOURCE_BYTES} bytes; compile it on this machine with the Swift distribution instead`
3713
+ );
3714
+ }
2631
3715
  const descriptor = snapshot.native;
2632
3716
  const address = await compileSwiftProject(
2633
3717
  submit,
@@ -2644,7 +3728,7 @@ async function compileRemote(packagePath, entry, snapshot, hosted) {
2644
3728
  );
2645
3729
  if (descriptor && address.native?.hash !== descriptor.hash) {
2646
3730
  throw new Error(
2647
- `${import_node_path8.default.basename(packagePath)}: Contrast compiled native contract ${address.native?.hash ?? "none"} but one typegen wrote ${descriptor.hash}; the app's One and the compile host's differ, or the compile host is older than this peachsim`
3731
+ `${import_node_path10.default.basename(packagePath)}: Contrast compiled native contract ${address.native?.hash ?? "none"} but one typegen wrote ${descriptor.hash}; the app's One and the compile host's differ, or the compile host is older than this peachsim`
2648
3732
  );
2649
3733
  }
2650
3734
  const response = await fetch(address.url, { signal });
@@ -2717,17 +3801,17 @@ function artifactFor(project, entry, moduleRoot) {
2717
3801
  return fresh;
2718
3802
  }
2719
3803
  function swiftPackageWatchFiles(packagePath, moduleRoot) {
2720
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3804
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2721
3805
  return [
2722
- import_node_path8.default.join(packagePath, "Package.swift"),
3806
+ ...xcodeProjects.has(packagePath) ? [] : [import_node_path10.default.join(packagePath, "Package.swift")],
2723
3807
  ...sourceFiles(packagePath),
2724
3808
  ...nativeSourceFiles(packagePath),
2725
3809
  ...resourceCandidateFiles(packagePath),
2726
- ...moduleRoot ? swiftModuleInputFiles(moduleRoot).map((file) => import_node_path8.default.join(moduleRoot, file)) : []
3810
+ ...moduleRoot ? swiftModuleInputFiles(moduleRoot).map((file) => import_node_path10.default.join(moduleRoot, file)) : []
2727
3811
  ];
2728
3812
  }
2729
3813
  async function swiftPackageMetadata(packagePath, packageName, moduleRoot, origin, hosted) {
2730
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3814
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2731
3815
  const mains = sourceFiles(packagePath).filter(
2732
3816
  (file) => /@main\s+(?:public\s+)?struct\s+\w+\s*:/.test(
2733
3817
  readPackageFile(packagePath, file, MAX_SWIFT_COMPILE_SOURCE_BYTES).toString("utf8")
@@ -2740,7 +3824,7 @@ async function swiftPackageMetadata(packagePath, packageName, moduleRoot, origin
2740
3824
  );
2741
3825
  }
2742
3826
  const project = projectFor(packagePath, hosted);
2743
- const entry = mains.length === 1 ? import_node_path8.default.relative(packagePath, mains[0]).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep) : Object.entries(native?.files ?? {}).find(
3827
+ const entry = mains.length === 1 ? import_node_path10.default.relative(packagePath, mains[0]).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep) : Object.entries(native?.files ?? {}).find(
2744
3828
  ([_file, names]) => names.length > 0
2745
3829
  )?.[0];
2746
3830
  if (!entry) throw new Error(`swift package ${packageName} has no native module source`);
@@ -2829,12 +3913,12 @@ function artifactUrl(project, artifact) {
2829
3913
  return `${serverOrigin()}${ARTIFACT_PATH2}${artifact.hash}.wasm`;
2830
3914
  }
2831
3915
  function packageFor(file) {
2832
- let dir = import_node_path9.default.dirname(file);
3916
+ let dir = import_node_path11.default.dirname(file);
2833
3917
  const stop = devServer?.config.root;
2834
3918
  for (; ; ) {
2835
- if (import_node_fs8.default.existsSync(import_node_path9.default.join(dir, "Package.swift"))) return dir;
2836
- if (stop !== void 0 && dir === stop || import_node_path9.default.dirname(dir) === dir) break;
2837
- dir = import_node_path9.default.dirname(dir);
3919
+ if (import_node_fs10.default.existsSync(import_node_path11.default.join(dir, "Package.swift"))) return dir;
3920
+ if (stop !== void 0 && dir === stop || import_node_path11.default.dirname(dir) === dir) break;
3921
+ dir = import_node_path11.default.dirname(dir);
2838
3922
  }
2839
3923
  throw new Error(
2840
3924
  `no Package.swift above ${file}${stop === void 0 ? "" : ` (searched up to ${stop})`}; a .swift import needs a swiftpm package like the one in packages/sootsim-swift/example`
@@ -2855,9 +3939,9 @@ function swiftPlugin(options = {}) {
2855
3939
  if (!resolved) throw new Error(`cannot resolve swift source ${source}`);
2856
3940
  let id = resolved.id;
2857
3941
  if (importer && (source.startsWith("./") || source.startsWith("../"))) {
2858
- const raw2 = import_node_path9.default.resolve(import_node_path9.default.dirname(importer.split("?")[0] ?? importer), source);
3942
+ const raw2 = import_node_path11.default.resolve(import_node_path11.default.dirname(importer.split("?")[0] ?? importer), source);
2859
3943
  try {
2860
- if (import_node_fs8.default.realpathSync(raw2) === import_node_fs8.default.realpathSync(resolved.id)) id = raw2;
3944
+ if (import_node_fs10.default.realpathSync(raw2) === import_node_fs10.default.realpathSync(resolved.id)) id = raw2;
2861
3945
  } catch {
2862
3946
  }
2863
3947
  }
@@ -2866,22 +3950,22 @@ function swiftPlugin(options = {}) {
2866
3950
  async load(id) {
2867
3951
  if (!id.startsWith(VIRTUAL_PREFIX)) return null;
2868
3952
  const file = id.slice(VIRTUAL_PREFIX.length);
2869
- if (!import_node_fs8.default.existsSync(file)) throw new Error(`swift source ${file} no longer exists`);
3953
+ if (!import_node_fs10.default.existsSync(file)) throw new Error(`swift source ${file} no longer exists`);
2870
3954
  const packagePath = options.packagePath ?? packageFor(file);
2871
3955
  const project = projectFor(packagePath);
2872
- const entry = import_node_path9.default.relative(packagePath, file).split(import_node_path9.default.sep).join(import_node_path9.default.posix.sep);
3956
+ const entry = import_node_path11.default.relative(packagePath, file).split(import_node_path11.default.sep).join(import_node_path11.default.posix.sep);
2873
3957
  for (const source of [
2874
3958
  ...sourceFiles(packagePath),
2875
3959
  ...nativeSourceFiles(packagePath)
2876
3960
  ])
2877
3961
  this.addWatchFile(source);
2878
- this.addWatchFile(import_node_path9.default.join(packagePath, "Package.swift"));
3962
+ this.addWatchFile(import_node_path11.default.join(packagePath, "Package.swift"));
2879
3963
  const moduleRoot = linkedModuleRoots(packagePath).find(
2880
- (root) => import_node_fs8.default.existsSync(import_node_path9.default.join(root, "toolchain.json"))
3964
+ (root) => import_node_fs10.default.existsSync(import_node_path11.default.join(root, "toolchain.json"))
2881
3965
  );
2882
3966
  if (moduleRoot)
2883
3967
  for (const relative of swiftModuleInputFiles(moduleRoot))
2884
- this.addWatchFile(import_node_path9.default.join(moduleRoot, relative));
3968
+ this.addWatchFile(import_node_path11.default.join(moduleRoot, relative));
2885
3969
  let artifact;
2886
3970
  try {
2887
3971
  artifact = await artifactFor(project, entry);
@@ -2900,7 +3984,7 @@ function swiftPlugin(options = {}) {
2900
3984
  ...artifact.package.resources.watched,
2901
3985
  ...artifact.package.bundleFiles.watched
2902
3986
  ])
2903
- this.addWatchFile(import_node_path9.default.join(packagePath, ...watched.split(import_node_path9.default.posix.sep)));
3987
+ this.addWatchFile(import_node_path11.default.join(packagePath, ...watched.split(import_node_path11.default.posix.sep)));
2904
3988
  const colors = artifact.package.resources.colors;
2905
3989
  const symbols = artifact.package.resources.symbols;
2906
3990
  const bundleFiles = artifact.package.bundleFiles.files;