peachsim 0.1.730 → 0.1.746

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 (107) 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-sim-host.ts +2 -0
  15. package/cli/drivers/playwright.ts +3 -3
  16. package/cli/drivers/registry.ts +7 -2
  17. package/cli/drivers/types.ts +4 -3
  18. package/cli/maestro-js.ts +10 -0
  19. package/cli/outbound-endpoints.ts +2 -2
  20. package/dist-lib/agent-daemon-client.cjs +1 -1
  21. package/dist-lib/agent-events.cjs +1 -1
  22. package/dist-lib/agent-identity.cjs +1 -1
  23. package/dist-lib/agent-sessions.cjs +1 -1
  24. package/dist-lib/attached-projects.cjs +1 -1
  25. package/dist-lib/auth/shared-session.cjs +39 -9
  26. package/dist-lib/backend-origin.cjs +1 -1
  27. package/dist-lib/beta.cjs +1 -1
  28. package/dist-lib/beta.mjs +1 -1
  29. package/dist-lib/bridge-constants.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.cjs +1 -1
  31. package/dist-lib/bridge-contract-input.mjs +1 -1
  32. package/dist-lib/bridge-contract.cjs +1 -1
  33. package/dist-lib/bridge-contract.mjs +1 -1
  34. package/dist-lib/capture-contract.cjs +13 -19
  35. package/dist-lib/capture-contract.mjs +13 -19
  36. package/dist-lib/cli-constants.cjs +1 -1
  37. package/dist-lib/cloud-contract.cjs +1 -1
  38. package/dist-lib/cloud-contract.mjs +1 -1
  39. package/dist-lib/cloud-test-args.cjs +1 -1
  40. package/dist-lib/cloud-test-args.mjs +1 -1
  41. package/dist-lib/cloud.cjs +1 -1
  42. package/dist-lib/cloud.mjs +1 -1
  43. package/dist-lib/config.cjs +1 -1
  44. package/dist-lib/detox/index.cjs +117 -11
  45. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  46. package/dist-lib/home-paths.cjs +32 -1
  47. package/dist-lib/host/bridge-host.cjs +1741 -540
  48. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  49. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  50. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  51. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  52. package/dist-lib/host/websocket-proxy.cjs +1 -1
  53. package/dist-lib/index.cjs +17 -22
  54. package/dist-lib/jump-to-source-babel.cjs +1 -1
  55. package/dist-lib/jump-to-source-native.cjs +1 -1
  56. package/dist-lib/kotlin-host.cjs +1 -1
  57. package/dist-lib/menu.cjs +1 -1
  58. package/dist-lib/menu.mjs +1 -1
  59. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  60. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  61. package/dist-lib/metro-production-bundle.cjs +1 -1
  62. package/dist-lib/metro-production-bundle.mjs +1 -1
  63. package/dist-lib/metro.cjs +1 -1
  64. package/dist-lib/native-app-identity.cjs +1 -1
  65. package/dist-lib/native-app-identity.mjs +1 -1
  66. package/dist-lib/native-firebase-metadata.cjs +1 -1
  67. package/dist-lib/native-firebase-metadata.mjs +1 -1
  68. package/dist-lib/plist.cjs +1 -1
  69. package/dist-lib/plist.mjs +1 -1
  70. package/dist-lib/profiles.cjs +1 -1
  71. package/dist-lib/public-brand.cjs +1 -1
  72. package/dist-lib/react-native-host-modules.cjs +1 -1
  73. package/dist-lib/react-native-host-modules.mjs +1 -1
  74. package/dist-lib/render-mode.cjs +1 -1
  75. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  76. package/dist-lib/sdk.cjs +2 -1
  77. package/dist-lib/sdk.mjs +2 -1
  78. package/dist-lib/skills.cjs +2431 -1075
  79. package/dist-lib/swift-compile.cjs +374 -65
  80. package/dist-lib/swift-compile.mjs +369 -66
  81. package/dist-lib/swift-package.cjs +146 -9
  82. package/dist-lib/swift-package.mjs +144 -9
  83. package/dist-lib/swift-submit.cjs +2 -2
  84. package/dist-lib/swift-submit.mjs +2 -2
  85. package/dist-lib/swift-toolchain.cjs +1 -1
  86. package/dist-lib/swift.cjs +1 -1
  87. package/dist-lib/vite-swift.cjs +1690 -233
  88. package/dist-lib/vite.cjs +4 -4
  89. package/package.json +1 -1
  90. package/skills/contrast/SKILL.md +1 -1
  91. package/src/auth/shared-session.ts +45 -9
  92. package/src/bridge-constants.ts +7 -7
  93. package/src/capture-contract.ts +18 -33
  94. package/src/desktop-host-delivery.ts +81 -0
  95. package/src/home-paths.ts +30 -0
  96. package/src/host/bridge-host.ts +11 -6
  97. package/src/native-seam-manifest.ts +0 -11
  98. package/src/sim-client.ts +1 -0
  99. package/src/swift-compile.ts +479 -76
  100. package/src/swift-distribution.lock.json +11 -11
  101. package/src/swift-host.ts +338 -45
  102. package/src/swift-package.ts +204 -19
  103. package/src/swift-remote-packages.ts +255 -0
  104. package/src/swift-submit.ts +4 -1
  105. package/src/vite-plugin-one.ts +2 -2
  106. package/src/vite-plugin.ts +29 -9
  107. package/src/xcode-project.ts +612 -0
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.730 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.746 | (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;
@@ -7,6 +7,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
8
  var __getProtoOf = Object.getPrototypeOf;
9
9
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __commonJS = (cb, mod) => function __require() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
10
13
  var __export = (target, all) => {
11
14
  for (var name in all)
12
15
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -29,6 +32,245 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
32
  ));
30
33
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
34
 
35
+ // ../../node_modules/plist/lib/parse.js
36
+ var require_parse = __commonJS({
37
+ "../../node_modules/plist/lib/parse.js"(exports2) {
38
+ var { DOMParser } = require("@xmldom/xmldom");
39
+ exports2.parse = parse;
40
+ var TEXT_NODE = 3;
41
+ var CDATA_NODE = 4;
42
+ var COMMENT_NODE = 8;
43
+ function shouldIgnoreNode(node) {
44
+ return node.nodeType === TEXT_NODE || node.nodeType === COMMENT_NODE || node.nodeType === CDATA_NODE;
45
+ }
46
+ function isEmptyNode(node) {
47
+ if (!node.childNodes || node.childNodes.length === 0) {
48
+ return true;
49
+ } else {
50
+ return false;
51
+ }
52
+ }
53
+ function invariant(test, message) {
54
+ if (!test) {
55
+ throw new Error(message);
56
+ }
57
+ }
58
+ function parse(xml) {
59
+ var doc = new DOMParser().parseFromString(xml, "text/xml");
60
+ invariant(
61
+ doc.documentElement.nodeName === "plist",
62
+ "malformed document. First element should be <plist>"
63
+ );
64
+ var plist2 = parsePlistXML(doc.documentElement);
65
+ if (plist2.length == 1) plist2 = plist2[0];
66
+ return plist2;
67
+ }
68
+ function parsePlistXML(node) {
69
+ var i, new_obj, key, val, new_arr, res, counter, type;
70
+ if (!node) return null;
71
+ if (node.nodeName === "plist") {
72
+ new_arr = [];
73
+ if (isEmptyNode(node)) {
74
+ return new_arr;
75
+ }
76
+ for (i = 0; i < node.childNodes.length; i++) {
77
+ if (!shouldIgnoreNode(node.childNodes[i])) {
78
+ new_arr.push(parsePlistXML(node.childNodes[i]));
79
+ }
80
+ }
81
+ return new_arr;
82
+ } else if (node.nodeName === "dict") {
83
+ new_obj = {};
84
+ key = null;
85
+ counter = 0;
86
+ if (isEmptyNode(node)) {
87
+ return new_obj;
88
+ }
89
+ for (i = 0; i < node.childNodes.length; i++) {
90
+ if (shouldIgnoreNode(node.childNodes[i])) continue;
91
+ if (counter % 2 === 0) {
92
+ invariant(
93
+ node.childNodes[i].nodeName === "key",
94
+ "Missing key while parsing <dict/>."
95
+ );
96
+ key = parsePlistXML(node.childNodes[i]);
97
+ } else {
98
+ invariant(
99
+ node.childNodes[i].nodeName !== "key",
100
+ 'Unexpected key "' + parsePlistXML(node.childNodes[i]) + '" while parsing <dict/>.'
101
+ );
102
+ new_obj[key] = parsePlistXML(node.childNodes[i]);
103
+ }
104
+ counter += 1;
105
+ }
106
+ if (counter % 2 === 1) {
107
+ new_obj[key] = "";
108
+ }
109
+ return new_obj;
110
+ } else if (node.nodeName === "array") {
111
+ new_arr = [];
112
+ if (isEmptyNode(node)) {
113
+ return new_arr;
114
+ }
115
+ for (i = 0; i < node.childNodes.length; i++) {
116
+ if (!shouldIgnoreNode(node.childNodes[i])) {
117
+ res = parsePlistXML(node.childNodes[i]);
118
+ if (null != res) new_arr.push(res);
119
+ }
120
+ }
121
+ return new_arr;
122
+ } else if (node.nodeName === "#text") {
123
+ } else if (node.nodeName === "key") {
124
+ if (isEmptyNode(node)) {
125
+ return "";
126
+ }
127
+ invariant(
128
+ node.childNodes[0].nodeValue !== "__proto__",
129
+ "__proto__ keys can lead to prototype pollution. More details on CVE-2022-22912"
130
+ );
131
+ return node.childNodes[0].nodeValue;
132
+ } else if (node.nodeName === "string") {
133
+ res = "";
134
+ if (isEmptyNode(node)) {
135
+ return res;
136
+ }
137
+ for (i = 0; i < node.childNodes.length; i++) {
138
+ var type = node.childNodes[i].nodeType;
139
+ if (type === TEXT_NODE || type === CDATA_NODE) {
140
+ res += node.childNodes[i].nodeValue;
141
+ }
142
+ }
143
+ return res;
144
+ } else if (node.nodeName === "integer") {
145
+ invariant(!isEmptyNode(node), 'Cannot parse "" as integer.');
146
+ return parseInt(node.childNodes[0].nodeValue, 10);
147
+ } else if (node.nodeName === "real") {
148
+ invariant(!isEmptyNode(node), 'Cannot parse "" as real.');
149
+ res = "";
150
+ for (i = 0; i < node.childNodes.length; i++) {
151
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
152
+ res += node.childNodes[i].nodeValue;
153
+ }
154
+ }
155
+ return parseFloat(res);
156
+ } else if (node.nodeName === "data") {
157
+ res = "";
158
+ if (isEmptyNode(node)) {
159
+ return Buffer.from(res, "base64");
160
+ }
161
+ for (i = 0; i < node.childNodes.length; i++) {
162
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
163
+ res += node.childNodes[i].nodeValue.replace(/\s+/g, "");
164
+ }
165
+ }
166
+ return Buffer.from(res, "base64");
167
+ } else if (node.nodeName === "date") {
168
+ invariant(!isEmptyNode(node), 'Cannot parse "" as Date.');
169
+ return new Date(node.childNodes[0].nodeValue);
170
+ } else if (node.nodeName === "null") {
171
+ return null;
172
+ } else if (node.nodeName === "true") {
173
+ return true;
174
+ } else if (node.nodeName === "false") {
175
+ return false;
176
+ } else {
177
+ throw new Error("Invalid PLIST tag " + node.nodeName);
178
+ }
179
+ }
180
+ }
181
+ });
182
+
183
+ // ../../node_modules/plist/lib/build.js
184
+ var require_build = __commonJS({
185
+ "../../node_modules/plist/lib/build.js"(exports2) {
186
+ var base64 = require("base64-js");
187
+ var xmlbuilder = require("xmlbuilder");
188
+ exports2.build = build;
189
+ function ISODateString(d) {
190
+ function pad(n) {
191
+ return n < 10 ? "0" + n : n;
192
+ }
193
+ return d.getUTCFullYear() + "-" + pad(d.getUTCMonth() + 1) + "-" + pad(d.getUTCDate()) + "T" + pad(d.getUTCHours()) + ":" + pad(d.getUTCMinutes()) + ":" + pad(d.getUTCSeconds()) + "Z";
194
+ }
195
+ var toString = Object.prototype.toString;
196
+ function type(obj) {
197
+ var m = toString.call(obj).match(/\[object (.*)\]/);
198
+ return m ? m[1] : m;
199
+ }
200
+ function build(obj, opts) {
201
+ var XMLHDR = {
202
+ version: "1.0",
203
+ encoding: "UTF-8"
204
+ };
205
+ var XMLDTD = {
206
+ pubid: "-//Apple//DTD PLIST 1.0//EN",
207
+ sysid: "http://www.apple.com/DTDs/PropertyList-1.0.dtd"
208
+ };
209
+ var doc = xmlbuilder.create("plist");
210
+ doc.dec(XMLHDR.version, XMLHDR.encoding, XMLHDR.standalone);
211
+ doc.dtd(XMLDTD.pubid, XMLDTD.sysid);
212
+ doc.att("version", "1.0");
213
+ walk_obj(obj, doc);
214
+ if (!opts) opts = {};
215
+ opts.pretty = opts.pretty !== false;
216
+ return doc.end(opts);
217
+ }
218
+ function walk_obj(next, next_child) {
219
+ var tag_type, i, prop;
220
+ var name = type(next);
221
+ if ("Undefined" == name) {
222
+ return;
223
+ } else if (Array.isArray(next)) {
224
+ next_child = next_child.ele("array");
225
+ for (i = 0; i < next.length; i++) {
226
+ walk_obj(next[i], next_child);
227
+ }
228
+ } else if (Buffer.isBuffer(next)) {
229
+ next_child.ele("data").raw(next.toString("base64"));
230
+ } else if ("Object" == name) {
231
+ next_child = next_child.ele("dict");
232
+ for (prop in next) {
233
+ if (next.hasOwnProperty(prop)) {
234
+ next_child.ele("key").txt(prop);
235
+ walk_obj(next[prop], next_child);
236
+ }
237
+ }
238
+ } else if ("Number" == name) {
239
+ tag_type = next % 1 === 0 ? "integer" : "real";
240
+ next_child.ele(tag_type).txt(next.toString());
241
+ } else if ("BigInt" == name) {
242
+ next_child.ele("integer").txt(next);
243
+ } else if ("Date" == name) {
244
+ next_child.ele("date").txt(ISODateString(new Date(next)));
245
+ } else if ("Boolean" == name) {
246
+ next_child.ele(next ? "true" : "false");
247
+ } else if ("String" == name) {
248
+ next_child.ele("string").txt(next);
249
+ } else if ("ArrayBuffer" == name) {
250
+ next_child.ele("data").raw(base64.fromByteArray(next));
251
+ } else if (next && next.buffer && "ArrayBuffer" == type(next.buffer)) {
252
+ next_child.ele("data").raw(base64.fromByteArray(new Uint8Array(next.buffer), next_child));
253
+ } else if ("Null" === name) {
254
+ next_child.ele("null").txt("");
255
+ }
256
+ }
257
+ }
258
+ });
259
+
260
+ // ../../node_modules/plist/index.js
261
+ var require_plist = __commonJS({
262
+ "../../node_modules/plist/index.js"(exports2) {
263
+ var parserFunctions = require_parse();
264
+ Object.keys(parserFunctions).forEach(function(k) {
265
+ exports2[k] = parserFunctions[k];
266
+ });
267
+ var builderFunctions = require_build();
268
+ Object.keys(builderFunctions).forEach(function(k) {
269
+ exports2[k] = builderFunctions[k];
270
+ });
271
+ }
272
+ });
273
+
32
274
  // src/vite-plugin-swift.ts
33
275
  var vite_plugin_swift_exports = {};
34
276
  __export(vite_plugin_swift_exports, {
@@ -45,8 +287,8 @@ __export(vite_plugin_swift_exports, {
45
287
  swiftPlugin: () => swiftPlugin
46
288
  });
47
289
  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);
290
+ var import_node_fs10 = __toESM(require("node:fs"), 1);
291
+ var import_node_path11 = __toESM(require("node:path"), 1);
50
292
 
51
293
  // ../sootsim-swift/src/entryModule.ts
52
294
  function nativeExportLines(args, commonjs) {
@@ -251,14 +493,24 @@ function swiftImplicitResourcePaths(paths) {
251
493
  ) || /(?:^|\/)[^/]+\.lproj\/[^/]+$/.test(file))
252
494
  ).sort();
253
495
  }
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;
496
+ var MANIFEST_DECLARATIONS = [
497
+ "executableTarget",
498
+ "testTarget",
499
+ "binaryTarget",
500
+ "systemLibrary",
501
+ "macro",
502
+ "plugin",
503
+ "target",
504
+ "library",
505
+ "executable",
506
+ "package"
507
+ ];
508
+ function manifestCalls(manifest, kinds) {
509
+ const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"])\/\/[^\n]*/g, "$1");
510
+ const calls = [];
511
+ const pattern = new RegExp(`\\.(${MANIFEST_DECLARATIONS.join("|")})\\s*\\(`, "g");
259
512
  let match;
260
513
  while ((match = pattern.exec(code)) !== null) {
261
- const executable = match[1] === "executableTarget";
262
514
  let depth = 1;
263
515
  const start = pattern.lastIndex;
264
516
  let i = start;
@@ -286,18 +538,141 @@ function swiftManifestTargets(manifest, resourcePaths = []) {
286
538
  }
287
539
  i++;
288
540
  }
541
+ if (kinds.includes(match[1]))
542
+ calls.push({ kind: match[1], flat, call: code.slice(start, i) });
543
+ pattern.lastIndex = i;
544
+ }
545
+ return calls;
546
+ }
547
+ var NAME = /\bname\s*:\s*"([^"]+)"/;
548
+ function listArgument(call, label) {
549
+ const start = new RegExp(`\\b${label}\\s*:\\s*\\[`).exec(call);
550
+ if (!start) return [];
551
+ const items = [];
552
+ let depth = 0;
553
+ let inString = false;
554
+ let item = "";
555
+ for (let i = start.index + start[0].length; i < call.length; i++) {
556
+ const ch = call[i];
557
+ if (inString) {
558
+ item += ch;
559
+ if (ch === '"' && call[i - 1] !== "\\") inString = false;
560
+ continue;
561
+ }
562
+ if (ch === '"') inString = true;
563
+ else if (ch === "(" || ch === "[") depth++;
564
+ else if (ch === ")" || ch === "]") {
565
+ if (depth === 0) break;
566
+ depth--;
567
+ } else if (ch === "," && depth === 0) {
568
+ items.push(item.trim());
569
+ item = "";
570
+ continue;
571
+ }
572
+ item += ch;
573
+ }
574
+ if (item.trim()) items.push(item.trim());
575
+ return items;
576
+ }
577
+ function swiftPackageIdentity(url) {
578
+ return (url.split("/").pop() ?? url).replace(/\.git$/, "").toLowerCase();
579
+ }
580
+ function swiftManifestGraph(manifest) {
581
+ const graph = {
582
+ products: /* @__PURE__ */ new Map(),
583
+ dependencies: /* @__PURE__ */ new Map(),
584
+ binaryTargets: /* @__PURE__ */ new Set(),
585
+ systemLibraries: /* @__PURE__ */ new Set(),
586
+ packageURLs: /* @__PURE__ */ new Map(),
587
+ packagePaths: []
588
+ };
589
+ for (const { kind, flat, call } of manifestCalls(manifest, [
590
+ "library",
591
+ "executableTarget",
592
+ "target",
593
+ "binaryTarget",
594
+ "systemLibrary",
595
+ "package"
596
+ ])) {
597
+ if (kind === "package") {
598
+ const local = /\bpath\s*:\s*"([^"]+)"/.exec(flat)?.[1];
599
+ if (local) graph.packagePaths.push(local);
600
+ const url = /\burl\s*:\s*"([^"]+)"/.exec(flat)?.[1];
601
+ if (!url) continue;
602
+ graph.packageURLs.set(swiftPackageIdentity(url), url);
603
+ const name2 = NAME.exec(flat)?.[1];
604
+ if (name2) graph.packageURLs.set(name2.toLowerCase(), url);
605
+ continue;
606
+ }
607
+ const name = NAME.exec(flat)?.[1];
608
+ if (!name) continue;
609
+ if (kind === "library") {
610
+ graph.products.set(
611
+ name,
612
+ listArgument(call, "targets").flatMap(
613
+ (item) => /^"([^"]+)"$/.exec(item)?.[1] ?? []
614
+ )
615
+ );
616
+ continue;
617
+ }
618
+ if (kind === "binaryTarget") graph.binaryTargets.add(name);
619
+ if (kind === "systemLibrary") graph.systemLibraries.add(name);
620
+ const dependencies = [];
621
+ for (const item of listArgument(call, "dependencies")) {
622
+ const platforms = /condition\s*:\s*\.when\(\s*platforms\s*:\s*\[([^\]]*)\]/.exec(
623
+ item
624
+ )?.[1];
625
+ if (platforms !== void 0 && !/\.iOS\b/.test(platforms)) continue;
626
+ if (/condition\s*:\s*\.when\([^)]*\btraits\s*:/.test(item)) continue;
627
+ const plain = /^"([^"]+)"$/.exec(item)?.[1];
628
+ const product = /^\.product(?:Item)?\(\s*name\s*:\s*"([^"]+)"\s*,\s*package\s*:\s*"([^"]+)"/.exec(
629
+ item
630
+ );
631
+ const target = /^\.(?:target|byName)(?:Item)?\(\s*name\s*:\s*"([^"]+)"/.exec(
632
+ item
633
+ )?.[1];
634
+ if (plain) dependencies.push({ kind: "target", name: plain });
635
+ else if (product)
636
+ dependencies.push({
637
+ kind: "product",
638
+ name: product[1],
639
+ package: product[2].toLowerCase()
640
+ });
641
+ else if (target) dependencies.push({ kind: "target", name: target });
642
+ }
643
+ graph.dependencies.set(name, dependencies);
644
+ }
645
+ for (const dependencies of graph.dependencies.values()) {
646
+ for (const [index, dependency] of dependencies.entries()) {
647
+ if (dependency.kind === "target" && !graph.dependencies.has(dependency.name))
648
+ dependencies[index] = {
649
+ kind: "product",
650
+ name: dependency.name,
651
+ package: dependency.name.toLowerCase()
652
+ };
653
+ }
654
+ }
655
+ return graph;
656
+ }
657
+ function swiftManifestTargets(manifest, resourcePaths = []) {
658
+ const implicitResources = swiftImplicitResourcePaths(resourcePaths);
659
+ const targets = [];
660
+ for (const { kind, flat, call } of manifestCalls(manifest, [
661
+ "executableTarget",
662
+ "target"
663
+ ])) {
664
+ const executable = kind === "executableTarget";
289
665
  const name = /\bname\s*:\s*"([^"]+)"/.exec(flat)?.[1];
290
666
  if (!name) continue;
291
667
  const rawPath = /\bpath\s*:\s*"([^"]*)"/.exec(flat)?.[1];
292
668
  const targetPath = rawPath == null || rawPath === "" ? `Sources/${name}` : rawPath.replace(/^\.\//, "").replace(/\/+$/, "");
293
- const call = code.slice(start, i);
294
669
  const languageMode = Number(
295
670
  /\.swiftLanguageMode\(\s*\.v(\d+)\s*\)/.exec(call)?.[1] ?? "5"
296
671
  );
297
672
  const mainActorIsolation = /\.defaultIsolation\(\s*MainActor\.self\s*\)/.test(call);
298
673
  const excluded = [
299
674
  ...(/\bexclude\s*:\s*\[([^\]]*)\]/.exec(flat)?.[1] ?? "").matchAll(/"([^"]+)"/g)
300
- ].map((match2) => match2[1].replace(/^\.\//, "").replace(/\/+$/, ""));
675
+ ].map((match) => match[1].replace(/^\.\//, "").replace(/\/+$/, ""));
301
676
  const prefix = targetPath === "." ? "" : `${targetPath}/`;
302
677
  const resources = /\bresources\s*:/.test(flat) || implicitResources.some((file) => {
303
678
  if (!file.startsWith(prefix)) return false;
@@ -328,7 +703,10 @@ function swiftPackagePartition(manifest, resourcePaths = []) {
328
703
  var run2 = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
329
704
  var WASM_TRIPLE = "wasm32-unknown-wasip1";
330
705
  var cores = import_node_os.default.availableParallelism();
331
- var BUILD_ENV = { ...process.env, BINARYEN_CORES: String(Math.min(4, cores)) };
706
+ var BUILD_ENV = {
707
+ ...process.env,
708
+ BINARYEN_CORES: String(Math.min(4, cores))
709
+ };
332
710
  var BUILD_JOBS = String(Math.max(1, Math.floor(cores / 2)));
333
711
  function swiftDistributionAt(root) {
334
712
  const file = import_node_path2.default.join(root, SWIFT_DISTRIBUTION_MANIFEST);
@@ -352,14 +730,16 @@ function swiftModuleInputFiles(root) {
352
730
  "scripts/contrast-app-Package.swift",
353
731
  "toolchain.json"
354
732
  ];
355
- const walk = (dir) => {
356
- for (const entry of (0, import_node_fs2.readdirSync)(import_node_path2.default.join(root, dir), { withFileTypes: true })) {
733
+ const walk2 = (dir) => {
734
+ for (const entry of (0, import_node_fs2.readdirSync)(import_node_path2.default.join(root, dir), {
735
+ withFileTypes: true
736
+ })) {
357
737
  const relative = `${dir}/${entry.name}`;
358
- if (entry.isDirectory()) walk(relative);
738
+ if (entry.isDirectory()) walk2(relative);
359
739
  else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative);
360
740
  }
361
741
  };
362
- walk("Sources");
742
+ walk2("Sources");
363
743
  return files.sort();
364
744
  }
365
745
  async function ensureMacroPlugins(moduleRoot, toolchainBin) {
@@ -441,6 +821,9 @@ var OPTIONAL_FRAMEWORK_DEPENDENCIES = {
441
821
  CryptoKit: [],
442
822
  CommonCrypto: [],
443
823
  CoreText: [],
824
+ Compression: ["PeachCodec"],
825
+ zlib: ["PeachCodec"],
826
+ PeachCodec: [],
444
827
  Security: ["CryptoKit"],
445
828
  TikTokBusinessSDK: [],
446
829
  nSure: [],
@@ -451,6 +834,66 @@ var OPTIONAL_FRAMEWORK_DEPENDENCIES = {
451
834
  DatadogTrace: ["DatadogCore"]
452
835
  };
453
836
  var OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES));
837
+ var SWIFT_IMPORT = /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/;
838
+ function swiftImportNames(contents, unconditional = false) {
839
+ const names = [];
840
+ let depth = 0;
841
+ for (const line of contents.split("\n")) {
842
+ const directive = /^\s*#(if|endif)\b/.exec(line)?.[1];
843
+ if (directive === "if") depth++;
844
+ else if (directive === "endif") depth = Math.max(0, depth - 1);
845
+ if (unconditional && depth > 0) continue;
846
+ const name = SWIFT_IMPORT.exec(line)?.[1];
847
+ if (name) names.push(name);
848
+ }
849
+ return names;
850
+ }
851
+ function swiftPeachModules(moduleRoot) {
852
+ const distribution = swiftDistributionAt(moduleRoot);
853
+ return distribution ? distribution.modules : [
854
+ ...(0, import_node_fs2.readFileSync)(import_node_path2.default.join(moduleRoot, "Package.swift"), "utf8").matchAll(
855
+ /\.(?:target|systemLibrary)\(\s*name:\s*"([^"]+)"/g
856
+ )
857
+ ].map((match) => match[1]);
858
+ }
859
+ var availableModules = /* @__PURE__ */ new Map();
860
+ function swiftAvailableModules(moduleRoot, toolchainBin) {
861
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId;
862
+ const key = `${moduleRoot}\0${sdk}`;
863
+ const cached = availableModules.get(key);
864
+ if (cached) return cached;
865
+ const modules = new Set(swiftPeachModules(moduleRoot));
866
+ const configuration = (0, import_node_child_process2.execFileSync)(
867
+ import_node_path2.default.join(toolchainBin, "swift"),
868
+ ["sdk", "configure", "--show-configuration", sdk, "wasm32-unknown-wasip1"],
869
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }
870
+ );
871
+ const resources = /^swiftResourcesPath:\s*(.+)$/m.exec(configuration)?.[1]?.trim();
872
+ if (!resources) throw new Error(`swift sdk ${sdk} reports no swiftResourcesPath`);
873
+ for (const entry of (0, import_node_fs2.readdirSync)(import_node_path2.default.join(resources, "wasi"))) {
874
+ if (entry.endsWith(".swiftmodule"))
875
+ modules.add(entry.slice(0, -".swiftmodule".length));
876
+ }
877
+ for (const entry of (0, import_node_fs2.readdirSync)(resources)) {
878
+ const map = import_node_path2.default.join(resources, entry, "module.modulemap");
879
+ if (!(0, import_node_fs2.existsSync)(map)) continue;
880
+ for (const match of (0, import_node_fs2.readFileSync)(map, "utf8").matchAll(/^module\s+([A-Za-z_]\w*)/gm))
881
+ modules.add(match[1]);
882
+ }
883
+ availableModules.set(key, modules);
884
+ return modules;
885
+ }
886
+ function missingSwiftModules(files, available) {
887
+ const missing = /* @__PURE__ */ new Map();
888
+ for (const [file, contents] of Object.entries(files)) {
889
+ if (!file.endsWith(".swift") || file === "Package.swift") continue;
890
+ for (const name of new Set(swiftImportNames(contents, true))) {
891
+ if (available.has(name)) continue;
892
+ missing.set(name, [...missing.get(name) ?? [], file]);
893
+ }
894
+ }
895
+ return new Map([...missing].sort(([left], [right]) => left.localeCompare(right)));
896
+ }
454
897
  function swiftTargetDependencies(files, targets) {
455
898
  const names = /* @__PURE__ */ new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)]);
456
899
  const siblings = /* @__PURE__ */ new Map();
@@ -463,10 +906,8 @@ function swiftTargetDependencies(files, targets) {
463
906
  (candidate) => candidate.name !== target.name && candidate.path !== "." && candidate.path.startsWith(prefix) && file.startsWith(`${candidate.path}/`)
464
907
  ))
465
908
  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]);
909
+ for (const name of swiftImportNames(contents)) {
910
+ if (names.has(name) && name !== target.name) deps.add(name);
470
911
  }
471
912
  }
472
913
  siblings.set(target.name, [...deps].sort());
@@ -476,16 +917,14 @@ function swiftTargetDependencies(files, targets) {
476
917
  var ONE_PRODUCT = '.product(name: "One", package: "sootsim-swift")';
477
918
  var SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")';
478
919
  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
- )
920
+ ([file, contents]) => file.endsWith(".swift") && swiftImportNames(contents).includes("SpriteKit")
482
921
  );
483
- var FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"';
922
+ 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
923
  var ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"';
485
- var MULTI_MANIFEST_VERSION = 10;
924
+ var MULTI_MANIFEST_VERSION = 11;
486
925
  function swiftArtifactHash(input, release, moduleRoot) {
487
926
  const hash = (0, import_node_crypto2.createHash)("sha256");
488
- hash.update(`swift-compile/v14
927
+ hash.update(`swift-compile/v16
489
928
  ${release}
490
929
  `);
491
930
  if (input.oneModule) hash.update("one-module\n");
@@ -594,15 +1033,15 @@ function emitSwiftPackageManifest(args) {
594
1033
  }
595
1034
  function syncSwiftTree(base, files) {
596
1035
  (0, import_node_fs2.mkdirSync)(base, { recursive: true });
597
- const walk = (dir) => {
1036
+ const walk2 = (dir) => {
598
1037
  for (const entry of (0, import_node_fs2.readdirSync)(dir, { withFileTypes: true })) {
599
1038
  const full = import_node_path2.default.join(dir, entry.name);
600
1039
  if (dir === base && entry.name === ".build") continue;
601
- if (entry.isDirectory()) walk(full);
1040
+ if (entry.isDirectory()) walk2(full);
602
1041
  else if (!files.has(full)) (0, import_node_fs2.rmSync)(full, { force: true });
603
1042
  }
604
1043
  };
605
- walk(base);
1044
+ walk2(base);
606
1045
  for (const [full, contents] of files) {
607
1046
  if ((0, import_node_fs2.existsSync)(full) && (0, import_node_fs2.readFileSync)(full, "utf8") === contents) continue;
608
1047
  (0, import_node_fs2.mkdirSync)(import_node_path2.default.dirname(full), { recursive: true });
@@ -657,23 +1096,98 @@ function forwardedArguments(parameters) {
657
1096
  }
658
1097
  return args.join(", ");
659
1098
  }
660
- function liftExtensionOverrides(source) {
1099
+ function closingBrace(source, tokens, open) {
1100
+ let depth = 0;
1101
+ for (const at of tokens) {
1102
+ if (at < open) continue;
1103
+ if (source[at] === "{") depth++;
1104
+ else if (source[at] === "}" && --depth === 0) return at + 1;
1105
+ }
1106
+ return source.length;
1107
+ }
1108
+ function scanObjCExtensionMembers(source, tokens, records) {
1109
+ const masked = swiftCodeMask(source);
1110
+ const found = /* @__PURE__ */ new Map();
1111
+ const member = /\b(func|var)\s+([A-Za-z_]\w*)/g;
1112
+ for (const record of records) {
1113
+ const close = closingBrace(source, tokens, record.open);
1114
+ const body = masked.slice(record.open, close);
1115
+ member.lastIndex = 0;
1116
+ for (let match = member.exec(body); match; match = member.exec(body)) {
1117
+ const at = record.open + match.index + match[0].indexOf(match[1]);
1118
+ let depth = 0;
1119
+ for (const token of tokens) {
1120
+ if (token <= record.open) continue;
1121
+ if (token >= at) break;
1122
+ if (source[token] === "{") depth++;
1123
+ else if (source[token] === "}") depth--;
1124
+ }
1125
+ if (depth > 0) continue;
1126
+ const head = masked.slice(record.open, at);
1127
+ const bound = Math.max(
1128
+ head.lastIndexOf(";"),
1129
+ head.lastIndexOf("{"),
1130
+ head.lastIndexOf("}")
1131
+ );
1132
+ const prefix = head.slice(bound + 1);
1133
+ if (/(?:^|[^A-Za-z0-9_$])(?:private|fileprivate|static|class)(?:[^A-Za-z0-9_$]|$)/.test(
1134
+ prefix
1135
+ ))
1136
+ continue;
1137
+ if (!/@objc\b/.test(prefix) && !/@IBAction\b/.test(prefix) && !record.objcMembers)
1138
+ continue;
1139
+ const members = found.get(record.type) ?? /* @__PURE__ */ new Set();
1140
+ members.add(match[2]);
1141
+ found.set(record.type, members);
1142
+ }
1143
+ }
1144
+ return found;
1145
+ }
1146
+ function objcExtensionMemberIndex(sources) {
1147
+ const index = /* @__PURE__ */ new Map();
1148
+ for (const source of sources) {
1149
+ const { tokens } = swiftCodeScan(source);
1150
+ const masked = swiftCodeMask(source);
1151
+ const records = [];
1152
+ let pending = null;
1153
+ for (const at of tokens) {
1154
+ const rest = source.slice(at, at + 600);
1155
+ if (rest.startsWith("{")) {
1156
+ if (pending) records.push({ ...pending, open: at });
1157
+ pending = null;
1158
+ continue;
1159
+ }
1160
+ if (rest.startsWith("}")) continue;
1161
+ const extended = EXTENSION_DECL.exec(rest);
1162
+ if (extended) {
1163
+ const lines = source.lastIndexOf("\n", source.lastIndexOf("\n", at - 1) - 1) + 1;
1164
+ pending = {
1165
+ type: extended[1].split(".").pop(),
1166
+ objcMembers: /@objcMembers\b/.test(masked.slice(lines, at))
1167
+ };
1168
+ }
1169
+ }
1170
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, records)) {
1171
+ const into = index.get(type) ?? /* @__PURE__ */ new Set();
1172
+ for (const member of members) into.add(member);
1173
+ index.set(type, into);
1174
+ }
1175
+ }
1176
+ return index;
1177
+ }
1178
+ function liftExtensionOverrides(source, extraObjCExtensions) {
661
1179
  const { tokens } = swiftCodeScan(source);
1180
+ const masked = swiftCodeMask(source);
662
1181
  const stack = [];
663
1182
  let pending = null;
664
1183
  const classes = /* @__PURE__ */ new Map();
665
1184
  let declaredBase = null;
666
1185
  let declaredObjCMembers = false;
1186
+ const extensions = [];
1187
+ let declaredExtObjCMembers = false;
667
1188
  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
- };
1189
+ const overrides = [];
1190
+ const closing = (open) => closingBrace(source, tokens, open);
677
1191
  for (const at of tokens) {
678
1192
  const rest = source.slice(at, at + 600);
679
1193
  if (rest.startsWith("{")) {
@@ -684,6 +1198,12 @@ function liftExtensionOverrides(source) {
684
1198
  base: declaredBase,
685
1199
  objcMembers: declaredObjCMembers
686
1200
  });
1201
+ if (frame.kind === "extension")
1202
+ extensions.push({
1203
+ type: frame.name,
1204
+ open: at,
1205
+ objcMembers: declaredExtObjCMembers
1206
+ });
687
1207
  stack.push(frame);
688
1208
  pending = null;
689
1209
  continue;
@@ -703,12 +1223,39 @@ function liftExtensionOverrides(source) {
703
1223
  const extended = EXTENSION_DECL.exec(rest);
704
1224
  if (extended) {
705
1225
  pending = { kind: "extension", name: extended[1].split(".").pop() };
1226
+ const lines = source.lastIndexOf("\n", source.lastIndexOf("\n", at - 1) - 1) + 1;
1227
+ declaredExtObjCMembers = /@objcMembers\b/.test(masked.slice(lines, at));
706
1228
  continue;
707
1229
  }
708
1230
  const top = stack.at(-1);
709
- if (!rest.startsWith("override") || top?.kind !== "extension" || pending) continue;
1231
+ if (!rest.startsWith("override") || pending) continue;
710
1232
  const line = source.slice(source.lastIndexOf("\n", at - 1) + 1, at);
711
1233
  const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim());
1234
+ if (top?.kind === "class") {
1235
+ let member;
1236
+ let nameAt = 0;
1237
+ const direct = OVERRIDE_FUNC.exec(rest);
1238
+ if (direct) {
1239
+ member = direct[2];
1240
+ nameAt = at + rest.indexOf(
1241
+ member,
1242
+ rest.indexOf("func", "override".length + direct[1].length) + 4
1243
+ );
1244
+ } else {
1245
+ const property2 = OVERRIDE_VAR.exec(rest);
1246
+ if (property2) {
1247
+ const open = at + property2[0].length - 1;
1248
+ if (!/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) {
1249
+ member = property2[2];
1250
+ nameAt = at + rest.indexOf(member, rest.indexOf("var"));
1251
+ }
1252
+ }
1253
+ }
1254
+ if (member !== void 0 && !modifiers.includes("private") && !modifiers.includes("fileprivate"))
1255
+ overrides.push({ type: top.name, member, at, nameAt });
1256
+ continue;
1257
+ }
1258
+ if (top?.kind !== "extension") continue;
712
1259
  const func = OVERRIDE_FUNC.exec(rest);
713
1260
  if (func) {
714
1261
  const name = func[2];
@@ -726,20 +1273,18 @@ function liftExtensionOverrides(source) {
726
1273
  if (args === null) continue;
727
1274
  const call = (clause.includes("->") ? "return " : "") + (/\b(?:throws|rethrows)\b/.test(clause) ? "try " : "") + (/\basync\b/.test(clause) ? "await " : "") + `__peach_ext_${name}(${args})`;
728
1275
  const signature = `func ${name}${func[3] ?? ""}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ""}`;
1276
+ const nameAt = at + rest.indexOf(name, rest.indexOf("func", "override".length + func[1].length) + 4);
729
1277
  lifted.push({
730
1278
  type: top.name,
731
1279
  member: name,
732
- stub: `${[...modifiers, "override"].join(" ")} ${signature} { ${call} };`,
1280
+ at,
1281
+ modifiers,
1282
+ decl: signature,
1283
+ forward: `{ ${call} };`,
1284
+ nameAt,
733
1285
  edits: [
734
1286
  [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
- ]
1287
+ [nameAt, 0, "__peach_ext_"]
743
1288
  ]
744
1289
  });
745
1290
  continue;
@@ -749,42 +1294,79 @@ function liftExtensionOverrides(source) {
749
1294
  const open = at + property[0].length - 1;
750
1295
  if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue;
751
1296
  const name = property[2];
1297
+ const nameAt = at + rest.indexOf(name, rest.indexOf("var"));
752
1298
  lifted.push({
753
1299
  type: top.name,
754
1300
  member: name,
755
- stub: `${[...modifiers, "override"].join(" ")} var ${name}: ${property[3].trim()} { __peach_ext_${name} };`,
1301
+ at,
1302
+ modifiers,
1303
+ decl: `var ${name}: ${property[3].trim()}`,
1304
+ forward: `{ __peach_ext_${name} };`,
1305
+ nameAt,
756
1306
  edits: [
757
1307
  [at, "override".length, " ".repeat("override".length)],
758
- [at + rest.indexOf(name, rest.indexOf("var")), 0, "__peach_ext_"]
1308
+ [nameAt, 0, "__peach_ext_"]
759
1309
  ]
760
1310
  });
761
1311
  }
762
1312
  }
763
- const overridesObjC = (type, member) => {
1313
+ const extIndex = /* @__PURE__ */ new Map();
1314
+ if (extraObjCExtensions)
1315
+ for (const [type, members] of extraObjCExtensions)
1316
+ extIndex.set(type, new Set(members));
1317
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, extensions)) {
1318
+ const into = extIndex.get(type) ?? /* @__PURE__ */ new Set();
1319
+ for (const member of members) into.add(member);
1320
+ extIndex.set(type, into);
1321
+ }
1322
+ const overrideKind = (type, member) => {
764
1323
  let base = classes.get(type)?.base ?? null;
765
1324
  while (base !== null) {
766
- if (APPLE_CLASS.test(base)) return true;
767
1325
  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;
1326
+ if (declaredClass) {
1327
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace));
1328
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body);
1329
+ if (found) {
1330
+ const line = body.slice(body.lastIndexOf("\n", found.index) + 1, found.index);
1331
+ return declaredClass.objcMembers || /@objc\b/.test(line) ? "objc" : "plain";
1332
+ }
1333
+ if (extIndex.get(base)?.has(member)) return "ext";
1334
+ base = declaredClass.base;
1335
+ } else if (extIndex.get(base)?.has(member)) return "ext";
1336
+ else if (APPLE_CLASS.test(base)) return "apple";
1337
+ else return "unknown";
776
1338
  }
777
- return false;
1339
+ return "unknown";
778
1340
  };
1341
+ const rename = (at, nameAt) => [
1342
+ [at, "override".length, " ".repeat("override".length)],
1343
+ [nameAt, 0, "__peach_ovr_"]
1344
+ ];
779
1345
  const edits = [];
780
1346
  const stubs = /* @__PURE__ */ new Map();
781
1347
  for (const entry of lifted) {
782
1348
  const brace = classes.get(entry.type)?.brace;
783
- if (brace === void 0 || !overridesObjC(entry.type, entry.member)) continue;
1349
+ if (brace === void 0) continue;
1350
+ const kind = overrideKind(entry.type, entry.member);
1351
+ if (kind !== "apple" && kind !== "objc" && kind !== "ext") continue;
1352
+ if (kind === "ext" && (entry.modifiers.includes("private") || entry.modifiers.includes("fileprivate")))
1353
+ continue;
1354
+ if (kind === "ext") {
1355
+ edits.push(...rename(entry.at, entry.nameAt));
1356
+ continue;
1357
+ }
784
1358
  edits.push(...entry.edits);
785
- stubs.set(brace, [...stubs.get(brace) ?? [], entry.stub]);
1359
+ const head = [...entry.modifiers, "override"].filter((word) => word !== "").join(" ");
1360
+ stubs.set(brace, [
1361
+ ...stubs.get(brace) ?? [],
1362
+ `${head} ${entry.decl} ${entry.forward}`
1363
+ ]);
786
1364
  }
787
- for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(" ")}`]);
1365
+ for (const candidate of overrides) {
1366
+ if (overrideKind(candidate.type, candidate.member) !== "ext") continue;
1367
+ edits.push(...rename(candidate.at, candidate.nameAt));
1368
+ }
1369
+ for (const [brace, list2] of stubs) edits.push([brace + 1, 0, ` ${list2.join(" ")}`]);
788
1370
  let out = source;
789
1371
  for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
790
1372
  out = out.slice(0, at) + insert + out.slice(at + remove);
@@ -964,8 +1546,8 @@ function swiftCodeMask(source) {
964
1546
  scanCode(0, false);
965
1547
  return chars.join("");
966
1548
  }
967
- function swiftSourceAsIOS(original) {
968
- const source = liftExtensionOverrides(original);
1549
+ function swiftSourceAsIOS(original, extraObjCExtensions) {
1550
+ const source = liftExtensionOverrides(original, extraObjCExtensions);
969
1551
  const { lineStarts, tokens } = swiftCodeScan(source);
970
1552
  let offset = 0;
971
1553
  const conditioned = source.split("\n").map((line) => {
@@ -980,9 +1562,14 @@ function swiftSourceAsIOS(original) {
980
1562
  const reusableBodies = [];
981
1563
  let depth = 0;
982
1564
  let opensReusableBody = false;
1565
+ const sceneLifecycleBodies = /* @__PURE__ */ new Set();
983
1566
  for (const at of tokens) {
984
1567
  const rest = conditioned.slice(at, at + 400);
985
1568
  if (rest.startsWith("{")) {
1569
+ if (sceneLifecycleBodies.has(at)) {
1570
+ out += conditioned.slice(copied, at + 1) + " public var _peachUsesSceneLifecycle: Bool { true };";
1571
+ copied = at + 1;
1572
+ }
986
1573
  depth++;
987
1574
  if (opensReusableBody) reusableBodies.push(depth);
988
1575
  opensReusableBody = false;
@@ -1018,12 +1605,33 @@ function swiftSourceAsIOS(original) {
1018
1605
  opensReusableBody = true;
1019
1606
  }
1020
1607
  const modifiers = conditioned.slice(conditioned.lastIndexOf("\n", at - 1) + 1, at);
1608
+ const delegateClass = DELEGATE_CLASS.exec(rest);
1609
+ if (delegateClass && /\bUIApplicationDelegate\b/.test(delegateClass[0])) {
1610
+ const body = at + delegateClass[0].lastIndexOf("{");
1611
+ let bodyDepth = 0;
1612
+ for (const token of tokens) {
1613
+ if (token < body) continue;
1614
+ if (conditioned[token] === "{") bodyDepth++;
1615
+ else if (conditioned[token] === "}" && --bodyDepth === 0) break;
1616
+ else if (bodyDepth === 1 && /^func\s+application\s*\([^{}]*\bconfigurationForConnecting\s+/.test(
1617
+ conditioned.slice(token, token + 600)
1618
+ )) {
1619
+ sceneLifecycleBodies.add(body);
1620
+ break;
1621
+ }
1622
+ }
1623
+ }
1021
1624
  if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
1022
1625
  out += `${conditioned.slice(copied, at)}final `;
1023
1626
  copied = at;
1024
1627
  }
1025
1628
  continue;
1026
1629
  }
1630
+ if (/^@UIApplicationMain\b/.test(rest)) {
1631
+ out += conditioned.slice(copied, at) + "@main".padEnd("@UIApplicationMain".length);
1632
+ copied = at + "@UIApplicationMain".length;
1633
+ continue;
1634
+ }
1027
1635
  const selector = SELECTOR.exec(rest);
1028
1636
  const match = selector ?? OBJC_ATTRIBUTE.exec(rest);
1029
1637
  if (!match) continue;
@@ -1040,6 +1648,19 @@ function swiftSourceAsIOS(original) {
1040
1648
  }
1041
1649
  return lowerAnyObjectDoubleValue(out + conditioned.slice(copied));
1042
1650
  }
1651
+ function swiftApplicationEntry(file, source) {
1652
+ const { tokens } = swiftCodeScan(source);
1653
+ let depth = 0;
1654
+ for (const at of tokens) {
1655
+ if (source[at] === "{") depth++;
1656
+ else if (source[at] === "}") depth--;
1657
+ else if (depth === 0 && /^@(?:main|UIApplicationMain)\b/.test(source.slice(at)))
1658
+ return true;
1659
+ else if (depth === 0 && import_node_path2.default.basename(file) === "main.swift" && /^UIApplicationMain\s*\(/.test(source.slice(at)))
1660
+ return true;
1661
+ }
1662
+ return false;
1663
+ }
1043
1664
  function swiftCodeScan(source) {
1044
1665
  const starts = /* @__PURE__ */ new Set();
1045
1666
  const tokens = [];
@@ -1122,7 +1743,7 @@ function swiftCodeScan(source) {
1122
1743
  else top.parens--;
1123
1744
  i++;
1124
1745
  } else {
1125
- const keyword = source.startsWith("class", i) ? "class" : source.startsWith("extension", i) ? "extension" : source.startsWith("override", i) ? "override" : source.startsWith("import", i) ? "import" : source.startsWith("NSClassFromString", i) ? "NSClassFromString" : null;
1746
+ const keyword = source.startsWith("class", i) ? "class" : source.startsWith("extension", i) ? "extension" : source.startsWith("override", i) ? "override" : source.startsWith("import", i) ? "import" : source.startsWith("func", i) ? "func" : source.startsWith("UIApplicationMain", i) ? "UIApplicationMain" : source.startsWith("NSClassFromString", i) ? "NSClassFromString" : null;
1126
1747
  if (keyword && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + keyword.length] ?? "")) {
1127
1748
  tokens.push(i);
1128
1749
  i += keyword.length;
@@ -1134,7 +1755,7 @@ function swiftCodeScan(source) {
1134
1755
  }
1135
1756
  return { lineStarts: starts, tokens };
1136
1757
  }
1137
- var compiledSource = (file, contents) => file.endsWith(".swift") ? swiftSourceAsIOS(contents) : contents;
1758
+ var compiledSource = (file, contents, extraObjCExtensions) => file.endsWith(".swift") ? swiftSourceAsIOS(contents, extraObjCExtensions) : contents;
1138
1759
  function writeSwiftProject(layout, input, moduleRoot) {
1139
1760
  const resourceTargets = swiftManifestTargets(
1140
1761
  input.files["Package.swift"] ?? "",
@@ -1167,10 +1788,16 @@ function writeSwiftProject(layout, input, moduleRoot) {
1167
1788
  // sootsim-swift files ${modulePlan.digest("hex").slice(0, 16)}
1168
1789
  // resource accessors ${resourcePlan}
1169
1790
  `;
1791
+ const objcExtensions = objcExtensionMemberIndex(
1792
+ Object.entries(input.files).filter(([file]) => file.endsWith(".swift")).map(([, contents]) => contents)
1793
+ );
1170
1794
  if (targets.length === 0) {
1171
1795
  for (const [file, contents] of Object.entries(input.files)) {
1172
1796
  if (file === "Package.swift") continue;
1173
- files.set(import_node_path2.default.join(layout.sources, file), compiledSource(file, contents));
1797
+ files.set(
1798
+ import_node_path2.default.join(layout.sources, file),
1799
+ compiledSource(file, contents, objcExtensions)
1800
+ );
1174
1801
  }
1175
1802
  let manifest = (0, import_node_fs2.readFileSync)(
1176
1803
  import_node_path2.default.join(moduleRoot, "scripts/contrast-app-Package.swift"),
@@ -1216,7 +1843,7 @@ function writeSwiftProject(layout, input, moduleRoot) {
1216
1843
  const base = layout.multi ? layout.root : layout.sources;
1217
1844
  for (const [file, contents] of Object.entries(input.files)) {
1218
1845
  if (file === "Package.swift") continue;
1219
- files.set(import_node_path2.default.join(base, file), compiledSource(file, contents));
1846
+ files.set(import_node_path2.default.join(base, file), compiledSource(file, contents, objcExtensions));
1220
1847
  }
1221
1848
  files.set(
1222
1849
  import_node_path2.default.join(layout.root, "Package.swift"),
@@ -1342,10 +1969,16 @@ function compileSwiftProjectUnit(input, options) {
1342
1969
  plugin
1343
1970
  ])
1344
1971
  ],
1345
- { env: BUILD_ENV, maxBuffer: 64 * 1024 * 1024, timeout: options.timeoutMs }
1972
+ {
1973
+ env: BUILD_ENV,
1974
+ maxBuffer: 64 * 1024 * 1024,
1975
+ timeout: options.timeoutMs
1976
+ }
1346
1977
  );
1347
1978
  } catch (error) {
1348
- throw new Error(projectDiagnostic(outputOf(error), layout), { cause: error });
1979
+ throw new Error(projectDiagnostic(outputOf(error), layout), {
1980
+ cause: error
1981
+ });
1349
1982
  }
1350
1983
  return {
1351
1984
  hash,
@@ -1357,9 +1990,9 @@ function compileSwiftProjectUnit(input, options) {
1357
1990
 
1358
1991
  // src/swift-host.ts
1359
1992
  var import_node_crypto4 = require("node:crypto");
1360
- var import_node_fs7 = __toESM(require("node:fs"), 1);
1993
+ var import_node_fs9 = __toESM(require("node:fs"), 1);
1361
1994
  var import_node_os5 = __toESM(require("node:os"), 1);
1362
- var import_node_path8 = __toESM(require("node:path"), 1);
1995
+ var import_node_path10 = __toESM(require("node:path"), 1);
1363
1996
 
1364
1997
  // ../sootsim-swift/src/bundleAssets.ts
1365
1998
  var import_svgpath = __toESM(require("svgpath"), 1);
@@ -1393,15 +2026,15 @@ function pickImagesetFile(images) {
1393
2026
  scale: pick.scale === "2x" ? 2 : pick.scale === "3x" ? 3 : 1
1394
2027
  };
1395
2028
  }
1396
- function flatScale(path9) {
1397
- const match = /@([23])x\.[^./]+$/.exec(path9);
2029
+ function flatScale(path11) {
2030
+ const match = /@([23])x\.[^./]+$/.exec(path11);
1398
2031
  return match ? Number(match[1]) : 1;
1399
2032
  }
1400
2033
  function providesNamespace(text) {
1401
2034
  if (text === null) return false;
1402
2035
  try {
1403
- const parsed = JSON.parse(text);
1404
- return parsed?.properties?.["provides-namespace"] === true;
2036
+ const parsed2 = JSON.parse(text);
2037
+ return parsed2?.properties?.["provides-namespace"] === true;
1405
2038
  } catch {
1406
2039
  return false;
1407
2040
  }
@@ -1421,25 +2054,25 @@ function catalogEntryName(contentsPath, kind, readText) {
1421
2054
  }
1422
2055
  return segments.join("/");
1423
2056
  }
1424
- function isFlatResourceImage(path9) {
1425
- return path9.split("/").includes("Resources") && RASTER_EXTENSIONS.has(extOf(path9));
2057
+ function isFlatResourceImage(path11) {
2058
+ return path11.split("/").includes("Resources") && RASTER_EXTENSIONS.has(extOf(path11));
1426
2059
  }
1427
2060
  function enumerateBundleImages(paths, readText) {
1428
2061
  const table = [];
1429
2062
  const seen = /* @__PURE__ */ new Set();
1430
- const catalogs = paths.filter((path9) => baseOf(path9) === "Contents.json");
2063
+ const catalogs = paths.filter((path11) => baseOf(path11) === "Contents.json");
1431
2064
  for (const contentsPath of catalogs) {
1432
2065
  const name = catalogEntryName(contentsPath, ".imageset", readText);
1433
2066
  if (name === null || seen.has(name)) continue;
1434
- let parsed;
2067
+ let parsed2;
1435
2068
  try {
1436
2069
  const text = readText(contentsPath);
1437
2070
  if (text === null) continue;
1438
- parsed = JSON.parse(text);
2071
+ parsed2 = JSON.parse(text);
1439
2072
  } catch {
1440
2073
  continue;
1441
2074
  }
1442
- const images = parsed?.images;
2075
+ const images = parsed2?.images;
1443
2076
  if (!Array.isArray(images)) continue;
1444
2077
  const dir = contentsPath.split("/").slice(0, -1).join("/");
1445
2078
  const pick = pickImagesetFile(images);
@@ -1448,19 +2081,19 @@ function enumerateBundleImages(paths, readText) {
1448
2081
  seen.add(name);
1449
2082
  table.push({ name, file: `${dir}/${pick.filename}`, scale: pick.scale });
1450
2083
  }
1451
- for (const path9 of paths) {
1452
- if (!isFlatResourceImage(path9)) continue;
1453
- const name = baseOf(path9).slice(0, -extOf(path9).length);
2084
+ for (const path11 of paths) {
2085
+ if (!isFlatResourceImage(path11)) continue;
2086
+ const name = baseOf(path11).slice(0, -extOf(path11).length);
1454
2087
  if (name === "" || seen.has(name)) continue;
1455
2088
  seen.add(name);
1456
- table.push({ name, file: path9, scale: flatScale(path9) });
2089
+ table.push({ name, file: path11, scale: flatScale(path11) });
1457
2090
  }
1458
2091
  return table;
1459
2092
  }
1460
2093
  function colorComponent(value) {
1461
2094
  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;
2095
+ const parsed2 = value.startsWith("0x") ? Number.parseInt(value.slice(2), 16) / 255 : value.includes(".") ? Number.parseFloat(value) : Number.parseInt(value, 10) / 255;
2096
+ return Number.isFinite(parsed2) ? parsed2 : null;
1464
2097
  }
1465
2098
  function colorsetValue(color) {
1466
2099
  if (typeof color !== "object" || color === null) return null;
@@ -1482,7 +2115,7 @@ function colorsetValue(color) {
1482
2115
  }
1483
2116
  function enumerateBundleColors(paths, readText) {
1484
2117
  const table = {};
1485
- for (const contentsPath of paths.filter((path9) => baseOf(path9) === "Contents.json")) {
2118
+ for (const contentsPath of paths.filter((path11) => baseOf(path11) === "Contents.json")) {
1486
2119
  const name = catalogEntryName(contentsPath, ".colorset", readText);
1487
2120
  if (name === null || name in table) continue;
1488
2121
  let colors;
@@ -1501,12 +2134,12 @@ function enumerateBundleColors(paths, readText) {
1501
2134
  const idiom = Reflect.get(entry, "idiom");
1502
2135
  if (idiom !== "universal" && idiom !== "iphone") continue;
1503
2136
  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(
2137
+ const list2 = Array.isArray(appearances) ? appearances : [];
2138
+ if (list2.some((item) => Reflect.get(item, "appearance") === "contrast")) continue;
2139
+ const isDark = list2.some(
1507
2140
  (item) => Reflect.get(item, "appearance") === "luminosity" && Reflect.get(item, "value") === "dark"
1508
2141
  );
1509
- if (list.length > 0 && !isDark) continue;
2142
+ if (list2.length > 0 && !isDark) continue;
1510
2143
  const value = colorsetValue(Reflect.get(entry, "color"));
1511
2144
  if (value === null) continue;
1512
2145
  if (isDark) dark = value;
@@ -1547,8 +2180,8 @@ function axisExtremes(points) {
1547
2180
  function pathBounds(d) {
1548
2181
  const xs = [];
1549
2182
  const ys = [];
1550
- for (const path9 of d)
1551
- (0, import_svgpath.default)(path9).abs().unshort().unarc().iterate((segment, _index, x, y) => {
2183
+ for (const path11 of d)
2184
+ (0, import_svgpath.default)(path11).abs().unshort().unarc().iterate((segment, _index, x, y) => {
1552
2185
  const [command, ...args] = segment;
1553
2186
  if (command === "M" || command === "L") {
1554
2187
  xs.push(Number(args[0]));
@@ -1575,7 +2208,7 @@ function guide(svg, id, axis) {
1575
2208
  }
1576
2209
  function enumerateBundleSymbols(paths, readText) {
1577
2210
  const table = {};
1578
- for (const contentsPath of paths.filter((path9) => baseOf(path9) === "Contents.json")) {
2211
+ for (const contentsPath of paths.filter((path11) => baseOf(path11) === "Contents.json")) {
1579
2212
  const name = catalogEntryName(contentsPath, ".symbolset", readText);
1580
2213
  if (name === null || name in table) continue;
1581
2214
  let symbols;
@@ -1608,8 +2241,8 @@ function enumerateBundleSymbols(paths, readText) {
1608
2241
  viewBox: "0 0 24 24",
1609
2242
  advance,
1610
2243
  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()
2244
+ layers: d.map((path11) => ({
2245
+ d: (0, import_svgpath.default)(path11).abs().scale(scale).translate(translateX, translateY).round(3).toString()
1613
2246
  }))
1614
2247
  };
1615
2248
  }
@@ -1619,7 +2252,7 @@ function enumerateBundleJson(paths) {
1619
2252
  const found = [];
1620
2253
  const seen = /* @__PURE__ */ new Set();
1621
2254
  const ordered = [...paths].filter(
1622
- (path9) => path9.split("/").includes("Resources") && path9.split("/").every((segment) => segment !== "" && segment !== "..") && (extOf(path9) === ".json" || extOf(path9) === ".xcstrings")
2255
+ (path11) => path11.split("/").includes("Resources") && path11.split("/").every((segment) => segment !== "" && segment !== "..") && (extOf(path11) === ".json" || extOf(path11) === ".xcstrings")
1623
2256
  ).sort((a, b) => {
1624
2257
  const aDepth = a.split("/").length;
1625
2258
  const bDepth = b.split("/").length;
@@ -1727,8 +2360,8 @@ function readSharedDesktopAuthSession() {
1727
2360
  const filepath = getSharedDesktopAuthFilePath();
1728
2361
  if (!(0, import_node_fs3.existsSync)(filepath)) return null;
1729
2362
  try {
1730
- const parsed = JSON.parse((0, import_node_fs3.readFileSync)(filepath, "utf8"));
1731
- const normalized = normalizeSession(parsed);
2363
+ const parsed2 = JSON.parse((0, import_node_fs3.readFileSync)(filepath, "utf8"));
2364
+ const normalized = normalizeSession(parsed2);
1732
2365
  if (!normalized) {
1733
2366
  (0, import_node_fs3.rmSync)(filepath, { force: true });
1734
2367
  return null;
@@ -1825,9 +2458,9 @@ function resolveContrastBackendOrigin(currentOrigin) {
1825
2458
  const origin = currentOrigin?.trim();
1826
2459
  if (!origin) return DEFAULT_CONTRAST_BACKEND_ORIGIN;
1827
2460
  try {
1828
- const parsed = new URL(origin);
1829
- if (isLoopbackHost(parsed.hostname) || isContrastBackendHost(parsed.hostname)) {
1830
- return parsed.origin;
2461
+ const parsed2 = new URL(origin);
2462
+ if (isLoopbackHost(parsed2.hostname) || isContrastBackendHost(parsed2.hostname)) {
2463
+ return parsed2.origin;
1831
2464
  }
1832
2465
  } catch {
1833
2466
  }
@@ -1849,7 +2482,7 @@ var import_promises = require("node:stream/promises");
1849
2482
  async function installVerifiedTarball(tarball) {
1850
2483
  const { url, digest, destDir, installedMarker, label } = tarball;
1851
2484
  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");
2485
+ const archivePath = import_node_path5.default.join(downloadDir, "archive");
1853
2486
  import_node_fs4.default.mkdirSync(import_node_path5.default.dirname(destDir), { recursive: true });
1854
2487
  const tmpDir = import_node_fs4.default.mkdtempSync(
1855
2488
  import_node_path5.default.join(import_node_path5.default.dirname(destDir), `.installing-${import_node_path5.default.basename(destDir)}-`)
@@ -1862,7 +2495,8 @@ async function installVerifiedTarball(tarball) {
1862
2495
  `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
1863
2496
  );
1864
2497
  }
1865
- await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
2498
+ if (new URL(url).pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir);
2499
+ else await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
1866
2500
  if (!import_node_fs4.default.existsSync(import_node_path5.default.join(tmpDir, installedMarker))) {
1867
2501
  throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
1868
2502
  }
@@ -1924,41 +2558,47 @@ function digestFile(filePath, algorithm, encoding) {
1924
2558
  stream.on("end", () => resolve2(hash.digest(encoding)));
1925
2559
  });
1926
2560
  }
2561
+ function extractZip(zipPath, destDir) {
2562
+ return runExtractor("ditto", ["-x", "-k", zipPath, destDir]);
2563
+ }
1927
2564
  function extractTarball(tarPath, destDir, stripComponents) {
2565
+ const args = ["-xzf", tarPath, "-C", destDir];
2566
+ if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
2567
+ return runExtractor("tar", args);
2568
+ }
2569
+ function runExtractor(command, args) {
1928
2570
  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, {
2571
+ const child = (0, import_node_child_process3.spawn)(command, args, {
1932
2572
  stdio: ["ignore", "inherit", "inherit"]
1933
2573
  });
1934
2574
  child.on("error", reject);
1935
2575
  child.on("exit", (code) => {
1936
2576
  if (code === 0) resolve2();
1937
- else reject(new Error(`tar exited with code ${code}`));
2577
+ else reject(new Error(`${command} exited with code ${code}`));
1938
2578
  });
1939
2579
  });
1940
2580
  }
1941
2581
 
1942
2582
  // src/swift-distribution.lock.json
1943
2583
  var swift_distribution_lock_default = {
1944
- id: "42c53105b2e06d39",
2584
+ id: "d27a9b6d2aee64d4",
1945
2585
  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",
2586
+ wasmSdkId: "swift-6.3-RELEASE_wasm-peach-41921598-peach-26be2317",
2587
+ wasmSdkUrl: "https://r2.sootsim.com/swift-wasm-sdk/swift-6.3-RELEASE_wasm-peach-41921598-peach-26be2317.artifactbundle.tar.gz",
2588
+ wasmSdkChecksum: "f34f29d9426f42b04d1c38585d61cf38ecb5357f4287c4843870bec63de6b08c",
2589
+ source: "8f9873608a950d832ec49cf4bbc32fb65689e5f7",
1950
2590
  hosts: {
1951
2591
  "darwin-arm64": {
1952
- sha256: "d58abb1193369130460267e9cc57330f13de28e7a3aa404aeb7b9323cbd29384",
1953
- size: 7115901
2592
+ sha256: "b7fa68565ae1be6ee7964390b4d07949228894ac4a06fe7f58e4238dd0650197",
2593
+ size: 19319227
1954
2594
  },
1955
2595
  "linux-x64": {
1956
- sha256: "1cdd181fdd228e9f928367820cd39db2e703a7af47a819f7d26ed77b96839309",
1957
- size: 7121403
2596
+ sha256: "733ebee3a16142c97575532daf49990df57171ede17de6530a9c5906471d96ca",
2597
+ size: 19324099
1958
2598
  },
1959
2599
  "linux-arm64": {
1960
- sha256: "288e3ff43c881a63ec201856a61a90de323e8aa01714d47be65e8cac98af1738",
1961
- size: 7120448
2600
+ sha256: "84b258d95a71536392f25d2afb8c40835df771594a2c0e42049ee33781ce78ad",
2601
+ size: 19323438
1962
2602
  }
1963
2603
  }
1964
2604
  };
@@ -2089,6 +2729,190 @@ function swiftModuleToolchain(root) {
2089
2729
  };
2090
2730
  }
2091
2731
 
2732
+ // src/swift-remote-packages.ts
2733
+ var import_node_child_process5 = require("node:child_process");
2734
+ var import_node_fs7 = __toESM(require("node:fs"), 1);
2735
+ var import_node_path8 = __toESM(require("node:path"), 1);
2736
+ var REMOTE_CHECKOUTS = import_node_path8.default.join(".build", "peach", "checkouts");
2737
+ var C_FAMILY = /\.(c|cc|cpp|cxx|m|mm|s|S)$/;
2738
+ function readPins(resolved) {
2739
+ const data = JSON.parse(import_node_fs7.default.readFileSync(resolved, "utf8"));
2740
+ const pins = data && typeof data === "object" && "pins" in data && Array.isArray(data.pins) ? data.pins : null;
2741
+ if (!pins)
2742
+ throw new Error(`${resolved} has no pins; resolve packages in a current Xcode`);
2743
+ const out = /* @__PURE__ */ new Map();
2744
+ for (const pin of pins) {
2745
+ const identity = pin?.identity;
2746
+ const location = pin?.location;
2747
+ const revision = pin?.state?.revision;
2748
+ if (typeof identity === "string" && typeof location === "string" && typeof revision === "string")
2749
+ out.set(identity, { location, revision });
2750
+ }
2751
+ return out;
2752
+ }
2753
+ function walk(dir) {
2754
+ if (!import_node_fs7.default.existsSync(dir)) return [];
2755
+ const out = [];
2756
+ for (const entry of import_node_fs7.default.readdirSync(dir, { withFileTypes: true })) {
2757
+ if (entry.name.startsWith(".")) continue;
2758
+ const full = import_node_path8.default.join(dir, entry.name);
2759
+ if (entry.isDirectory()) out.push(...walk(full));
2760
+ else if (entry.isFile()) out.push(full);
2761
+ }
2762
+ return out.sort();
2763
+ }
2764
+ var verified2 = /* @__PURE__ */ new Set();
2765
+ function checkout(checkouts, identity, pin) {
2766
+ const dir = import_node_path8.default.join(checkouts, identity);
2767
+ const key = `${dir}\0${pin.revision}`;
2768
+ if (verified2.has(key)) return dir;
2769
+ const git = (...args) => (0, import_node_child_process5.execFileSync)("git", ["-C", dir, ...args], {
2770
+ encoding: "utf8",
2771
+ stdio: ["ignore", "pipe", "pipe"]
2772
+ }).trim();
2773
+ const current = import_node_fs7.default.existsSync(import_node_path8.default.join(dir, ".git")) ? git("rev-parse", "HEAD") : "";
2774
+ if (current !== pin.revision) {
2775
+ import_node_fs7.default.rmSync(dir, { recursive: true, force: true });
2776
+ import_node_fs7.default.mkdirSync(dir, { recursive: true });
2777
+ try {
2778
+ git("init", "-q");
2779
+ git("fetch", "-q", "--depth", "1", pin.location, pin.revision);
2780
+ git("checkout", "-q", "FETCH_HEAD");
2781
+ } catch (error) {
2782
+ import_node_fs7.default.rmSync(dir, { recursive: true, force: true });
2783
+ const stderr = error instanceof Error && "stderr" in error ? String(error.stderr).trim() : "";
2784
+ throw new Error(
2785
+ `could not fetch ${pin.location} at ${pin.revision}${stderr ? `: ${stderr}` : ""}`
2786
+ );
2787
+ }
2788
+ }
2789
+ verified2.add(key);
2790
+ return dir;
2791
+ }
2792
+ function resolveRemotePackages(projectDir, resolved, products, provided) {
2793
+ const result = { targets: [], unavailable: /* @__PURE__ */ new Map() };
2794
+ const wanted = products.filter((entry) => !provided.has(entry.product));
2795
+ if (wanted.length === 0) return result;
2796
+ if (!resolved) {
2797
+ for (const entry of wanted)
2798
+ result.unavailable.set(entry.product, {
2799
+ repositoryURL: entry.repositoryURL,
2800
+ reason: "no Package.resolved pins it; resolve packages in Xcode once"
2801
+ });
2802
+ return result;
2803
+ }
2804
+ const pins = readPins(resolved);
2805
+ const checkouts = import_node_path8.default.join(projectDir, REMOTE_CHECKOUTS);
2806
+ import_node_fs7.default.mkdirSync(checkouts, { recursive: true });
2807
+ import_node_fs7.default.writeFileSync(import_node_path8.default.join(import_node_path8.default.dirname(checkouts), ".gitignore"), "*\n");
2808
+ const packages = /* @__PURE__ */ new Map();
2809
+ const load2 = (identity) => {
2810
+ const cached = packages.get(identity);
2811
+ if (cached) return cached;
2812
+ const pin = pins.get(identity);
2813
+ if (!pin) return null;
2814
+ const dir = checkout(checkouts, identity, pin);
2815
+ const manifest = import_node_fs7.default.readFileSync(import_node_path8.default.join(dir, "Package.swift"), "utf8");
2816
+ const loaded = { dir, manifest, graph: swiftManifestGraph(manifest) };
2817
+ packages.set(identity, loaded);
2818
+ return loaded;
2819
+ };
2820
+ const targets = /* @__PURE__ */ new Map();
2821
+ const outcomes = /* @__PURE__ */ new Map();
2822
+ const resolveProduct = (identity, product) => {
2823
+ const key = `${identity}\0${product}`;
2824
+ if (outcomes.has(key)) return outcomes.get(key);
2825
+ outcomes.set(key, null);
2826
+ const pkg = load2(identity);
2827
+ if (!pkg) {
2828
+ outcomes.set(key, `package ${identity} is not pinned in Package.resolved`);
2829
+ return outcomes.get(key);
2830
+ }
2831
+ const roots = pkg.graph.products.get(product);
2832
+ if (!roots) {
2833
+ outcomes.set(key, `package ${identity} has no library ${product}`);
2834
+ return outcomes.get(key);
2835
+ }
2836
+ const declared = new Map(
2837
+ swiftManifestTargets(pkg.manifest).map((target) => [target.name, target])
2838
+ );
2839
+ const reached = [];
2840
+ const seen = /* @__PURE__ */ new Set();
2841
+ const pending = [...roots];
2842
+ let reason = null;
2843
+ while (pending.length > 0 && !reason) {
2844
+ const name = pending.pop();
2845
+ if (seen.has(name) || provided.has(name)) continue;
2846
+ seen.add(name);
2847
+ if (pkg.graph.binaryTargets.has(name)) {
2848
+ reason = `${name} is a binary framework`;
2849
+ break;
2850
+ }
2851
+ if (pkg.graph.systemLibraries.has(name)) {
2852
+ reason = `${name} is a system C library`;
2853
+ break;
2854
+ }
2855
+ const target = declared.get(name);
2856
+ if (!target) {
2857
+ reason = `${identity} declares no target ${name}`;
2858
+ break;
2859
+ }
2860
+ const files = walk(import_node_path8.default.join(pkg.dir, target.path));
2861
+ if (files.some((file) => C_FAMILY.test(file))) {
2862
+ reason = `${name} is a C or Objective-C target`;
2863
+ break;
2864
+ }
2865
+ reached.push(target);
2866
+ for (const dependency of pkg.graph.dependencies.get(name) ?? []) {
2867
+ if (dependency.kind === "target") pending.push(dependency.name);
2868
+ else if (!provided.has(dependency.name)) {
2869
+ const url = pkg.graph.packageURLs.get(dependency.package);
2870
+ const nested = resolveProduct(
2871
+ url ? swiftPackageIdentity(url) : dependency.package,
2872
+ dependency.name
2873
+ );
2874
+ if (nested) reason = `${dependency.name}: ${nested}`;
2875
+ }
2876
+ }
2877
+ }
2878
+ if (reason) {
2879
+ outcomes.set(key, reason);
2880
+ return reason;
2881
+ }
2882
+ const relative = reached.flatMap(
2883
+ (target) => walk(import_node_path8.default.join(pkg.dir, target.path)).map(
2884
+ (file) => import_node_path8.default.relative(pkg.dir, file).split(import_node_path8.default.sep).join(import_node_path8.default.posix.sep)
2885
+ )
2886
+ );
2887
+ const withResources = new Map(
2888
+ swiftManifestTargets(pkg.manifest, relative).map((target) => [target.name, target])
2889
+ );
2890
+ for (const target of reached) {
2891
+ const dir = import_node_path8.default.join(pkg.dir, target.path);
2892
+ targets.set(target.name, {
2893
+ ...withResources.get(target.name) ?? target,
2894
+ executable: false,
2895
+ dir,
2896
+ files: walk(dir)
2897
+ });
2898
+ }
2899
+ return null;
2900
+ };
2901
+ for (const entry of wanted) {
2902
+ const reason = resolveProduct(
2903
+ swiftPackageIdentity(entry.repositoryURL),
2904
+ entry.product
2905
+ );
2906
+ if (reason)
2907
+ result.unavailable.set(entry.product, {
2908
+ repositoryURL: entry.repositoryURL,
2909
+ reason
2910
+ });
2911
+ }
2912
+ result.targets = [...targets.values()];
2913
+ return result;
2914
+ }
2915
+
2092
2916
  // src/swift-submit.ts
2093
2917
  var SWIFT_COMPILE_PATH = "/api/swift-compile";
2094
2918
  var MAX_SWIFT_COMPILE_FILES = 256;
@@ -2099,7 +2923,7 @@ var MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES = 8 * 1024 * 1024;
2099
2923
  var MAX_SWIFT_COMPILE_IMAGES = 128;
2100
2924
  var MAX_SWIFT_COMPILE_IMAGE_BYTES = 4 * 1024 * 1024;
2101
2925
  var MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES = 16 * 1024 * 1024;
2102
- var SWIFT_HOST_ABI = 21;
2926
+ var SWIFT_HOST_ABI = 24;
2103
2927
  var POLL_INTERVAL_MS = 1500;
2104
2928
  function swiftNativeEntry(native, file) {
2105
2929
  return {
@@ -2225,6 +3049,445 @@ async function compileSwiftProject(submit, work, origin, signal) {
2225
3049
  }
2226
3050
  }
2227
3051
 
3052
+ // src/xcode-project.ts
3053
+ var import_node_fs8 = __toESM(require("node:fs"), 1);
3054
+ var import_node_path9 = __toESM(require("node:path"), 1);
3055
+ var import_plist = __toESM(require_plist(), 1);
3056
+ function parseOpenStepPlist(text) {
3057
+ let i = 0;
3058
+ const fail = (message) => {
3059
+ const line = text.slice(0, i).split("\n").length;
3060
+ throw new Error(`project.pbxproj line ${line}: ${message}`);
3061
+ };
3062
+ const skip = () => {
3063
+ for (; ; ) {
3064
+ const ch = text[i];
3065
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") i++;
3066
+ else if (ch === "/" && text[i + 1] === "*") {
3067
+ const end = text.indexOf("*/", i + 2);
3068
+ if (end < 0) fail("unterminated comment");
3069
+ i = end + 2;
3070
+ } else if (ch === "/" && text[i + 1] === "/") {
3071
+ const end = text.indexOf("\n", i);
3072
+ i = end < 0 ? text.length : end + 1;
3073
+ } else return;
3074
+ }
3075
+ };
3076
+ const quoted = () => {
3077
+ i++;
3078
+ let out = "";
3079
+ for (; ; ) {
3080
+ const ch = text[i++];
3081
+ if (ch === void 0) fail("unterminated string");
3082
+ if (ch === '"') return out;
3083
+ if (ch !== "\\") {
3084
+ out += ch;
3085
+ continue;
3086
+ }
3087
+ const next = text[i++];
3088
+ if (next === "n") out += "\n";
3089
+ else if (next === "t") out += " ";
3090
+ else if (next === "r") out += "\r";
3091
+ else if (next === "U") {
3092
+ out += String.fromCharCode(parseInt(text.slice(i, i + 4), 16));
3093
+ i += 4;
3094
+ } else out += next;
3095
+ }
3096
+ };
3097
+ const value = () => {
3098
+ skip();
3099
+ const ch = text[i];
3100
+ if (ch === "{") {
3101
+ i++;
3102
+ const dict = {};
3103
+ for (; ; ) {
3104
+ skip();
3105
+ if (text[i] === "}") {
3106
+ i++;
3107
+ return dict;
3108
+ }
3109
+ const key = value();
3110
+ if (typeof key !== "string") fail("dictionary key is not a string");
3111
+ skip();
3112
+ if (text[i++] !== "=") fail("expected =");
3113
+ dict[key] = value();
3114
+ skip();
3115
+ if (text[i++] !== ";") fail("expected ;");
3116
+ }
3117
+ }
3118
+ if (ch === "(") {
3119
+ i++;
3120
+ const list2 = [];
3121
+ for (; ; ) {
3122
+ skip();
3123
+ if (text[i] === ")") {
3124
+ i++;
3125
+ return list2;
3126
+ }
3127
+ list2.push(value());
3128
+ skip();
3129
+ if (text[i] === ",") i++;
3130
+ else if (text[i] !== ")") fail("expected , or )");
3131
+ }
3132
+ }
3133
+ if (ch === '"') return quoted();
3134
+ const start = i;
3135
+ while (i < text.length && /[A-Za-z0-9_$+/:.\-<>]/.test(text[i])) i++;
3136
+ if (i === start) fail(`unexpected ${JSON.stringify(ch ?? "end of file")}`);
3137
+ return text.slice(start, i);
3138
+ };
3139
+ if (text.startsWith("// !$*UTF8*$!")) i = text.indexOf("\n") + 1;
3140
+ const root = value();
3141
+ skip();
3142
+ if (i !== text.length) fail("trailing content");
3143
+ return root;
3144
+ }
3145
+ var isDict = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3146
+ var str = (value) => typeof value === "string" ? value : void 0;
3147
+ var list = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
3148
+ var APPLICATION = "com.apple.product-type.application";
3149
+ var NEVER_MEMBER = /(?:^|\/)(?:Info\.plist|[^/]+\.entitlements|[^/]+\.xcconfig|\.DS_Store)$/;
3150
+ var BUNDLE_DIR = /\.(xcassets|bundle|lproj|xcdatamodeld|scnassets|spriteatlas|rcproject|storyboardc|icon)$/;
3151
+ function walkFiles(dir) {
3152
+ if (!import_node_fs8.default.existsSync(dir)) return [];
3153
+ const out = [];
3154
+ for (const entry of import_node_fs8.default.readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
3155
+ if (entry.name.startsWith(".")) continue;
3156
+ const full = import_node_path9.default.join(dir, entry.name);
3157
+ if (entry.isDirectory()) out.push(...walkFiles(full));
3158
+ else if (entry.isFile()) out.push(full);
3159
+ }
3160
+ return out;
3161
+ }
3162
+ function readXcconfig(file, seen = /* @__PURE__ */ new Set()) {
3163
+ if (seen.has(file) || !import_node_fs8.default.existsSync(file)) return {};
3164
+ seen.add(file);
3165
+ const settings = {};
3166
+ for (const raw2 of import_node_fs8.default.readFileSync(file, "utf8").split("\n")) {
3167
+ const line = raw2.replace(/\/\/.*$/, "").trim();
3168
+ const include = /^#include\??\s+"([^"]+)"/.exec(line);
3169
+ if (include) {
3170
+ Object.assign(
3171
+ settings,
3172
+ readXcconfig(import_node_path9.default.resolve(import_node_path9.default.dirname(file), include[1]), seen)
3173
+ );
3174
+ continue;
3175
+ }
3176
+ const setting = /^([A-Z_][A-Z0-9_]*)(?:\[[^\]]*\])?\s*=\s*(.*)$/.exec(line);
3177
+ if (setting) settings[setting[1]] = setting[2].trim();
3178
+ }
3179
+ return settings;
3180
+ }
3181
+ function c99Identifier(name) {
3182
+ const id = name.replace(/[^A-Za-z0-9_]/g, "_");
3183
+ return /^[0-9]/.test(id) ? `_${id}` : id;
3184
+ }
3185
+ var parsed = /* @__PURE__ */ new Map();
3186
+ function readProject(pbxproj) {
3187
+ const mtimeMs = import_node_fs8.default.statSync(pbxproj).mtimeMs;
3188
+ const cached = parsed.get(pbxproj);
3189
+ if (cached?.mtimeMs === mtimeMs) return cached.root;
3190
+ const root = parseOpenStepPlist(import_node_fs8.default.readFileSync(pbxproj, "utf8"));
3191
+ if (!isDict(root) || !isDict(root.objects)) {
3192
+ throw new Error(`${pbxproj} has no objects table`);
3193
+ }
3194
+ parsed.set(pbxproj, { mtimeMs, root });
3195
+ return root;
3196
+ }
3197
+ function readXcodeAppTarget(xcodeproj, targetName) {
3198
+ const pbxproj = import_node_path9.default.join(xcodeproj, "project.pbxproj");
3199
+ if (!import_node_fs8.default.existsSync(pbxproj)) throw new Error(`${xcodeproj} has no project.pbxproj`);
3200
+ const root = readProject(pbxproj);
3201
+ const objects = root.objects;
3202
+ const object = (id) => {
3203
+ const found = id === void 0 ? void 0 : objects[id];
3204
+ return isDict(found) ? found : void 0;
3205
+ };
3206
+ const project = object(str(root.rootObject));
3207
+ if (!project || project.isa !== "PBXProject") {
3208
+ throw new Error(`${pbxproj} has no PBXProject root`);
3209
+ }
3210
+ const projectDir = import_node_fs8.default.realpathSync(
3211
+ import_node_path9.default.resolve(import_node_path9.default.dirname(xcodeproj), str(project.projectDirPath) ?? "")
3212
+ );
3213
+ const parent = /* @__PURE__ */ new Map();
3214
+ for (const [id, entry] of Object.entries(objects)) {
3215
+ if (!isDict(entry)) continue;
3216
+ if (entry.isa === "PBXGroup" || entry.isa === "PBXVariantGroup") {
3217
+ for (const child of list(entry.children)) parent.set(child, id);
3218
+ }
3219
+ }
3220
+ const resolvedPaths = /* @__PURE__ */ new Map();
3221
+ const resolvePath = (id) => {
3222
+ if (resolvedPaths.has(id)) return resolvedPaths.get(id);
3223
+ const entry = object(id);
3224
+ let result = null;
3225
+ if (entry) {
3226
+ const own = str(entry.path) ?? "";
3227
+ const tree = str(entry.sourceTree) ?? "<group>";
3228
+ if (tree === "<absolute>") result = own;
3229
+ else if (tree === "SOURCE_ROOT") result = import_node_path9.default.join(projectDir, own);
3230
+ else if (tree === "<group>") {
3231
+ const up = parent.get(id);
3232
+ const base = up ? resolvePath(up) : projectDir;
3233
+ result = base === null ? null : import_node_path9.default.join(base, own);
3234
+ }
3235
+ }
3236
+ resolvedPaths.set(id, result);
3237
+ return result;
3238
+ };
3239
+ const targets = list(project.targets).map((id) => ({ id, target: object(id) })).filter(
3240
+ (entry) => entry.target?.isa === "PBXNativeTarget"
3241
+ );
3242
+ const appTargets = targets.filter((entry) => entry.target.productType === APPLICATION);
3243
+ const appTargetNames = appTargets.map((entry) => str(entry.target.name) ?? entry.id);
3244
+ const chosen = targetName ? appTargets.find((entry) => entry.target.name === targetName) : appTargets.length === 1 ? appTargets[0] : void 0;
3245
+ if (!chosen) {
3246
+ throw new Error(
3247
+ 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`
3248
+ );
3249
+ }
3250
+ const { id: targetId, target } = chosen;
3251
+ const configSettings = (listId) => {
3252
+ const configs = list(object(listId)?.buildConfigurations).map(object);
3253
+ const config = configs.find((entry) => entry?.name === "Debug") ?? configs.find(Boolean);
3254
+ if (!config) return {};
3255
+ const base = str(config.baseConfigurationReference);
3256
+ const fromFile = base ? readXcconfig(resolvePath(base) ?? "") : {};
3257
+ const own = isDict(config.buildSettings) ? config.buildSettings : {};
3258
+ return {
3259
+ ...fromFile,
3260
+ ...Object.fromEntries(
3261
+ Object.entries(own).flatMap(
3262
+ ([key, value]) => typeof value === "string" ? [[key, value]] : []
3263
+ )
3264
+ )
3265
+ };
3266
+ };
3267
+ const settings = {
3268
+ ...configSettings(str(project.buildConfigurationList)),
3269
+ ...configSettings(str(target.buildConfigurationList))
3270
+ };
3271
+ const name = str(target.name) ?? targetId;
3272
+ const productName = (settings.PRODUCT_NAME ?? "$(TARGET_NAME)").replaceAll("$(TARGET_NAME)", name).replaceAll("${TARGET_NAME}", name);
3273
+ const moduleName = c99Identifier(
3274
+ settings.PRODUCT_MODULE_NAME && !settings.PRODUCT_MODULE_NAME.includes("$(") ? settings.PRODUCT_MODULE_NAME : productName
3275
+ );
3276
+ const variables = {
3277
+ ...settings,
3278
+ EXECUTABLE_NAME: settings.EXECUTABLE_NAME ?? productName,
3279
+ DEVELOPMENT_LANGUAGE: settings.DEVELOPMENT_LANGUAGE ?? str(project.developmentRegion) ?? "en",
3280
+ TARGET_NAME: name,
3281
+ PRODUCT_NAME: productName,
3282
+ PRODUCT_MODULE_NAME: moduleName,
3283
+ SRCROOT: projectDir,
3284
+ SOURCE_ROOT: projectDir
3285
+ };
3286
+ const expand = (value) => {
3287
+ const seen = /* @__PURE__ */ new Set();
3288
+ while (/\$[({][A-Za-z_][A-Za-z0-9_]*[)}]/.test(value)) {
3289
+ if (seen.has(value)) throw new Error(`${name} has cyclic Info.plist build settings`);
3290
+ seen.add(value);
3291
+ value = value.replace(
3292
+ /\$[({]([A-Za-z_][A-Za-z0-9_]*)[)}]/g,
3293
+ (match, key) => {
3294
+ const replacement = Object.entries(variables).find(
3295
+ ([name2]) => name2 === key
3296
+ )?.[1];
3297
+ if (replacement === void 0)
3298
+ throw new Error(`${name} Info.plist has unresolved setting ${match}`);
3299
+ return replacement;
3300
+ }
3301
+ );
3302
+ }
3303
+ return value;
3304
+ };
3305
+ const expandValue = (value) => {
3306
+ if (typeof value === "string") return expand(value);
3307
+ if (Array.isArray(value)) return value.map(expandValue);
3308
+ if (typeof value === "object" && !(value instanceof Date) && !Buffer.isBuffer(value)) {
3309
+ return Object.fromEntries(
3310
+ Object.entries(value).map(([key, value2]) => [key, expandValue(value2)])
3311
+ );
3312
+ }
3313
+ return value;
3314
+ };
3315
+ const infoPlistFile = settings.INFOPLIST_FILE ? import_node_path9.default.resolve(projectDir, expand(settings.INFOPLIST_FILE)) : null;
3316
+ const sourceInfo = infoPlistFile ? import_plist.default.parse(import_node_fs8.default.readFileSync(infoPlistFile, "utf8")) : {};
3317
+ if (!sourceInfo || typeof sourceInfo !== "object" || Array.isArray(sourceInfo) || sourceInfo instanceof Date || Buffer.isBuffer(sourceInfo)) {
3318
+ throw new Error(`${name} Info.plist must contain a dictionary`);
3319
+ }
3320
+ const info = {};
3321
+ for (const [key, value] of Object.entries(sourceInfo)) info[key] = expandValue(value);
3322
+ for (const [key, value] of Object.entries(settings)) {
3323
+ if (!key.startsWith("INFOPLIST_KEY_") || key.endsWith("_Generation")) continue;
3324
+ info[key.slice("INFOPLIST_KEY_".length)] = value === "YES" ? true : value === "NO" ? false : expand(value);
3325
+ }
3326
+ if (settings.INFOPLIST_KEY_UIApplicationSceneManifest_Generation === "YES" && info.UIApplicationSceneManifest === void 0) {
3327
+ info.UIApplicationSceneManifest = {
3328
+ UIApplicationSupportsMultipleScenes: true,
3329
+ UISceneConfigurations: {}
3330
+ };
3331
+ }
3332
+ const sources = /* @__PURE__ */ new Set();
3333
+ const resources = /* @__PURE__ */ new Set();
3334
+ const addResource = (file) => {
3335
+ if (import_node_fs8.default.existsSync(file) && import_node_fs8.default.statSync(file).isDirectory()) {
3336
+ for (const inner of walkFiles(file)) resources.add(inner);
3337
+ } else if (import_node_fs8.default.existsSync(file)) resources.add(file);
3338
+ };
3339
+ const fileRefPaths = (refId) => {
3340
+ const ref = object(refId);
3341
+ if (!ref) return [];
3342
+ if (ref.isa === "PBXVariantGroup") {
3343
+ return list(ref.children).flatMap((child) => {
3344
+ const resolved2 = resolvePath(child);
3345
+ return resolved2 ? [resolved2] : [];
3346
+ });
3347
+ }
3348
+ const resolved = resolvePath(refId);
3349
+ return resolved ? [resolved] : [];
3350
+ };
3351
+ for (const phaseId of list(target.buildPhases)) {
3352
+ const phase = object(phaseId);
3353
+ if (phase?.isa !== "PBXSourcesBuildPhase" && phase?.isa !== "PBXResourcesBuildPhase")
3354
+ continue;
3355
+ for (const buildFileId of list(phase.files)) {
3356
+ for (const file of fileRefPaths(str(object(buildFileId)?.fileRef) ?? "")) {
3357
+ if (phase.isa === "PBXSourcesBuildPhase" && file.endsWith(".swift")) {
3358
+ if (import_node_fs8.default.existsSync(file)) sources.add(file);
3359
+ } else if (phase.isa === "PBXResourcesBuildPhase") addResource(file);
3360
+ }
3361
+ }
3362
+ }
3363
+ const addSynchronized = (folder, relative) => {
3364
+ const file = import_node_path9.default.join(folder, relative);
3365
+ if (NEVER_MEMBER.test(relative)) return;
3366
+ if (file.endsWith(".swift")) {
3367
+ if (!relative.split("/").some((segment) => BUNDLE_DIR.test(segment)))
3368
+ sources.add(file);
3369
+ } else if (/\.(h|m|mm|c|cpp|metal)$/.test(file)) {
3370
+ return;
3371
+ } else resources.add(file);
3372
+ };
3373
+ const owned = new Set(list(target.fileSystemSynchronizedGroups));
3374
+ for (const [groupId, group] of Object.entries(objects)) {
3375
+ if (!isDict(group) || group.isa !== "PBXFileSystemSynchronizedRootGroup") continue;
3376
+ const folder = resolvePath(groupId);
3377
+ if (!folder) continue;
3378
+ const exceptions = /* @__PURE__ */ new Set();
3379
+ for (const exceptionId of list(group.exceptions)) {
3380
+ const exception = object(exceptionId);
3381
+ if (exception?.target !== targetId) continue;
3382
+ for (const relative of list(exception.membershipExceptions))
3383
+ exceptions.add(relative);
3384
+ }
3385
+ if (owned.has(groupId)) {
3386
+ for (const file of walkFiles(folder)) {
3387
+ const relative = import_node_path9.default.relative(folder, file).split(import_node_path9.default.sep).join("/");
3388
+ if ([...exceptions].some(
3389
+ (exception) => relative === exception || relative.startsWith(`${exception}/`)
3390
+ ))
3391
+ continue;
3392
+ addSynchronized(folder, relative);
3393
+ }
3394
+ } else {
3395
+ for (const relative of exceptions) {
3396
+ const file = import_node_path9.default.join(folder, relative);
3397
+ if (import_node_fs8.default.existsSync(file) && import_node_fs8.default.statSync(file).isDirectory()) {
3398
+ for (const inner of walkFiles(file))
3399
+ addSynchronized(
3400
+ folder,
3401
+ import_node_path9.default.relative(folder, inner).split(import_node_path9.default.sep).join("/")
3402
+ );
3403
+ } else if (import_node_fs8.default.existsSync(file)) addSynchronized(folder, relative);
3404
+ }
3405
+ }
3406
+ }
3407
+ const localPackageDirs = Object.entries(objects).flatMap(([id, entry]) => {
3408
+ if (!isDict(entry)) return [];
3409
+ const candidate = entry.isa === "XCLocalSwiftPackageReference" ? import_node_path9.default.resolve(projectDir, str(entry.relativePath) ?? "") : entry.isa === "PBXFileReference" && entry.lastKnownFileType === "wrapper" ? resolvePath(id) : null;
3410
+ return candidate && import_node_fs8.default.existsSync(import_node_path9.default.join(candidate, "Package.swift")) ? [candidate] : [];
3411
+ });
3412
+ const graphs = /* @__PURE__ */ new Map();
3413
+ const graphOf = (dir) => {
3414
+ const cached = graphs.get(dir);
3415
+ if (cached) return cached;
3416
+ const graph = swiftManifestGraph(
3417
+ import_node_fs8.default.readFileSync(import_node_path9.default.join(dir, "Package.swift"), "utf8")
3418
+ );
3419
+ graphs.set(dir, graph);
3420
+ return graph;
3421
+ };
3422
+ const localProducts = /* @__PURE__ */ new Map();
3423
+ for (const dir of localPackageDirs) {
3424
+ for (const product of graphOf(dir).products.keys()) localProducts.set(product, dir);
3425
+ }
3426
+ const localPackages = /* @__PURE__ */ new Set();
3427
+ const remoteProducts = [];
3428
+ const unresolvedProducts = [];
3429
+ for (const dependencyId of list(target.packageProductDependencies)) {
3430
+ const dependency = object(dependencyId);
3431
+ const product = str(dependency?.productName);
3432
+ if (!dependency || !product) continue;
3433
+ const reference = object(str(dependency.package));
3434
+ if (reference?.isa === "XCRemoteSwiftPackageReference") {
3435
+ remoteProducts.push({
3436
+ product,
3437
+ repositoryURL: str(reference.repositoryURL) ?? ""
3438
+ });
3439
+ } else if (reference?.isa === "XCLocalSwiftPackageReference") {
3440
+ localPackages.add(import_node_path9.default.resolve(projectDir, str(reference.relativePath) ?? ""));
3441
+ } else if (localProducts.has(product)) {
3442
+ localPackages.add(localProducts.get(product));
3443
+ } else unresolvedProducts.push(product);
3444
+ }
3445
+ const pending = [...localPackages];
3446
+ while (pending.length > 0) {
3447
+ const dir = pending.pop();
3448
+ const graph = graphOf(dir);
3449
+ for (const relative of graph.packagePaths) {
3450
+ const next = import_node_path9.default.resolve(dir, relative);
3451
+ if (localPackages.has(next) || !import_node_fs8.default.existsSync(import_node_path9.default.join(next, "Package.swift")))
3452
+ continue;
3453
+ localPackages.add(next);
3454
+ pending.push(next);
3455
+ }
3456
+ for (const dependencies of graph.dependencies.values()) {
3457
+ for (const dependency of dependencies) {
3458
+ if (dependency.kind !== "product") continue;
3459
+ const url = graph.packageURLs.get(dependency.package);
3460
+ if (url && !remoteProducts.some((entry) => entry.product === dependency.name))
3461
+ remoteProducts.push({ product: dependency.name, repositoryURL: url });
3462
+ }
3463
+ }
3464
+ }
3465
+ const packageResolved = [
3466
+ import_node_path9.default.join(xcodeproj, "project.xcworkspace"),
3467
+ ...import_node_fs8.default.readdirSync(projectDir).filter((entry) => entry.endsWith(".xcworkspace")).map((entry) => import_node_path9.default.join(projectDir, entry))
3468
+ ].map(
3469
+ (workspace) => import_node_path9.default.join(workspace, "xcshareddata", "swiftpm", "Package.resolved")
3470
+ ).find((file) => import_node_fs8.default.existsSync(file)) ?? null;
3471
+ const swiftVersion = Number.parseFloat(settings.SWIFT_VERSION ?? "5");
3472
+ return {
3473
+ projectDir,
3474
+ pbxproj,
3475
+ name,
3476
+ moduleName,
3477
+ sources: [...sources].sort(),
3478
+ resources: [...resources].sort(),
3479
+ infoPlist: import_plist.default.build(info),
3480
+ infoPlistFile,
3481
+ languageMode: swiftVersion >= 6 ? 6 : 5,
3482
+ mainActorIsolation: settings.SWIFT_DEFAULT_ACTOR_ISOLATION === "MainActor",
3483
+ localPackages: [...localPackages].sort(),
3484
+ remoteProducts,
3485
+ packageResolved,
3486
+ unresolvedProducts,
3487
+ appTargets: appTargetNames
3488
+ };
3489
+ }
3490
+
2228
3491
  // src/swift-host.ts
2229
3492
  var ARTIFACT_PATH = "/__peach/swift/";
2230
3493
  var RESOURCE_PATH = "/__peach/swift-res/";
@@ -2240,17 +3503,17 @@ var SKIP_SOURCE_DIRS = /* @__PURE__ */ new Set([
2240
3503
  var NATIVE_DESCRIPTOR = ".one-native-source.json";
2241
3504
  var NATIVE_GLUE = ".one-native-source.swift.txt";
2242
3505
  function swiftPackageId(packagePath) {
2243
- return import_node_path8.default.basename(packagePath).replace(/[^A-Za-z0-9_]/g, "_").replace(/^(\d)/, "_$1");
3506
+ return import_node_path10.default.basename(packagePath).replace(/[^A-Za-z0-9_]/g, "_").replace(/^(\d)/, "_$1");
2244
3507
  }
2245
3508
  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;
3509
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
3510
+ const file = import_node_path10.default.join(packagePath, NATIVE_DESCRIPTOR);
3511
+ if (!import_node_fs9.default.existsSync(file)) return null;
2249
3512
  const value = JSON.parse(
2250
3513
  readPackageFile(packagePath, file, MAX_SWIFT_COMPILE_SOURCE_BYTES).toString("utf8")
2251
3514
  );
2252
3515
  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))) {
3516
+ 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
3517
  throw invalid();
2255
3518
  }
2256
3519
  if (!isSwiftNativeModules(value) || value.packageId !== swiftPackageId(packagePath)) {
@@ -2259,12 +3522,12 @@ function nativeSourceDescriptor(packagePath) {
2259
3522
  return value;
2260
3523
  }
2261
3524
  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));
3525
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
3526
+ return [NATIVE_DESCRIPTOR, NATIVE_GLUE].map((name) => import_node_path10.default.join(packagePath, name)).filter((file) => import_node_fs9.default.existsSync(file));
2264
3527
  }
2265
3528
  var projects = /* @__PURE__ */ new Map();
2266
3529
  function projectFor(packagePath, hosted) {
2267
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3530
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2268
3531
  const existing = projects.get(packagePath);
2269
3532
  if (existing) {
2270
3533
  if (hosted && !existing.hosted) {
@@ -2284,52 +3547,136 @@ function projectFor(packagePath, hosted) {
2284
3547
  projects.set(packagePath, created);
2285
3548
  return created;
2286
3549
  }
3550
+ var xcodeProjects = /* @__PURE__ */ new Map();
3551
+ function remotePackages(entry, app) {
3552
+ if (!entry.provided) return { targets: [], unavailable: /* @__PURE__ */ new Map() };
3553
+ const key = JSON.stringify([
3554
+ app.remoteProducts,
3555
+ app.packageResolved,
3556
+ app.packageResolved ? import_node_fs9.default.statSync(app.packageResolved).mtimeMs : 0
3557
+ ]);
3558
+ if (entry.remote?.key !== key) {
3559
+ entry.remote = {
3560
+ key,
3561
+ packages: resolveRemotePackages(
3562
+ import_node_fs9.default.realpathSync(app.projectDir),
3563
+ app.packageResolved,
3564
+ app.remoteProducts,
3565
+ entry.provided
3566
+ )
3567
+ };
3568
+ }
3569
+ return entry.remote.packages;
3570
+ }
3571
+ var XCODE_APP_DIR = "__app__";
3572
+ var XCODE_PACKAGES_DIR = "__packages__";
3573
+ var CHECKOUTS_PREFIX = `${REMOTE_CHECKOUTS.split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)}/`;
3574
+ function xcodeInputKey(appSources, file, relative) {
3575
+ if (appSources.has(file)) return import_node_path10.default.posix.join(XCODE_APP_DIR, relative);
3576
+ return relative.startsWith(CHECKOUTS_PREFIX) ? import_node_path10.default.posix.join(XCODE_PACKAGES_DIR, relative.slice(CHECKOUTS_PREFIX.length)) : relative;
3577
+ }
3578
+ function xcodeLayout(root) {
3579
+ const registered = xcodeProjects.get(root);
3580
+ if (!registered) return null;
3581
+ const app = readXcodeAppTarget(registered.xcodeproj, registered.target);
3582
+ const files = /* @__PURE__ */ new Set([app.pbxproj, ...app.sources, ...app.resources]);
3583
+ if (app.infoPlistFile) files.add(app.infoPlistFile);
3584
+ const targets = [];
3585
+ for (const dir of app.localPackages) {
3586
+ const manifest = import_node_path10.default.join(dir, "Package.swift");
3587
+ files.add(manifest);
3588
+ const prefix = import_node_path10.default.relative(root, dir).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep);
3589
+ const all = packageFiles(dir).map(
3590
+ (file) => import_node_path10.default.relative(dir, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
3591
+ );
3592
+ for (const target of swiftManifestTargets(import_node_fs9.default.readFileSync(manifest, "utf8"), all)) {
3593
+ if (target.executable) continue;
3594
+ targets.push({ ...target, path: import_node_path10.default.posix.join(prefix, target.path) });
3595
+ for (const relative of all) {
3596
+ if (relative.startsWith(`${target.path}/`)) files.add(import_node_path10.default.join(dir, relative));
3597
+ }
3598
+ }
3599
+ }
3600
+ const remote = remotePackages(registered, app);
3601
+ for (const target of remote.targets) {
3602
+ targets.push({
3603
+ ...target,
3604
+ path: import_node_path10.default.posix.join(
3605
+ XCODE_PACKAGES_DIR,
3606
+ 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)
3607
+ )
3608
+ });
3609
+ for (const file of target.files) files.add(file);
3610
+ }
3611
+ return {
3612
+ app,
3613
+ targets,
3614
+ unavailable: remote.unavailable,
3615
+ files: [...files].sort()
3616
+ };
3617
+ }
3618
+ function xcodeManifest(layout) {
3619
+ const settings = (mode, mainActor) => `swiftSettings: [.swiftLanguageMode(.v${mode})${mainActor ? ", .defaultIsolation(MainActor.self)" : ""}]`;
3620
+ return [
3621
+ "// swift-tools-version: 6.2",
3622
+ "import PackageDescription",
3623
+ 'let package = Package(name: "app", targets: [',
3624
+ ` .executableTarget(name: "${layout.app.moduleName}", path: "${XCODE_APP_DIR}", ${settings(layout.app.languageMode, layout.app.mainActorIsolation)}),`,
3625
+ ...layout.targets.map(
3626
+ (target) => ` .target(name: "${target.name}", path: "${target.path}", ${target.resources ? "resources: [], " : ""}${settings(target.languageMode, target.mainActorIsolation)}),`
3627
+ ),
3628
+ "])",
3629
+ ""
3630
+ ].join("\n");
3631
+ }
2287
3632
  function packageFiles(root) {
2288
- const canonicalRoot = import_node_fs7.default.realpathSync(root);
3633
+ const canonicalRoot = import_node_fs9.default.realpathSync(root);
3634
+ const xcode = xcodeLayout(canonicalRoot);
3635
+ if (xcode) return xcode.files;
2289
3636
  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))) {
3637
+ const walk2 = (dir) => {
3638
+ for (const entry of import_node_fs9.default.readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
2292
3639
  if (entry.name.startsWith(".") && entry.name !== NATIVE_DESCRIPTOR && entry.name !== NATIVE_GLUE || SKIP_SOURCE_DIRS.has(entry.name))
2293
3640
  continue;
2294
- const full = import_node_path8.default.join(dir, entry.name);
3641
+ const full = import_node_path10.default.join(dir, entry.name);
2295
3642
  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)) {
3643
+ const real = import_node_fs9.default.realpathSync(full);
3644
+ const relative = import_node_path10.default.relative(canonicalRoot, real);
3645
+ if (relative.startsWith(`..${import_node_path10.default.sep}`) || relative === ".." || import_node_path10.default.isAbsolute(relative)) {
2299
3646
  throw new Error(`swift input escapes the selected package: ${full}`);
2300
3647
  }
2301
3648
  if (entry.isDirectory()) {
2302
- if (import_node_fs7.default.existsSync(import_node_path8.default.join(full, "Package.swift"))) continue;
2303
- walk(full);
3649
+ if (import_node_fs9.default.existsSync(import_node_path10.default.join(full, "Package.swift"))) continue;
3650
+ walk2(full);
2304
3651
  } else if (entry.isFile()) {
2305
3652
  found.push(full);
2306
3653
  if (found.length > 4096) throw new Error("swift package exceeds 4096 input files");
2307
3654
  }
2308
3655
  }
2309
3656
  };
2310
- walk(canonicalRoot);
3657
+ walk2(canonicalRoot);
2311
3658
  return found;
2312
3659
  }
2313
3660
  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)) {
3661
+ const canonicalRoot = import_node_fs9.default.realpathSync(root);
3662
+ const relative = import_node_path10.default.relative(canonicalRoot, import_node_fs9.default.realpathSync(file));
3663
+ if (relative === ".." || relative.startsWith(`..${import_node_path10.default.sep}`) || import_node_path10.default.isAbsolute(relative)) {
2317
3664
  throw new Error(`swift input escapes the selected package: ${file}`);
2318
3665
  }
2319
- let ancestor = import_node_path8.default.resolve(file);
3666
+ let ancestor = import_node_path10.default.resolve(file);
2320
3667
  while (ancestor !== canonicalRoot) {
2321
- if (import_node_fs7.default.lstatSync(ancestor).isSymbolicLink()) {
3668
+ if (import_node_fs9.default.lstatSync(ancestor).isSymbolicLink()) {
2322
3669
  throw new Error(`swift input is a symlink: ${ancestor}`);
2323
3670
  }
2324
- const parent = import_node_path8.default.dirname(ancestor);
3671
+ const parent = import_node_path10.default.dirname(ancestor);
2325
3672
  if (parent === ancestor)
2326
3673
  throw new Error(`swift input escapes the selected package: ${file}`);
2327
3674
  ancestor = parent;
2328
3675
  }
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);
3676
+ const expected = import_node_fs9.default.statSync(file);
3677
+ const fd = import_node_fs9.default.openSync(file, import_node_fs9.default.constants.O_RDONLY | import_node_fs9.default.constants.O_NOFOLLOW);
2331
3678
  try {
2332
- const stat = import_node_fs7.default.fstatSync(fd);
3679
+ const stat = import_node_fs9.default.fstatSync(fd);
2333
3680
  if (stat.dev !== expected.dev || stat.ino !== expected.ino) {
2334
3681
  throw new Error(`swift input changed while opening: ${file}`);
2335
3682
  }
@@ -2339,28 +3686,43 @@ function readPackageFile(root, file, maxBytes) {
2339
3686
  const bytes = Buffer.alloc(stat.size + 1);
2340
3687
  let offset = 0;
2341
3688
  while (offset < bytes.length) {
2342
- const count = import_node_fs7.default.readSync(fd, bytes, offset, bytes.length - offset, null);
3689
+ const count = import_node_fs9.default.readSync(fd, bytes, offset, bytes.length - offset, null);
2343
3690
  if (count === 0) break;
2344
3691
  offset += count;
2345
3692
  }
2346
- if (offset !== stat.size || import_node_fs7.default.fstatSync(fd).size !== stat.size) {
3693
+ if (offset !== stat.size || import_node_fs9.default.fstatSync(fd).size !== stat.size) {
2347
3694
  throw new Error(`swift input changed while reading: ${file}`);
2348
3695
  }
2349
3696
  return bytes.subarray(0, offset);
2350
3697
  } finally {
2351
- import_node_fs7.default.closeSync(fd);
3698
+ import_node_fs9.default.closeSync(fd);
2352
3699
  }
2353
3700
  }
2354
3701
  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;
3702
+ return packageFiles(root).filter((file) => file.endsWith(".swift"));
2360
3703
  }
2361
3704
  function resourceCandidateFiles(root) {
2362
- return packageFiles(root).filter((file) => !file.endsWith(".swift"));
3705
+ return packageFiles(root).filter(
3706
+ (file) => !file.endsWith(".swift") && import_node_path10.default.basename(file) !== "project.pbxproj"
3707
+ );
2363
3708
  }
3709
+ var HOSTED_LIMITS = {
3710
+ resources: MAX_SWIFT_COMPILE_RESOURCES,
3711
+ resourceBytes: MAX_SWIFT_COMPILE_RESOURCE_BYTES,
3712
+ resourceTotalBytes: MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES,
3713
+ images: MAX_SWIFT_COMPILE_IMAGES,
3714
+ imageBytes: MAX_SWIFT_COMPILE_IMAGE_BYTES,
3715
+ imageTotalBytes: MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES
3716
+ };
3717
+ var LOCAL_LIMITS = {
3718
+ resources: Infinity,
3719
+ resourceBytes: Infinity,
3720
+ resourceTotalBytes: Infinity,
3721
+ images: Infinity,
3722
+ imageBytes: Infinity,
3723
+ imageTotalBytes: Infinity
3724
+ };
3725
+ var inputLimits = (hosted) => hosted ? HOSTED_LIMITS : LOCAL_LIMITS;
2364
3726
  var RESOURCE_CONTENT_TYPES = {
2365
3727
  ".avif": "image/avif",
2366
3728
  ".bmp": "image/bmp",
@@ -2372,20 +3734,19 @@ var RESOURCE_CONTENT_TYPES = {
2372
3734
  ".webp": "image/webp"
2373
3735
  };
2374
3736
  function buildSwiftResourceTable(project, baseUrl) {
3737
+ const limits = inputLimits(Boolean(project.hosted));
2375
3738
  const absolute = resourceCandidateFiles(project.packagePath);
2376
3739
  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)
3740
+ (file) => import_node_path10.default.relative(project.packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
2378
3741
  );
2379
3742
  const byRelative = new Map(absolute.map((file, index) => [relative[index], file]));
2380
3743
  const readContents = (candidate) => {
2381
3744
  const file = byRelative.get(candidate);
2382
3745
  if (!file || !/(^|\/)Contents\.json$|\.symbolset\/[^/]+\.svg$/.test(candidate))
2383
3746
  return null;
2384
- return readPackageFile(
2385
- project.packagePath,
2386
- file,
2387
- MAX_SWIFT_COMPILE_RESOURCE_BYTES
2388
- ).toString("utf8");
3747
+ return readPackageFile(project.packagePath, file, limits.resourceBytes).toString(
3748
+ "utf8"
3749
+ );
2389
3750
  };
2390
3751
  const found = enumerateBundleImages(relative, readContents);
2391
3752
  const colors = enumerateBundleColors(relative, readContents);
@@ -2398,20 +3759,16 @@ function buildSwiftResourceTable(project, baseUrl) {
2398
3759
  for (const { name, file, scale } of found) {
2399
3760
  const disk = byRelative.get(file);
2400
3761
  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) {
3762
+ if (Object.keys(images).length >= limits.images || imageBytes + import_node_fs9.default.statSync(disk).size > limits.imageTotalBytes) {
2402
3763
  throw new Error("swift image pack exceeds the compile service caps");
2403
3764
  }
2404
- const bytes = readPackageFile(
2405
- project.packagePath,
2406
- disk,
2407
- MAX_SWIFT_COMPILE_IMAGE_BYTES
2408
- );
3765
+ const bytes = readPackageFile(project.packagePath, disk, limits.imageBytes);
2409
3766
  imageBytes += bytes.length;
2410
3767
  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();
3768
+ const ext = import_node_path10.default.posix.extname(file).toLowerCase();
2412
3769
  table[name] = { uri: `${baseUrl}${RESOURCE_PATH}${hash}${ext}`, scale };
2413
3770
  images[name] = {
2414
- file: import_node_path8.default.posix.basename(file),
3771
+ file: import_node_path10.default.posix.basename(file),
2415
3772
  data: bytes.toString("base64")
2416
3773
  };
2417
3774
  watched.push(file);
@@ -2434,26 +3791,36 @@ function buildSwiftResourceTable(project, baseUrl) {
2434
3791
  }
2435
3792
  return { table, images, colors, symbols, watched };
2436
3793
  }
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);
3794
+ function buildSwiftBundleFiles(packagePath, hosted) {
3795
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
3796
+ const limits = inputLimits(hosted);
2442
3797
  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)
3798
+ (file) => import_node_path10.default.relative(packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
2444
3799
  );
2445
3800
  const files = {};
2446
3801
  const watched = [];
2447
3802
  let total = 0;
3803
+ const xcode = xcodeLayout(packagePath);
3804
+ if (xcode) {
3805
+ const bytes = Buffer.from(xcode.app.infoPlist);
3806
+ if (bytes.length > limits.resourceBytes || bytes.length > limits.resourceTotalBytes)
3807
+ throw new Error("swift launch Info.plist exceeds bundle resource limits");
3808
+ files["Info.plist"] = bytes.toString("base64");
3809
+ total += bytes.length;
3810
+ if (xcode.app.infoPlistFile)
3811
+ watched.push(
3812
+ import_node_path10.default.relative(packagePath, xcode.app.infoPlistFile).split(import_node_path10.default.sep).join("/")
3813
+ );
3814
+ }
2448
3815
  for (const { base, file } of enumerateBundleJson(relative)) {
2449
3816
  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) {
3817
+ const disk = import_node_path10.default.join(packagePath, ...file.split("/"));
3818
+ if (Object.keys(files).length >= limits.resources || total + import_node_fs9.default.statSync(disk).size > limits.resourceTotalBytes) {
2452
3819
  throw new Error(
2453
- `swift bundle pack exceeds ${BUNDLE_MAX_FILES} files / ${BUNDLE_MAX_TOTAL_BYTES} bytes`
3820
+ `swift bundle pack exceeds ${limits.resources} files / ${limits.resourceTotalBytes} bytes`
2454
3821
  );
2455
3822
  }
2456
- const bytes = readPackageFile(packagePath, disk, BUNDLE_MAX_FILE_BYTES);
3823
+ const bytes = readPackageFile(packagePath, disk, limits.resourceBytes);
2457
3824
  files[base] = bytes.toString("base64");
2458
3825
  total += bytes.length;
2459
3826
  }
@@ -2463,12 +3830,12 @@ function serveSwiftResource(project, key) {
2463
3830
  return project.resourceFiles.get(key) ?? project.resourcesPrevious.get(key) ?? null;
2464
3831
  }
2465
3832
  function linkedModuleRoots(packagePath) {
2466
- packagePath = import_node_fs7.default.realpathSync(packagePath);
3833
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2467
3834
  let manifest;
2468
3835
  try {
2469
3836
  manifest = readPackageFile(
2470
3837
  packagePath,
2471
- import_node_path8.default.join(packagePath, "Package.swift"),
3838
+ import_node_path10.default.join(packagePath, "Package.swift"),
2472
3839
  MAX_SWIFT_COMPILE_SOURCE_BYTES
2473
3840
  ).toString("utf8");
2474
3841
  } catch {
@@ -2477,8 +3844,8 @@ function linkedModuleRoots(packagePath) {
2477
3844
  const roots = /* @__PURE__ */ new Set();
2478
3845
  const dependency = /\.package\(\s*path:\s*"([^"]+)"\s*\)/g;
2479
3846
  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);
3847
+ const root = import_node_path10.default.resolve(packagePath, match[1]);
3848
+ if (import_node_fs9.default.existsSync(import_node_path10.default.join(root, "Package.swift"))) roots.add(root);
2482
3849
  }
2483
3850
  return [...roots].sort();
2484
3851
  }
@@ -2487,46 +3854,43 @@ function sourceStamp(packagePath, moduleRootOverride, hosted = false) {
2487
3854
  hash.update(packagePath);
2488
3855
  const projectInputs = new Set(packageFiles(packagePath));
2489
3856
  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);
3857
+ hash.update(import_node_path10.default.relative(packagePath, file));
3858
+ const stat = import_node_fs9.default.statSync(file);
2492
3859
  hash.update(`${stat.mtimeMs}/${stat.ctimeMs}/${stat.size}`);
2493
3860
  }
2494
3861
  const moduleRoot = hosted ? void 0 : moduleRootOverride ?? linkedModuleRoots(packagePath).find(
2495
- (root) => import_node_fs7.default.existsSync(import_node_path8.default.join(root, "toolchain.json"))
3862
+ (root) => import_node_fs9.default.existsSync(import_node_path10.default.join(root, "toolchain.json"))
2496
3863
  );
2497
3864
  if (moduleRoot) {
2498
3865
  hash.update(moduleRoot);
2499
3866
  for (const relative of swiftModuleInputFiles(moduleRoot)) {
2500
3867
  hash.update(relative);
2501
- hash.update(String(import_node_fs7.default.statSync(import_node_path8.default.join(moduleRoot, relative)).mtimeMs));
3868
+ hash.update(String(import_node_fs9.default.statSync(import_node_path10.default.join(moduleRoot, relative)).mtimeMs));
2502
3869
  }
2503
3870
  }
2504
3871
  return hash.digest("hex").slice(0, 16);
2505
3872
  }
2506
3873
  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}`;
3874
+ const relative = import_node_path10.default.relative(packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep);
3875
+ return `${import_node_path10.default.basename(packagePath)}${import_node_path10.default.posix.sep}${relative}`;
2509
3876
  }
2510
3877
  function icuUrl(origin, artifact) {
2511
3878
  return "url" in artifact.icu ? artifact.icu.url : `${origin}${ICU_PATH}${artifact.icu.sha256}`;
2512
3879
  }
2513
3880
  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");
3881
+ const xcode = xcodeLayout(packagePath);
3882
+ const appSources = new Set(xcode?.app.sources);
2521
3883
  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(
3884
+ for (const file of sourceFiles(packagePath)) {
3885
+ const relative = import_node_path10.default.relative(packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep);
3886
+ if (xcode && import_node_path10.default.basename(file) === "Package.swift") continue;
3887
+ files[xcode ? xcodeInputKey(appSources, file, relative) : relative] = readPackageFile(
2525
3888
  packagePath,
2526
3889
  file,
2527
3890
  MAX_SWIFT_COMPILE_SOURCE_BYTES
2528
3891
  ).toString("utf8");
2529
3892
  }
3893
+ if (xcode) files["Package.swift"] = xcodeManifest(xcode);
2530
3894
  return files;
2531
3895
  }
2532
3896
  function packageSnapshot(project) {
@@ -2536,16 +3900,16 @@ function packageSnapshot(project) {
2536
3900
  files,
2537
3901
  resourcePaths: swiftImplicitResourcePaths(
2538
3902
  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)
3903
+ (file) => import_node_path10.default.relative(project.packagePath, file).split(import_node_path10.default.sep).join(import_node_path10.default.posix.sep)
2540
3904
  )
2541
3905
  ),
2542
3906
  resources: buildSwiftResourceTable(project, ""),
2543
- bundleFiles: buildSwiftBundleFiles(project.packagePath),
3907
+ bundleFiles: buildSwiftBundleFiles(project.packagePath, Boolean(project.hosted)),
2544
3908
  native,
2545
3909
  ...native ? {
2546
3910
  glue: readPackageFile(
2547
3911
  project.packagePath,
2548
- import_node_path8.default.join(project.packagePath, NATIVE_GLUE),
3912
+ import_node_path10.default.join(project.packagePath, NATIVE_GLUE),
2549
3913
  MAX_SWIFT_COMPILE_SOURCE_BYTES
2550
3914
  ).toString("utf8")
2551
3915
  } : {}
@@ -2584,7 +3948,7 @@ async function compile(packagePath, entry, stamp, moduleRootOverride, hosted, sn
2584
3948
  package: content
2585
3949
  };
2586
3950
  const moduleRoot = moduleRootOverride ?? linkedModuleRoots(packagePath).find(
2587
- (root) => import_node_fs7.default.existsSync(import_node_path8.default.join(root, "toolchain.json"))
3951
+ (root) => import_node_fs9.default.existsSync(import_node_path10.default.join(root, "toolchain.json"))
2588
3952
  ) ?? await swiftDistributionRoot();
2589
3953
  if (!moduleRoot)
2590
3954
  return {
@@ -2593,27 +3957,112 @@ async function compile(packagePath, entry, stamp, moduleRootOverride, hosted, sn
2593
3957
  package: content
2594
3958
  };
2595
3959
  const toolchain = swiftModuleToolchain(moduleRoot);
2596
- const artifact = await compileSwiftProjectUnit(snapshotCompileInput(snapshot, entry), {
3960
+ const input = snapshotCompileInput(snapshot, entry);
3961
+ const targets = compileTargets(input).map((target) => target.name);
3962
+ const missing = missingSwiftModules(
3963
+ input.files,
3964
+ /* @__PURE__ */ new Set([
3965
+ ...swiftAvailableModules(moduleRoot, toolchain.toolchainBin),
3966
+ // a project without a manifest compiles as the template's one App target
3967
+ ...targets.length > 0 ? targets : ["App"]
3968
+ ])
3969
+ );
3970
+ if (missing.size > 0) throw new Error(missingModulesMessage(packagePath, missing));
3971
+ const artifact = await compileSwiftProjectUnit(input, {
2597
3972
  // the compile rewrites Sources/App in its root before swiftpm builds, and
2598
3973
  // its lock orders one process only: two vites on one root (a lane's dev
2599
3974
  // server and a capture, or two checkouts) build each other's sources. so
2600
3975
  // each app and module checkout gets its own root, which keeps the same
2601
3976
  // app's incremental build across restarts.
2602
- buildRoot: process.env.CONTRAST_SWIFT_BUILD_ROOT ?? import_node_path8.default.join(
3977
+ buildRoot: process.env.CONTRAST_SWIFT_BUILD_ROOT ?? import_node_path10.default.join(
2603
3978
  import_node_os5.default.tmpdir(),
2604
3979
  "contrast-swift-build",
2605
- (0, import_node_crypto4.createHash)("sha256").update(`${moduleRoot}\0${import_node_path8.default.resolve(packagePath)}`).digest("hex").slice(0, 16)
3980
+ (0, import_node_crypto4.createHash)("sha256").update(`${moduleRoot}\0${import_node_path10.default.resolve(packagePath)}`).digest("hex").slice(0, 16)
2606
3981
  ),
2607
3982
  moduleRoot,
2608
3983
  ...toolchain
3984
+ }).catch((error) => {
3985
+ const report = error instanceof Error ? swiftApiGapReport(error.message) : null;
3986
+ throw report ? new Error(`${error instanceof Error ? error.message : ""}
3987
+
3988
+ ${report}`, {
3989
+ cause: error
3990
+ }) : error;
2609
3991
  });
2610
3992
  return { ...artifact, stamp, package: content };
2611
3993
  }
3994
+ var API_GAP_PATTERNS = [
3995
+ [/^cannot find (?:type )?'([^']+)' in scope/, (match) => match[1]],
3996
+ // a typealias reports its aliased type after `aka`, which is the api's owner
3997
+ [
3998
+ /^(?:value of )?type '([^']+)'(?: \(aka '([^']+)'\))? has no member '([^']+)'/,
3999
+ (match) => `${(match[2] ?? match[1]).replace(/^Optional<(.+)>$/, "$1").replace(/\?$/, "")}.${match[3]}`
4000
+ ],
4001
+ [
4002
+ /^module '([^']+)' has no member named '([^']+)'/,
4003
+ (match) => `${match[1]}.${match[2]}`
4004
+ ],
4005
+ [/^'([^']+)' is unavailable/, (match) => match[1]],
4006
+ [/^no such module '([^']+)'/, (match) => `module ${match[1]}`]
4007
+ ];
4008
+ function swiftApiGapReport(output) {
4009
+ const gaps = /* @__PURE__ */ new Map();
4010
+ const other = /* @__PURE__ */ new Map();
4011
+ const seen = /* @__PURE__ */ new Set();
4012
+ for (const line of output.split("\n")) {
4013
+ const diagnostic = /^(\S[^:]*\.swift):(\d+):(\d+): error: (.+)$/.exec(line);
4014
+ if (!diagnostic || seen.has(line)) continue;
4015
+ seen.add(line);
4016
+ const file = diagnostic[1].replace(new RegExp(`^${XCODE_APP_DIR}/`), "").replace(new RegExp(`^${XCODE_PACKAGES_DIR}/`), "");
4017
+ const message = diagnostic[4];
4018
+ const rule = API_GAP_PATTERNS.find(([pattern]) => pattern.test(message));
4019
+ const key = rule ? rule[1](rule[0].exec(message)) : message;
4020
+ const table = rule ? gaps : other;
4021
+ const entry = table.get(key) ?? { errors: 0, files: /* @__PURE__ */ new Set() };
4022
+ entry.errors++;
4023
+ entry.files.add(file);
4024
+ table.set(key, entry);
4025
+ }
4026
+ if (gaps.size === 0) return null;
4027
+ const rows = (table) => {
4028
+ const sorted = [...table].sort(
4029
+ ([left, a], [right, b]) => b.errors - a.errors || left.localeCompare(right)
4030
+ );
4031
+ const width = Math.min(48, Math.max(...sorted.map(([key]) => key.length)));
4032
+ return sorted.map(
4033
+ ([key, entry]) => ` ${key.padEnd(width)} ${String(entry.errors).padStart(3)} error${entry.errors === 1 ? " " : "s"} ${[...entry.files].sort().join(", ")}`
4034
+ );
4035
+ };
4036
+ const errors = [...gaps.values()].reduce((sum, entry) => sum + entry.errors, 0);
4037
+ return [
4038
+ `Peach lacks ${gaps.size} API${gaps.size === 1 ? "" : "s"} this app uses (${errors} error${errors === 1 ? "" : "s"}):`,
4039
+ ...rows(gaps),
4040
+ ...other.size > 0 ? ["other errors, often caused by the ones above:", ...rows(other)] : []
4041
+ ].join("\n");
4042
+ }
4043
+ function missingModulesMessage(packagePath, missing) {
4044
+ const layout = xcodeLayout(packagePath);
4045
+ const remote = new Map(
4046
+ (layout?.app.remoteProducts ?? []).map((entry) => [
4047
+ entry.product,
4048
+ entry.repositoryURL
4049
+ ])
4050
+ );
4051
+ const width = Math.max(...[...missing.keys()].map((name) => name.length));
4052
+ return [
4053
+ `Peach does not provide ${missing.size} module${missing.size === 1 ? "" : "s"} this app imports:`,
4054
+ ...[...missing].map(([name, files]) => {
4055
+ const source = remote.get(name);
4056
+ const reason = layout?.unavailable.get(name)?.reason;
4057
+ return ` ${name.padEnd(width)} ${files.length} file${files.length === 1 ? "" : "s"}${source ? `, package ${source}` : ""}${reason ? ` (${reason})` : ""}`;
4058
+ })
4059
+ ].join("\n");
4060
+ }
2612
4061
  async function compileRemote(packagePath, entry, snapshot, hosted) {
2613
4062
  const auth = hosted ? null : resolveCliAuth();
2614
4063
  if (!hosted && (!auth || auth.kind === "github")) {
2615
4064
  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`
4065
+ `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
4066
  );
2618
4067
  }
2619
4068
  const origin = hosted?.origin ?? resolveContrastBackendOrigin(auth?.kind === "session" ? auth.origin : null);
@@ -2628,6 +4077,13 @@ async function compileRemote(packagePath, entry, snapshot, hosted) {
2628
4077
  signal
2629
4078
  });
2630
4079
  if (!submit) throw new Error("swift compile: no credential to submit with");
4080
+ const sources = Object.values(snapshot.files);
4081
+ const bytes = sources.reduce((total2, text) => total2 + Buffer.byteLength(text), 0);
4082
+ if (sources.length > MAX_SWIFT_COMPILE_FILES || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES) {
4083
+ throw new Error(
4084
+ `${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`
4085
+ );
4086
+ }
2631
4087
  const descriptor = snapshot.native;
2632
4088
  const address = await compileSwiftProject(
2633
4089
  submit,
@@ -2644,7 +4100,7 @@ async function compileRemote(packagePath, entry, snapshot, hosted) {
2644
4100
  );
2645
4101
  if (descriptor && address.native?.hash !== descriptor.hash) {
2646
4102
  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`
4103
+ `${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
4104
  );
2649
4105
  }
2650
4106
  const response = await fetch(address.url, { signal });
@@ -2717,30 +4173,31 @@ function artifactFor(project, entry, moduleRoot) {
2717
4173
  return fresh;
2718
4174
  }
2719
4175
  function swiftPackageWatchFiles(packagePath, moduleRoot) {
2720
- packagePath = import_node_fs7.default.realpathSync(packagePath);
4176
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2721
4177
  return [
2722
- import_node_path8.default.join(packagePath, "Package.swift"),
4178
+ ...xcodeProjects.has(packagePath) ? [] : [import_node_path10.default.join(packagePath, "Package.swift")],
2723
4179
  ...sourceFiles(packagePath),
2724
4180
  ...nativeSourceFiles(packagePath),
2725
4181
  ...resourceCandidateFiles(packagePath),
2726
- ...moduleRoot ? swiftModuleInputFiles(moduleRoot).map((file) => import_node_path8.default.join(moduleRoot, file)) : []
4182
+ ...moduleRoot ? swiftModuleInputFiles(moduleRoot).map((file) => import_node_path10.default.join(moduleRoot, file)) : []
2727
4183
  ];
2728
4184
  }
2729
4185
  async function swiftPackageMetadata(packagePath, packageName, moduleRoot, origin, hosted) {
2730
- packagePath = import_node_fs7.default.realpathSync(packagePath);
4186
+ packagePath = import_node_fs9.default.realpathSync(packagePath);
2731
4187
  const mains = sourceFiles(packagePath).filter(
2732
- (file) => /@main\s+(?:public\s+)?struct\s+\w+\s*:/.test(
4188
+ (file) => swiftApplicationEntry(
4189
+ file,
2733
4190
  readPackageFile(packagePath, file, MAX_SWIFT_COMPILE_SOURCE_BYTES).toString("utf8")
2734
4191
  )
2735
4192
  );
2736
4193
  const native = nativeSourceDescriptor(packagePath);
2737
4194
  if (mains.length > 1 || mains.length === 0 && !native) {
2738
4195
  throw new Error(
2739
- `swift package ${packageName} needs exactly one @main source or generated native modules; found ${mains.length}`
4196
+ `swift package ${packageName} needs exactly one application entry source or generated native modules; found ${mains.length}`
2740
4197
  );
2741
4198
  }
2742
4199
  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(
4200
+ 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
4201
  ([_file, names]) => names.length > 0
2745
4202
  )?.[0];
2746
4203
  if (!entry) throw new Error(`swift package ${packageName} has no native module source`);
@@ -2829,12 +4286,12 @@ function artifactUrl(project, artifact) {
2829
4286
  return `${serverOrigin()}${ARTIFACT_PATH2}${artifact.hash}.wasm`;
2830
4287
  }
2831
4288
  function packageFor(file) {
2832
- let dir = import_node_path9.default.dirname(file);
4289
+ let dir = import_node_path11.default.dirname(file);
2833
4290
  const stop = devServer?.config.root;
2834
4291
  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);
4292
+ if (import_node_fs10.default.existsSync(import_node_path11.default.join(dir, "Package.swift"))) return dir;
4293
+ if (stop !== void 0 && dir === stop || import_node_path11.default.dirname(dir) === dir) break;
4294
+ dir = import_node_path11.default.dirname(dir);
2838
4295
  }
2839
4296
  throw new Error(
2840
4297
  `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 +4312,9 @@ function swiftPlugin(options = {}) {
2855
4312
  if (!resolved) throw new Error(`cannot resolve swift source ${source}`);
2856
4313
  let id = resolved.id;
2857
4314
  if (importer && (source.startsWith("./") || source.startsWith("../"))) {
2858
- const raw2 = import_node_path9.default.resolve(import_node_path9.default.dirname(importer.split("?")[0] ?? importer), source);
4315
+ const raw2 = import_node_path11.default.resolve(import_node_path11.default.dirname(importer.split("?")[0] ?? importer), source);
2859
4316
  try {
2860
- if (import_node_fs8.default.realpathSync(raw2) === import_node_fs8.default.realpathSync(resolved.id)) id = raw2;
4317
+ if (import_node_fs10.default.realpathSync(raw2) === import_node_fs10.default.realpathSync(resolved.id)) id = raw2;
2861
4318
  } catch {
2862
4319
  }
2863
4320
  }
@@ -2866,22 +4323,22 @@ function swiftPlugin(options = {}) {
2866
4323
  async load(id) {
2867
4324
  if (!id.startsWith(VIRTUAL_PREFIX)) return null;
2868
4325
  const file = id.slice(VIRTUAL_PREFIX.length);
2869
- if (!import_node_fs8.default.existsSync(file)) throw new Error(`swift source ${file} no longer exists`);
4326
+ if (!import_node_fs10.default.existsSync(file)) throw new Error(`swift source ${file} no longer exists`);
2870
4327
  const packagePath = options.packagePath ?? packageFor(file);
2871
4328
  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);
4329
+ const entry = import_node_path11.default.relative(packagePath, file).split(import_node_path11.default.sep).join(import_node_path11.default.posix.sep);
2873
4330
  for (const source of [
2874
4331
  ...sourceFiles(packagePath),
2875
4332
  ...nativeSourceFiles(packagePath)
2876
4333
  ])
2877
4334
  this.addWatchFile(source);
2878
- this.addWatchFile(import_node_path9.default.join(packagePath, "Package.swift"));
4335
+ this.addWatchFile(import_node_path11.default.join(packagePath, "Package.swift"));
2879
4336
  const moduleRoot = linkedModuleRoots(packagePath).find(
2880
- (root) => import_node_fs8.default.existsSync(import_node_path9.default.join(root, "toolchain.json"))
4337
+ (root) => import_node_fs10.default.existsSync(import_node_path11.default.join(root, "toolchain.json"))
2881
4338
  );
2882
4339
  if (moduleRoot)
2883
4340
  for (const relative of swiftModuleInputFiles(moduleRoot))
2884
- this.addWatchFile(import_node_path9.default.join(moduleRoot, relative));
4341
+ this.addWatchFile(import_node_path11.default.join(moduleRoot, relative));
2885
4342
  let artifact;
2886
4343
  try {
2887
4344
  artifact = await artifactFor(project, entry);
@@ -2900,7 +4357,7 @@ function swiftPlugin(options = {}) {
2900
4357
  ...artifact.package.resources.watched,
2901
4358
  ...artifact.package.bundleFiles.watched
2902
4359
  ])
2903
- this.addWatchFile(import_node_path9.default.join(packagePath, ...watched.split(import_node_path9.default.posix.sep)));
4360
+ this.addWatchFile(import_node_path11.default.join(packagePath, ...watched.split(import_node_path11.default.posix.sep)));
2904
4361
  const colors = artifact.package.resources.colors;
2905
4362
  const symbols = artifact.package.resources.symbols;
2906
4363
  const bundleFiles = artifact.package.bundleFiles.files;