peachsim 0.1.696 → 0.1.698

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 (75) hide show
  1. package/detox/index.ts +21 -11
  2. package/dist-lib/agent-daemon-client.cjs +1 -1
  3. package/dist-lib/agent-events.cjs +1 -1
  4. package/dist-lib/agent-identity.cjs +1 -1
  5. package/dist-lib/agent-sessions.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +1 -1
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +1 -1
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +1 -1
  16. package/dist-lib/capture-contract.cjs +1 -1
  17. package/dist-lib/capture-contract.mjs +1 -1
  18. package/dist-lib/cli-constants.cjs +1 -1
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +1 -1
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +1 -1
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +1 -1
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/detox/index.cjs +747 -31
  27. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  28. package/dist-lib/home-paths.cjs +1 -1
  29. package/dist-lib/host/bridge-host.cjs +1561 -1439
  30. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  31. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  32. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  33. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  34. package/dist-lib/host/websocket-proxy.cjs +1 -1
  35. package/dist-lib/index.cjs +1 -1
  36. package/dist-lib/jump-to-source-babel.cjs +1 -1
  37. package/dist-lib/jump-to-source-native.cjs +1 -1
  38. package/dist-lib/kotlin-host.cjs +1 -1
  39. package/dist-lib/menu.cjs +1 -1
  40. package/dist-lib/menu.mjs +1 -1
  41. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  42. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  43. package/dist-lib/metro-production-bundle.cjs +1 -1
  44. package/dist-lib/metro-production-bundle.mjs +1 -1
  45. package/dist-lib/metro.cjs +1 -1
  46. package/dist-lib/native-app-identity.cjs +1 -1
  47. package/dist-lib/native-app-identity.mjs +1 -1
  48. package/dist-lib/native-firebase-metadata.cjs +1 -1
  49. package/dist-lib/native-firebase-metadata.mjs +1 -1
  50. package/dist-lib/plist.cjs +1 -1
  51. package/dist-lib/plist.mjs +1 -1
  52. package/dist-lib/profiles.cjs +1 -1
  53. package/dist-lib/public-brand.cjs +1 -1
  54. package/dist-lib/react-native-host-modules.cjs +1 -1
  55. package/dist-lib/react-native-host-modules.mjs +1 -1
  56. package/dist-lib/render-mode.cjs +1 -1
  57. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  58. package/dist-lib/sdk.cjs +1 -1
  59. package/dist-lib/sdk.mjs +1 -1
  60. package/dist-lib/skills.cjs +1482 -1359
  61. package/dist-lib/swift-compile.cjs +3 -1
  62. package/dist-lib/swift-compile.mjs +2 -1
  63. package/dist-lib/swift-package.cjs +1 -1
  64. package/dist-lib/swift-package.mjs +1 -1
  65. package/dist-lib/swift-submit.cjs +2 -2
  66. package/dist-lib/swift-submit.mjs +2 -2
  67. package/dist-lib/swift-toolchain.cjs +1 -1
  68. package/dist-lib/swift.cjs +1 -1
  69. package/dist-lib/vite-swift.cjs +2 -2
  70. package/dist-lib/vite.cjs +1 -1
  71. package/package.json +1 -1
  72. package/src/expo-swift-host.ts +174 -43
  73. package/src/expoSwiftContract.ts +19 -0
  74. package/src/swift-compile.ts +1 -1
  75. package/src/swift-submit.ts +2 -1
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.696 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.698 | (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;
@@ -6097,1508 +6097,1508 @@ var RNX_FORKED_SCRIPT_ENV = "PEACH_RUNS_FORKED_SCRIPTS";
6097
6097
  // src/expo-swift-host.ts
6098
6098
  init_backend_origin();
6099
6099
 
6100
- // src/swift-distribution.ts
6101
- var import_node_fs11 = __toESM(require("node:fs"), 1);
6102
- var import_node_path11 = __toESM(require("node:path"), 1);
6103
-
6104
- // ../contrast-runtime-delivery/src/index.ts
6105
- var import_node_child_process2 = require("node:child_process");
6106
- var import_node_crypto2 = __toESM(require("node:crypto"), 1);
6107
- var import_node_fs7 = __toESM(require("node:fs"), 1);
6100
+ // src/swift-compile.ts
6101
+ var import_node_child_process3 = require("node:child_process");
6102
+ var import_node_crypto3 = require("node:crypto");
6103
+ var import_node_fs7 = require("node:fs");
6108
6104
  var import_node_os2 = __toESM(require("node:os"), 1);
6109
6105
  var import_node_path7 = __toESM(require("node:path"), 1);
6110
- var import_node_stream = require("node:stream");
6111
- var import_promises3 = require("node:stream/promises");
6106
+ var import_node_util2 = require("node:util");
6112
6107
 
6113
- // ../contrast-runtime-delivery/src/product.ts
6114
- var import_node_fs6 = __toESM(require("node:fs"), 1);
6115
- var import_node_path6 = __toESM(require("node:path"), 1);
6116
- function isValidRuntimeVersion(value) {
6117
- return value.length <= 100 && /^[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value);
6108
+ // src/swift-distribution-contract.ts
6109
+ init_is_record();
6110
+ var SWIFT_DISTRIBUTION_MANIFEST = "distribution.json";
6111
+ var SWIFT_DISTRIBUTION_HOSTS = [
6112
+ "darwin-arm64",
6113
+ "linux-x64",
6114
+ "linux-arm64"
6115
+ ];
6116
+ function swiftDistributionHost(platform, arch) {
6117
+ const host2 = `${platform}-${arch}`;
6118
+ return SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === host2) ?? null;
6118
6119
  }
6119
- function listInstalledRuntimes(product) {
6120
- try {
6121
- return import_node_fs6.default.readdirSync(product.runtimesDir(), { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort(compareSemver);
6122
- } catch {
6123
- return [];
6120
+ var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
6121
+ function parseSwiftDistributionManifest(value) {
6122
+ if (!isRecord(value) || typeof value.id !== "string" || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || !isStrings(value.modules) || !isStrings(value.objects) || !isStrings(value.link) || !isRecord(value.files) || !Object.values(value.files).every((sha) => typeof sha === "string") || typeof value.host !== "string" || !isStrings(value.plugins)) {
6123
+ throw new Error(`invalid Swift distribution ${SWIFT_DISTRIBUTION_MANIFEST}`);
6124
6124
  }
6125
- }
6126
- function runtimeTarballCacheName(product, version) {
6127
- return import_node_path6.default.posix.basename(product.tarballPath(version));
6128
- }
6129
- function compareSemver(a, b) {
6130
- const parse2 = (v) => {
6131
- const hyphen = v.indexOf("-");
6132
- const core = hyphen >= 0 ? v.slice(0, hyphen) : v;
6133
- const pre = hyphen >= 0 ? v.slice(hyphen + 1) : "";
6134
- const parts = core.split(".").map((n) => Number.parseInt(n, 10));
6135
- if (parts.some((n) => !Number.isFinite(n))) return [[Number.POSITIVE_INFINITY], v];
6136
- return [parts, pre];
6125
+ const host2 = SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === value.host);
6126
+ if (!host2) throw new Error(`Swift distribution names an unknown host ${value.host}`);
6127
+ return {
6128
+ id: value.id,
6129
+ release: value.release,
6130
+ wasmSdkId: value.wasmSdkId,
6131
+ wasmSdkUrl: value.wasmSdkUrl,
6132
+ wasmSdkChecksum: value.wasmSdkChecksum,
6133
+ modules: value.modules,
6134
+ objects: value.objects,
6135
+ link: value.link,
6136
+ files: Object.fromEntries(
6137
+ Object.entries(value.files).map(([file, sha]) => [file, String(sha)])
6138
+ ),
6139
+ host: host2,
6140
+ plugins: value.plugins
6137
6141
  };
6138
- const [an, ap] = parse2(a);
6139
- const [bn, bp] = parse2(b);
6140
- for (let i = 0; i < Math.max(an.length, bn.length); i++) {
6141
- const av = an[i] ?? 0;
6142
- const bv = bn[i] ?? 0;
6143
- if (av !== bv) return av - bv;
6142
+ }
6143
+ function parseSwiftDistributionLock(value) {
6144
+ if (!isRecord(value) || typeof value.id !== "string" || !/^[a-f0-9]{16}$/.test(value.id) || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || typeof value.source !== "string" || !isRecord(value.hosts)) {
6145
+ throw new Error("invalid Swift distribution lock");
6144
6146
  }
6145
- if (ap === bp) return 0;
6146
- if (!ap) return 1;
6147
- if (!bp) return -1;
6148
- return ap < bp ? -1 : 1;
6147
+ const hosts = value.hosts;
6148
+ const entry = (host2) => {
6149
+ const item = hosts[host2];
6150
+ if (!isRecord(item) || typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256) || typeof item.size !== "number") {
6151
+ throw new Error(`invalid Swift distribution lock entry for ${host2}`);
6152
+ }
6153
+ return { sha256: item.sha256, size: item.size };
6154
+ };
6155
+ return {
6156
+ id: value.id,
6157
+ release: value.release,
6158
+ wasmSdkId: value.wasmSdkId,
6159
+ wasmSdkUrl: value.wasmSdkUrl,
6160
+ wasmSdkChecksum: value.wasmSdkChecksum,
6161
+ source: value.source,
6162
+ hosts: {
6163
+ "darwin-arm64": entry("darwin-arm64"),
6164
+ "linux-x64": entry("linux-x64"),
6165
+ "linux-arm64": entry("linux-arm64")
6166
+ }
6167
+ };
6168
+ }
6169
+ function swiftDistributionKey(id, host2) {
6170
+ return `${id}/${host2}.tar.gz`;
6149
6171
  }
6150
6172
 
6151
- // ../contrast-runtime-delivery/src/index.ts
6152
- var DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT = 2;
6153
- function createRuntimeDelivery(product) {
6154
- function readConfig() {
6155
- try {
6156
- const parsed = JSON.parse(
6157
- import_node_fs7.default.readFileSync(product.configFile(), "utf8")
6158
- );
6159
- return parsed && typeof parsed === "object" ? parsed : {};
6160
- } catch {
6161
- return {};
6162
- }
6163
- }
6164
- function resolveCdnOrigin(input) {
6165
- const config = readConfig();
6166
- const value = input || process.env[product.env.cdnOrigin] || config.cdnOrigin || product.defaultCdnOrigin;
6167
- return value.replace(/\/+$/, "");
6168
- }
6169
- function resolveChannel(input) {
6170
- const config = readConfig();
6171
- return input || process.env[product.env.channel] || config.runtimeChannel || "stable";
6172
- }
6173
- function resolvePin() {
6174
- if (!product.env.pin) return null;
6175
- const env = process.env[product.env.pin];
6176
- if (env && env.trim()) return env.trim();
6177
- const config = readConfig();
6178
- return typeof config.runtimeVersion === "string" && config.runtimeVersion.trim() ? config.runtimeVersion.trim() : null;
6179
- }
6180
- function manifestUrl(cdnOrigin) {
6181
- const url = new URL(`${resolveCdnOrigin(cdnOrigin)}${product.manifestPath}`);
6182
- url.searchParams.set("t", String(Date.now()));
6183
- return url.toString();
6184
- }
6185
- function tarballUrl(version, cdnOrigin) {
6186
- return `${resolveCdnOrigin(cdnOrigin)}${product.tarballPath(version)}`;
6173
+ // src/swift-icu.ts
6174
+ var import_node_child_process2 = require("node:child_process");
6175
+ var import_node_crypto2 = require("node:crypto");
6176
+ var import_node_fs6 = require("node:fs");
6177
+ var import_node_path6 = __toESM(require("node:path"), 1);
6178
+ var import_node_util = require("node:util");
6179
+ var import_node_zlib = require("node:zlib");
6180
+ var run = (0, import_node_util.promisify)(import_node_child_process2.execFile);
6181
+ var deflate = (0, import_node_util.promisify)(import_node_zlib.gzip);
6182
+ var ARCHIVE = "wasi/lib_FoundationICU.a";
6183
+ var MEMBER = "icu_packaged_data.cpp.obj";
6184
+ var raw = /* @__PURE__ */ new Map();
6185
+ var assets = /* @__PURE__ */ new Map();
6186
+ function memo(cache, key, load2) {
6187
+ let pending = cache.get(key);
6188
+ if (!pending) {
6189
+ pending = load2();
6190
+ pending.catch(() => cache.delete(key));
6191
+ cache.set(key, pending);
6187
6192
  }
6188
- const UP_TO_DATE_CHECK_TIMEOUT_MS = 2e3;
6189
- async function fetchManifest(cdnOrigin, timeoutMs) {
6190
- const url = manifestUrl(cdnOrigin);
6191
- const res = await fetch(url, {
6192
- headers: { Accept: "application/json" },
6193
- // an install is allowed to wait; a best-effort check is not. see
6194
- // UP_TO_DATE_CHECK_TIMEOUT_MS.
6195
- ...timeoutMs ? { signal: AbortSignal.timeout(timeoutMs) } : {}
6196
- });
6197
- if (!res.ok) {
6198
- throw new Error(`manifest fetch failed: ${res.status} ${res.statusText} (${url})`);
6199
- }
6200
- return await res.json();
6193
+ return pending;
6194
+ }
6195
+ function swiftIcuData(toolchainBin, sdk) {
6196
+ return memo(raw, `${toolchainBin}\0${sdk}`, () => load(toolchainBin, sdk));
6197
+ }
6198
+ function swiftIcuAsset(toolchainBin, sdk) {
6199
+ return memo(assets, `${toolchainBin}\0${sdk}`, async () => {
6200
+ const zipped = await deflate(await swiftIcuData(toolchainBin, sdk));
6201
+ return { sha256: (0, import_node_crypto2.createHash)("sha256").update(zipped).digest("hex"), gzip: zipped };
6202
+ });
6203
+ }
6204
+ async function load(toolchainBin, sdk) {
6205
+ const { stdout } = await run(import_node_path6.default.join(toolchainBin, "swift"), [
6206
+ "sdk",
6207
+ "configure",
6208
+ "--show-configuration",
6209
+ sdk,
6210
+ "wasm32-unknown-wasip1"
6211
+ ]);
6212
+ const resources = /^swiftStaticResourcesPath: (.+)$/m.exec(stdout)?.[1]?.trim();
6213
+ if (!resources) throw new Error(`swift-icu: ${sdk} names no static resources`);
6214
+ return Buffer.from(
6215
+ icuSegment(archiveMember((0, import_node_fs6.readFileSync)(import_node_path6.default.join(resources, ARCHIVE)), MEMBER))
6216
+ );
6217
+ }
6218
+ function archiveMember(archive, name2) {
6219
+ if (archive.toString("latin1", 0, 8) !== "!<arch>\n")
6220
+ throw new Error("swift-icu: not an ar archive");
6221
+ let names = "";
6222
+ for (let at = 8; at + 60 <= archive.length; ) {
6223
+ const raw2 = archive.toString("latin1", at, at + 16).trimEnd();
6224
+ const size = Number(archive.toString("latin1", at + 48, at + 58).trim());
6225
+ const body = archive.subarray(at + 60, at + 60 + size);
6226
+ if (raw2 === "//") names = body.toString("latin1");
6227
+ const member = /^\/\d+$/.test(raw2) ? names.slice(Number(raw2.slice(1)), names.indexOf("/\n", Number(raw2.slice(1)))) : raw2.replace(/\/$/, "");
6228
+ if (member === name2) return body;
6229
+ at += 60 + size + size % 2;
6201
6230
  }
6202
- function resolveVersion(manifest, opts = {}) {
6203
- const channel = resolveChannel(opts.channel);
6204
- const version = opts.version || resolvePin() || manifest.channels[channel]?.latest;
6205
- if (!version) {
6206
- throw new Error(
6207
- `no version specified and channel '${channel}' has no latest entry in the manifest`
6208
- );
6209
- }
6210
- if (!isValidRuntimeVersion(version)) {
6211
- throw new Error(`invalid runtime version: ${version}`);
6212
- }
6213
- const entry = manifest.versions[version];
6214
- if (!entry) {
6215
- throw new Error(
6216
- `version ${version} not found in manifest; available: ${Object.keys(manifest.versions).slice(-10).join(", ") || "(none)"}`
6217
- );
6231
+ throw new Error(`swift-icu: ${name2} is not in the sdk's icu archive`);
6232
+ }
6233
+ function icuSegment(object) {
6234
+ let at = 8;
6235
+ const leb = () => {
6236
+ let result = 0;
6237
+ let shift = 0;
6238
+ let byte;
6239
+ do {
6240
+ byte = object[at++];
6241
+ result += (byte & 127) * 2 ** shift;
6242
+ shift += 7;
6243
+ } while (byte & 128);
6244
+ return result;
6245
+ };
6246
+ const found = [];
6247
+ while (at < object.length) {
6248
+ const id = object[at++];
6249
+ const size = leb();
6250
+ const end = at + size;
6251
+ if (id === 11) {
6252
+ for (let count = leb(); count > 0; count--) {
6253
+ if (leb() !== 0) throw new Error("swift-icu: unexpected data segment kind");
6254
+ at++;
6255
+ leb();
6256
+ at++;
6257
+ const length = leb();
6258
+ const bytes = object.subarray(at, at + length);
6259
+ if (bytes[2] === 218 && bytes[3] === 39) found.push(bytes);
6260
+ at += length;
6261
+ }
6218
6262
  }
6219
- return { version, channel, entry };
6263
+ at = end;
6220
6264
  }
6221
- async function install(opts = {}) {
6222
- product.ensureHome();
6223
- const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
6224
- const manifest = await fetchManifest(cdnOrigin);
6225
- const { version, channel, entry } = resolveVersion(manifest, opts);
6226
- const destDir = product.runtimeDir(version);
6227
- const setActive = opts.setActive !== false;
6228
- const protectVersions = [version, ...opts.protectVersions ?? []];
6229
- pruneLocalRetention({ protectVersions });
6230
- if (!opts.force && import_node_fs7.default.existsSync(import_node_path7.default.join(destDir, product.installedMarker))) {
6231
- if (setActive) product.writeActiveRuntime(version);
6232
- pruneLocalRetention({ protectVersions });
6233
- return {
6234
- version,
6235
- channel,
6236
- cdnOrigin,
6237
- runtimeDir: destDir,
6238
- installed: false,
6239
- activated: setActive,
6240
- manifest
6241
- };
6242
- }
6243
- if (!opts.quiet)
6244
- process.stderr.write(`${product.id}: downloading runtime ${version}\u2026
6245
- `);
6246
- await installVerifiedTarball({
6247
- url: entry.tarball || tarballUrl(version, cdnOrigin),
6248
- digest: { algorithm: "sha256", encoding: "hex", value: entry.sha256 },
6249
- destDir,
6250
- installedMarker: product.installedMarker,
6251
- label: `runtime ${version}`
6252
- });
6253
- if (setActive) product.writeActiveRuntime(version);
6254
- pruneLocalRetention({ protectVersions });
6255
- return {
6256
- version,
6257
- channel,
6258
- cdnOrigin,
6259
- runtimeDir: destDir,
6260
- installed: true,
6261
- activated: setActive,
6262
- manifest
6263
- };
6264
- }
6265
- async function updateToLatest(opts = {}) {
6266
- product.ensureHome();
6267
- pruneLocalRetention({ protectVersions: opts.protectVersions });
6268
- const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
6269
- const channel = resolveChannel(opts.channel);
6270
- const pin = resolvePin();
6271
- if (pin) {
6272
- const activeVersion2 = product.readActiveRuntime();
6273
- const pinInstalled = import_node_fs7.default.existsSync(
6274
- import_node_path7.default.join(product.runtimeDir(pin), product.installedMarker)
6275
- );
6276
- if (activeVersion2 === pin && pinInstalled) {
6277
- return {
6278
- checked: true,
6279
- updated: false,
6280
- reason: `runtime is pinned to ${pin}`,
6281
- activeVersion: activeVersion2,
6282
- latestVersion: pin
6283
- };
6265
+ if (found.length !== 1)
6266
+ throw new Error(`swift-icu: expected one icu data segment, found ${found.length}`);
6267
+ return found[0];
6268
+ }
6269
+
6270
+ // src/swift-package.ts
6271
+ function swiftManifestTargets(manifest) {
6272
+ const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
6273
+ const targets = [];
6274
+ const pattern = /\.(executableTarget|target)\s*\(/g;
6275
+ let match;
6276
+ while ((match = pattern.exec(code)) !== null) {
6277
+ const executable = match[1] === "executableTarget";
6278
+ let depth = 1;
6279
+ const start = pattern.lastIndex;
6280
+ let i = start;
6281
+ let inString = false;
6282
+ let escaped = false;
6283
+ let flat = "";
6284
+ while (i < code.length && depth > 0) {
6285
+ const ch = code[i];
6286
+ if (inString) {
6287
+ if (escaped) escaped = false;
6288
+ else if (ch === "\\") escaped = true;
6289
+ else if (ch === '"') inString = false;
6290
+ if (depth === 1) flat += ch;
6291
+ } else if (ch === '"') {
6292
+ inString = true;
6293
+ if (depth === 1) flat += ch;
6294
+ } else if (ch === "(") {
6295
+ depth++;
6296
+ if (depth === 1) flat += ch;
6297
+ } else if (ch === ")") {
6298
+ depth--;
6299
+ if (depth >= 1) flat += ch;
6300
+ } else if (depth === 1) {
6301
+ flat += ch;
6284
6302
  }
6285
- const installed2 = await install({
6286
- version: pin,
6287
- channel,
6288
- cdnOrigin,
6289
- setActive: false,
6290
- protectVersions: opts.protectVersions
6291
- });
6292
- return {
6293
- checked: true,
6294
- updated: true,
6295
- reason: `runtime is pinned to ${pin}`,
6296
- activeVersion: pin,
6297
- latestVersion: pin,
6298
- install: installed2
6299
- };
6300
- }
6301
- const manifest = await fetchManifest(cdnOrigin);
6302
- const latestVersion = manifest.channels[channel]?.latest;
6303
- if (!latestVersion) {
6304
- return {
6305
- checked: true,
6306
- updated: false,
6307
- reason: `channel '${channel}' has no latest runtime`,
6308
- activeVersion: product.readActiveRuntime()
6309
- };
6310
- }
6311
- const entry = manifest.versions[latestVersion];
6312
- if (!entry) {
6313
- return {
6314
- checked: true,
6315
- updated: false,
6316
- reason: `manifest is missing version ${latestVersion}`,
6317
- activeVersion: product.readActiveRuntime(),
6318
- latestVersion
6319
- };
6320
- }
6321
- const activeVersion = product.readActiveRuntime();
6322
- const activeDir = activeVersion ? product.runtimeDir(activeVersion) : null;
6323
- const activeInstalled = activeDir ? import_node_fs7.default.existsSync(import_node_path7.default.join(activeDir, product.installedMarker)) : false;
6324
- const shouldInstall = !activeVersion || !activeInstalled || compareSemver(latestVersion, activeVersion) > 0;
6325
- if (!shouldInstall) {
6326
- return {
6327
- checked: true,
6328
- updated: false,
6329
- reason: "active runtime is current",
6330
- activeVersion,
6331
- latestVersion
6332
- };
6303
+ i++;
6333
6304
  }
6334
- const installed = await install({
6335
- version: latestVersion,
6336
- channel,
6337
- cdnOrigin,
6338
- setActive: false,
6339
- protectVersions: opts.protectVersions
6305
+ const name2 = /\bname\s*:\s*"([^"]+)"/.exec(flat)?.[1];
6306
+ if (!name2) continue;
6307
+ const rawPath = /\bpath\s*:\s*"([^"]*)"/.exec(flat)?.[1];
6308
+ const targetPath = rawPath == null || rawPath === "" ? `Sources/${name2}` : rawPath.replace(/^\.\//, "").replace(/\/+$/, "");
6309
+ const call = code.slice(start, i);
6310
+ const languageMode = Number(
6311
+ /\.swiftLanguageMode\(\s*\.v(\d+)\s*\)/.exec(call)?.[1] ?? "5"
6312
+ );
6313
+ const mainActorIsolation = /\.defaultIsolation\(\s*MainActor\.self\s*\)/.test(call);
6314
+ const resources = /\bresources\s*:/.test(flat);
6315
+ targets.push({
6316
+ name: name2,
6317
+ path: targetPath,
6318
+ executable,
6319
+ languageMode,
6320
+ mainActorIsolation,
6321
+ resources
6340
6322
  });
6341
- return {
6342
- checked: true,
6343
- updated: true,
6344
- activeVersion: latestVersion,
6345
- latestVersion,
6346
- install: installed
6347
- };
6348
6323
  }
6349
- async function checkUpToDate(opts = {}) {
6350
- const active = product.readActiveRuntime();
6351
- const pinned = resolvePin();
6352
- if (pinned) {
6353
- return { active, latest: pinned, pinned, outdated: active !== pinned };
6324
+ return targets;
6325
+ }
6326
+ function swiftPackagePartition(manifest) {
6327
+ const targets = swiftManifestTargets(manifest);
6328
+ return targets.length === 1 && targets[0].executable && targets[0].path === "." ? [] : targets;
6329
+ }
6330
+
6331
+ // src/swift-compile.ts
6332
+ var run2 = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
6333
+ var WASM_TRIPLE = "wasm32-unknown-wasip1";
6334
+ var cores = import_node_os2.default.availableParallelism();
6335
+ var BUILD_ENV = { ...process.env, BINARYEN_CORES: String(Math.min(4, cores)) };
6336
+ var BUILD_JOBS = String(Math.max(1, Math.floor(cores / 2)));
6337
+ function swiftDistributionAt(root) {
6338
+ const file = import_node_path7.default.join(root, SWIFT_DISTRIBUTION_MANIFEST);
6339
+ if (!(0, import_node_fs7.existsSync)(file)) return null;
6340
+ return parseSwiftDistributionManifest(JSON.parse((0, import_node_fs7.readFileSync)(file, "utf8")));
6341
+ }
6342
+ function swiftModuleSdk(root) {
6343
+ const pin = swiftDistributionAt(root) ?? JSON.parse((0, import_node_fs7.readFileSync)(import_node_path7.default.join(root, "toolchain.json"), "utf8"));
6344
+ if (!pin || typeof pin !== "object" || typeof Reflect.get(pin, "wasmSdkId") !== "string" || typeof Reflect.get(pin, "wasmSdkUrl") !== "string" || typeof Reflect.get(pin, "wasmSdkChecksum") !== "string")
6345
+ throw new Error(`${root} pins no wasm SDK id, url and checksum`);
6346
+ return {
6347
+ wasmSdkId: String(Reflect.get(pin, "wasmSdkId")),
6348
+ wasmSdkUrl: String(Reflect.get(pin, "wasmSdkUrl")),
6349
+ wasmSdkChecksum: String(Reflect.get(pin, "wasmSdkChecksum"))
6350
+ };
6351
+ }
6352
+ function swiftModuleInputFiles(root) {
6353
+ if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST];
6354
+ const files = [
6355
+ "Package.swift",
6356
+ "scripts/contrast-app-Package.swift",
6357
+ "toolchain.json"
6358
+ ];
6359
+ const walk = (dir) => {
6360
+ for (const entry of (0, import_node_fs7.readdirSync)(import_node_path7.default.join(root, dir), { withFileTypes: true })) {
6361
+ const relative2 = `${dir}/${entry.name}`;
6362
+ if (entry.isDirectory()) walk(relative2);
6363
+ else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative2);
6354
6364
  }
6355
- try {
6356
- const manifest = await fetchManifest(
6357
- resolveCdnOrigin(opts.cdnOrigin),
6358
- UP_TO_DATE_CHECK_TIMEOUT_MS
6359
- );
6360
- const channel = resolveChannel(opts.channel);
6361
- const latest = manifest.channels[channel]?.latest ?? null;
6362
- const outdated = !!(latest && (!active || compareSemver(latest, active) > 0));
6363
- return { active, latest, pinned: null, outdated };
6364
- } catch {
6365
- return { active, latest: null, pinned: null, outdated: false };
6365
+ };
6366
+ walk("Sources");
6367
+ return files.sort();
6368
+ }
6369
+ async function ensureMacroPlugins(moduleRoot, toolchainBin) {
6370
+ const distribution = swiftDistributionAt(moduleRoot);
6371
+ if (distribution)
6372
+ return distribution.plugins.map((plugin) => import_node_path7.default.join(moduleRoot, plugin));
6373
+ const dir = import_node_path7.default.join(moduleRoot, ".build/host/RnxPreviewMacros");
6374
+ const ext = process.platform === "darwin" ? "dylib" : "so";
6375
+ const plugins = [
6376
+ {
6377
+ library: import_node_path7.default.join(dir, `libRnxPreviewMacros.${ext}`),
6378
+ source: import_node_path7.default.join(moduleRoot, "Sources/RnxPreviewMacros/PreviewMacro.swift")
6379
+ },
6380
+ {
6381
+ library: import_node_path7.default.join(dir, `libFoundationMacros.${ext}`),
6382
+ source: import_node_path7.default.join(moduleRoot, "Sources/FoundationMacros/PredicateMacro.swift")
6366
6383
  }
6384
+ ];
6385
+ const stale = plugins.some(
6386
+ ({ library, source }) => !(0, import_node_fs7.existsSync)(library) || (0, import_node_fs7.statSync)(source).mtimeMs > (0, import_node_fs7.statSync)(library).mtimeMs
6387
+ );
6388
+ if (stale) {
6389
+ await run2("sh", [
6390
+ import_node_path7.default.join(moduleRoot, "scripts/build-preview-plugin.sh"),
6391
+ toolchainBin,
6392
+ plugins[0].library
6393
+ ]);
6367
6394
  }
6368
- function planLocalRetention(opts = {}) {
6369
- product.ensureHome();
6370
- const retainVersions = Math.max(
6371
- 1,
6372
- Math.floor(opts.retainVersions ?? DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT)
6395
+ return plugins.map(({ library }) => library);
6396
+ }
6397
+ var linkedModuleDigests = /* @__PURE__ */ new Map();
6398
+ function swiftModuleDigest(root) {
6399
+ const files = swiftModuleInputFiles(root);
6400
+ const stampHash = (0, import_node_crypto3.createHash)("sha256");
6401
+ for (const file of files) {
6402
+ const stat2 = (0, import_node_fs7.statSync)(import_node_path7.default.join(root, file), { bigint: true });
6403
+ stampHash.update(file);
6404
+ stampHash.update(
6405
+ `${stat2.dev}:${stat2.ino}:${stat2.size}:${stat2.mtimeNs}:${stat2.ctimeNs}
6406
+ `
6373
6407
  );
6374
- const installed = listInstalledRuntimes(product);
6375
- const installedSet = new Set(installed);
6376
- const activeVersion = product.readActiveRuntime();
6377
- const pinnedVersion = resolvePin();
6378
- const keep = /* @__PURE__ */ new Set();
6379
- for (const version of [
6380
- activeVersion,
6381
- pinnedVersion,
6382
- ...opts.protectVersions ?? []
6383
- ]) {
6384
- if (version && installedSet.has(version)) keep.add(version);
6385
- }
6386
- for (const version of [...installed].reverse()) {
6387
- if (keep.size >= retainVersions) break;
6388
- keep.add(version);
6389
- }
6390
- const cacheTemplateMarker = "__RUNTIME_VERSION__";
6391
- const cacheTemplate = runtimeTarballCacheName(product, cacheTemplateMarker);
6392
- const markerOffset = cacheTemplate.indexOf(cacheTemplateMarker);
6393
- const cachePrefix = cacheTemplate.slice(0, markerOffset);
6394
- const cacheSuffix = cacheTemplate.slice(markerOffset + cacheTemplateMarker.length);
6395
- let removeCacheFiles = [];
6396
- if (markerOffset >= 0) {
6397
- try {
6398
- removeCacheFiles = import_node_fs7.default.readdirSync(product.cacheDir(), { withFileTypes: true }).filter((entry) => {
6399
- if (!entry.isFile()) return false;
6400
- const complete = entry.name.startsWith(cachePrefix) && entry.name.endsWith(cacheSuffix);
6401
- const partial = entry.name.startsWith(cachePrefix) && entry.name.endsWith(`${cacheSuffix}.partial`);
6402
- return complete || partial;
6403
- }).map((entry) => import_node_path7.default.join(product.cacheDir(), entry.name)).sort();
6404
- } catch {
6405
- }
6406
- }
6407
- return {
6408
- activeVersion,
6409
- pinnedVersion,
6410
- keepVersions: installed.filter((version) => keep.has(version)),
6411
- removeVersions: installed.filter((version) => !keep.has(version)),
6412
- removeCacheFiles
6413
- };
6414
6408
  }
6415
- function pruneLocalRetention(opts = {}) {
6416
- const plan = planLocalRetention(opts);
6417
- for (const version of plan.removeVersions) {
6418
- import_node_fs7.default.rmSync(product.runtimeDir(version), { recursive: true, force: true });
6419
- }
6420
- for (const cacheFile of plan.removeCacheFiles) {
6421
- import_node_fs7.default.rmSync(cacheFile, { force: true });
6422
- }
6423
- return plan;
6409
+ const stamp = stampHash.digest("hex");
6410
+ const cached3 = linkedModuleDigests.get(root);
6411
+ if (cached3?.stamp === stamp) return cached3.digest;
6412
+ const hash = (0, import_node_crypto3.createHash)("sha256");
6413
+ for (const file of files) {
6414
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(file).digest());
6415
+ hash.update(
6416
+ (0, import_node_crypto3.createHash)("sha256").update((0, import_node_fs7.readFileSync)(import_node_path7.default.join(root, file))).digest()
6417
+ );
6418
+ }
6419
+ const digest = hash.digest();
6420
+ linkedModuleDigests.set(root, { stamp, digest });
6421
+ return digest;
6422
+ }
6423
+ function compileTargets(input) {
6424
+ const manifest = input.files["Package.swift"];
6425
+ return manifest === void 0 ? [] : swiftPackagePartition(manifest);
6426
+ }
6427
+ function withNativeSourceGlue(input, glue) {
6428
+ const targets = compileTargets(input);
6429
+ if (targets.length > 1) {
6430
+ throw new Error("swift native modules need one SwiftPM target");
6424
6431
  }
6432
+ const targetPath = targets[0]?.path === "." ? "" : targets[0]?.path ?? "";
6425
6433
  return {
6426
- product,
6427
- resolveCdnOrigin,
6428
- resolveChannel,
6429
- resolvePin,
6430
- manifestUrl,
6431
- tarballUrl,
6432
- fetchManifest,
6433
- resolveVersion,
6434
- install,
6435
- updateToLatest,
6436
- checkUpToDate,
6437
- planLocalRetention,
6438
- pruneLocalRetention,
6439
- listInstalled: () => listInstalledRuntimes(product)
6434
+ ...input,
6435
+ files: {
6436
+ ...input.files,
6437
+ [import_node_path7.default.posix.join(targetPath, "OneNativeSource.generated.swift")]: glue
6438
+ },
6439
+ oneModule: true
6440
6440
  };
6441
6441
  }
6442
- async function installVerifiedTarball(tarball) {
6443
- const { url, digest, destDir, installedMarker, label } = tarball;
6444
- const downloadDir = import_node_fs7.default.mkdtempSync(import_node_path7.default.join(import_node_os2.default.tmpdir(), "runtime-delivery-download-"));
6445
- const archivePath = import_node_path7.default.join(downloadDir, "archive.tar.gz");
6446
- import_node_fs7.default.mkdirSync(import_node_path7.default.dirname(destDir), { recursive: true });
6447
- const tmpDir = import_node_fs7.default.mkdtempSync(
6448
- import_node_path7.default.join(import_node_path7.default.dirname(destDir), `.installing-${import_node_path7.default.basename(destDir)}-`)
6449
- );
6450
- try {
6451
- await downloadToFile(url, archivePath);
6452
- const actual = await digestFile(archivePath, digest.algorithm, digest.encoding);
6453
- if (actual !== digest.value) {
6454
- throw new Error(
6455
- `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
6456
- );
6457
- }
6458
- await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
6459
- if (!import_node_fs7.default.existsSync(import_node_path7.default.join(tmpDir, installedMarker))) {
6460
- throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
6461
- }
6462
- try {
6463
- import_node_fs7.default.renameSync(tmpDir, destDir);
6464
- } catch (err) {
6465
- if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
6466
- const aside = `${tmpDir}-replaced`;
6467
- try {
6468
- import_node_fs7.default.renameSync(destDir, aside);
6469
- } catch (moveErr) {
6470
- if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
6471
- }
6472
- try {
6473
- import_node_fs7.default.renameSync(tmpDir, destDir);
6474
- } catch (landErr) {
6475
- if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !import_node_fs7.default.existsSync(import_node_path7.default.join(destDir, installedMarker))) {
6476
- throw landErr;
6477
- }
6478
- } finally {
6479
- import_node_fs7.default.rmSync(aside, { recursive: true, force: true });
6442
+ var OPTIONAL_FRAMEWORK_DEPENDENCIES = {
6443
+ Accelerate: [],
6444
+ CryptoKit: [],
6445
+ Security: [],
6446
+ TikTokBusinessSDK: [],
6447
+ nSure: [],
6448
+ Statsig: [],
6449
+ DatadogCore: [],
6450
+ DatadogLogs: ["DatadogCore"],
6451
+ DatadogRUM: ["DatadogCore"],
6452
+ DatadogTrace: ["DatadogCore"]
6453
+ };
6454
+ var OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES));
6455
+ function swiftTargetDependencies(files, targets) {
6456
+ const names = /* @__PURE__ */ new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)]);
6457
+ const siblings = /* @__PURE__ */ new Map();
6458
+ for (const target of targets) {
6459
+ const prefix = target.path === "." ? "" : `${target.path}/`;
6460
+ const deps = /* @__PURE__ */ new Set();
6461
+ for (const [file, contents] of Object.entries(files)) {
6462
+ if (file === "Package.swift" || !file.startsWith(prefix)) continue;
6463
+ if (targets.some(
6464
+ (candidate) => candidate.name !== target.name && candidate.path !== "." && candidate.path.startsWith(prefix) && file.startsWith(`${candidate.path}/`)
6465
+ ))
6466
+ continue;
6467
+ for (const match of contents.matchAll(
6468
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm
6469
+ )) {
6470
+ if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1]);
6480
6471
  }
6481
6472
  }
6482
- } finally {
6483
- import_node_fs7.default.rmSync(tmpDir, { recursive: true, force: true });
6484
- import_node_fs7.default.rmSync(downloadDir, { recursive: true, force: true });
6473
+ siblings.set(target.name, [...deps].sort());
6485
6474
  }
6475
+ return siblings;
6486
6476
  }
6487
- function isErrnoCode(err, ...codes) {
6488
- return err instanceof Error && "code" in err && codes.includes(String(err.code));
6489
- }
6490
- async function downloadToFile(url, destPath) {
6491
- const res = await fetch(url);
6492
- if (!res.ok || !res.body) {
6493
- throw new Error(`download failed: ${res.status} ${res.statusText} (${url})`);
6477
+ var ONE_PRODUCT = '.product(name: "One", package: "sootsim-swift")';
6478
+ var SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")';
6479
+ var importsSpriteKit = (files) => Object.entries(files).some(
6480
+ ([file, contents]) => file.endsWith(".swift") && /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
6481
+ contents
6482
+ )
6483
+ );
6484
+ var FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"';
6485
+ var ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"';
6486
+ var MULTI_MANIFEST_VERSION = 10;
6487
+ function swiftArtifactHash(input, release, moduleRoot) {
6488
+ const hash = (0, import_node_crypto3.createHash)("sha256");
6489
+ hash.update(`swift-compile/v12
6490
+ ${release}
6491
+ `);
6492
+ if (input.oneModule) hash.update("one-module\n");
6493
+ hash.update(swiftModuleDigest(moduleRoot));
6494
+ for (const file of Object.keys(input.files).sort()) {
6495
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(file).digest());
6496
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(input.files[file]).digest());
6494
6497
  }
6495
- import_node_fs7.default.mkdirSync(import_node_path7.default.dirname(destPath), { recursive: true });
6496
- const tmp = `${destPath}.partial`;
6497
- try {
6498
- await (0, import_promises3.pipeline)(
6499
- import_node_stream.Readable.fromWeb(res.body),
6500
- import_node_fs7.default.createWriteStream(tmp)
6498
+ for (const base of Object.keys(input.resources ?? {}).sort()) {
6499
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(base).digest());
6500
+ hash.update(
6501
+ (0, import_node_crypto3.createHash)("sha256").update(input.resources?.[base] ?? "").digest()
6501
6502
  );
6502
- import_node_fs7.default.renameSync(tmp, destPath);
6503
- } catch (err) {
6504
- try {
6505
- import_node_fs7.default.unlinkSync(tmp);
6506
- } catch {
6507
- }
6508
- throw err;
6509
6503
  }
6510
- }
6511
- function digestFile(filePath, algorithm, encoding) {
6512
- return new Promise((resolve5, reject) => {
6513
- const hash = import_node_crypto2.default.createHash(algorithm);
6514
- const stream = import_node_fs7.default.createReadStream(filePath);
6515
- stream.on("data", (chunk) => hash.update(chunk));
6516
- stream.on("error", reject);
6517
- stream.on("end", () => resolve5(hash.digest(encoding)));
6518
- });
6519
- }
6520
- function extractTarball(tarPath, destDir, stripComponents) {
6521
- return new Promise((resolve5, reject) => {
6522
- const args = ["-xzf", tarPath, "-C", destDir];
6523
- if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
6524
- const child = (0, import_node_child_process2.spawn)("tar", args, {
6525
- stdio: ["ignore", "inherit", "inherit"]
6526
- });
6527
- child.on("error", reject);
6528
- child.on("exit", (code) => {
6529
- if (code === 0) resolve5();
6530
- else reject(new Error(`tar exited with code ${code}`));
6531
- });
6532
- });
6533
- }
6534
-
6535
- // src/swift-distribution.ts
6536
- init_home_paths();
6537
-
6538
- // src/swift-compile.ts
6539
- var import_node_child_process4 = require("node:child_process");
6540
- var import_node_crypto4 = require("node:crypto");
6541
- var import_node_fs9 = require("node:fs");
6542
- var import_node_os3 = __toESM(require("node:os"), 1);
6543
- var import_node_path9 = __toESM(require("node:path"), 1);
6544
- var import_node_util2 = require("node:util");
6545
-
6546
- // src/swift-distribution-contract.ts
6547
- init_is_record();
6548
- var SWIFT_DISTRIBUTION_MANIFEST = "distribution.json";
6549
- var SWIFT_DISTRIBUTION_HOSTS = [
6550
- "darwin-arm64",
6551
- "linux-x64",
6552
- "linux-arm64"
6553
- ];
6554
- function swiftDistributionHost(platform, arch) {
6555
- const host2 = `${platform}-${arch}`;
6556
- return SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === host2) ?? null;
6557
- }
6558
- var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
6559
- function parseSwiftDistributionManifest(value) {
6560
- if (!isRecord(value) || typeof value.id !== "string" || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || !isStrings(value.modules) || !isStrings(value.objects) || !isStrings(value.link) || !isRecord(value.files) || !Object.values(value.files).every((sha) => typeof sha === "string") || typeof value.host !== "string" || !isStrings(value.plugins)) {
6561
- throw new Error(`invalid Swift distribution ${SWIFT_DISTRIBUTION_MANIFEST}`);
6504
+ for (const name2 of Object.keys(input.images ?? {}).sort()) {
6505
+ const image = input.images?.[name2];
6506
+ if (!image) continue;
6507
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(name2).digest());
6508
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(image.file).digest());
6509
+ hash.update((0, import_node_crypto3.createHash)("sha256").update(image.data).digest());
6562
6510
  }
6563
- const host2 = SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === value.host);
6564
- if (!host2) throw new Error(`Swift distribution names an unknown host ${value.host}`);
6565
- return {
6566
- id: value.id,
6567
- release: value.release,
6568
- wasmSdkId: value.wasmSdkId,
6569
- wasmSdkUrl: value.wasmSdkUrl,
6570
- wasmSdkChecksum: value.wasmSdkChecksum,
6571
- modules: value.modules,
6572
- objects: value.objects,
6573
- link: value.link,
6574
- files: Object.fromEntries(
6575
- Object.entries(value.files).map(([file, sha]) => [file, String(sha)])
6576
- ),
6577
- host: host2,
6578
- plugins: value.plugins
6579
- };
6580
- }
6581
- function parseSwiftDistributionLock(value) {
6582
- if (!isRecord(value) || typeof value.id !== "string" || !/^[a-f0-9]{16}$/.test(value.id) || typeof value.release !== "string" || typeof value.wasmSdkId !== "string" || typeof value.wasmSdkUrl !== "string" || typeof value.wasmSdkChecksum !== "string" || typeof value.source !== "string" || !isRecord(value.hosts)) {
6583
- throw new Error("invalid Swift distribution lock");
6511
+ const targets = compileTargets(input);
6512
+ if (targets.length > 0) {
6513
+ hash.update(`swift-multi/v${MULTI_MANIFEST_VERSION}
6514
+ `);
6515
+ hash.update(
6516
+ JSON.stringify({
6517
+ targets,
6518
+ siblings: [...swiftTargetDependencies(input.files, targets)].sort(
6519
+ (a, b) => String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0
6520
+ )
6521
+ })
6522
+ );
6584
6523
  }
6585
- const hosts = value.hosts;
6586
- const entry = (host2) => {
6587
- const item = hosts[host2];
6588
- if (!isRecord(item) || typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256) || typeof item.size !== "number") {
6589
- throw new Error(`invalid Swift distribution lock entry for ${host2}`);
6590
- }
6591
- return { sha256: item.sha256, size: item.size };
6524
+ return hash.digest("hex");
6525
+ }
6526
+ function emitSwiftPackageManifest(args) {
6527
+ const { targets, siblings, moduleRoot, oneModule, spriteKit, distribution } = args;
6528
+ const reachedFrameworks = new Set(
6529
+ [...siblings.values()].flat().filter(
6530
+ (name2) => OPTIONAL_FRAMEWORKS.has(name2) && !targets.some((target) => target.name === name2)
6531
+ ).flatMap((name2) => [name2, ...OPTIONAL_FRAMEWORK_DEPENDENCIES[name2] ?? []])
6532
+ );
6533
+ const distributionObjects = distribution?.objects.filter(
6534
+ (object) => [...OPTIONAL_FRAMEWORKS].every(
6535
+ (name2) => !object.startsWith(`lib/${name2}-`) || reachedFrameworks.has(name2)
6536
+ )
6537
+ );
6538
+ const executable = targets.find((target) => target.executable);
6539
+ if (!executable) throw new Error("swift-compile: no executable target to emit");
6540
+ const stanza = (target) => {
6541
+ const isolation = target.mainActorIsolation ? " .defaultIsolation(MainActor.self)," : "";
6542
+ const imports = distribution ? `, "-I", ${JSON.stringify(import_node_path7.default.join(moduleRoot, "modules"))}` : "";
6543
+ const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${FOUNDATION_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ""}${imports}])]`;
6544
+ const deps = [
6545
+ ...distribution ? [] : [
6546
+ '.product(name: "SwiftUI", package: "sootsim-swift")',
6547
+ ...oneModule ? [ONE_PRODUCT] : [],
6548
+ ...spriteKit ? [SPRITEKIT_PRODUCT] : []
6549
+ ],
6550
+ ...(siblings.get(target.name) ?? []).flatMap(
6551
+ (dependency) => OPTIONAL_FRAMEWORKS.has(dependency) && !targets.some((candidate) => candidate.name === dependency) ? distribution ? [] : [`.product(name: "${dependency}", package: "sootsim-swift")`] : [`"${dependency}"`]
6552
+ )
6553
+ ].join(", ");
6554
+ const library = distribution ? [
6555
+ ...(distributionObjects ?? []).map((object) => import_node_path7.default.join(moduleRoot, object)),
6556
+ ...distribution.link
6557
+ ].map((flag) => `, ${JSON.stringify(flag)}`).join("") : "";
6558
+ const kind = target.executable ? ".executableTarget" : ".target";
6559
+ const link = target.executable ? `,
6560
+ linkerSettings: [
6561
+ .unsafeFlags([
6562
+ "-Xclang-linker", "-mexec-model=reactor",
6563
+ "-Xlinker", "--export-if-defined=__main_argc_argv"${library},
6564
+ ]),
6565
+ .unsafeFlags(["-Xlinker", "--strip-all"], .when(configuration: .release)),
6566
+ ]` : "";
6567
+ return [
6568
+ ` ${kind}(`,
6569
+ ` name: "${target.name}",`,
6570
+ ` dependencies: [${deps}],`,
6571
+ ` path: "${target.path}",`,
6572
+ ` ${swiftSettings}${link}`,
6573
+ ` ),`
6574
+ ].join("\n");
6592
6575
  };
6593
- return {
6594
- id: value.id,
6595
- release: value.release,
6596
- wasmSdkId: value.wasmSdkId,
6597
- wasmSdkUrl: value.wasmSdkUrl,
6598
- wasmSdkChecksum: value.wasmSdkChecksum,
6599
- source: value.source,
6600
- hosts: {
6601
- "darwin-arm64": entry("darwin-arm64"),
6602
- "linux-x64": entry("linux-x64"),
6603
- "linux-arm64": entry("linux-arm64")
6576
+ return [
6577
+ "// swift-tools-version: 6.2",
6578
+ "import PackageDescription",
6579
+ "",
6580
+ "// generated by swift-compile from the project package partition.",
6581
+ "let package = Package(",
6582
+ ' name: "app",',
6583
+ ` products: [.executable(name: "${executable.name}", targets: ["${executable.name}"])],`,
6584
+ ` dependencies: [${distribution ? "" : `.package(path: "${moduleRoot}")`}],`,
6585
+ " targets: [",
6586
+ ...targets.map(stanza),
6587
+ " ]",
6588
+ ")",
6589
+ ""
6590
+ ].join("\n");
6591
+ }
6592
+ function syncSwiftTree(base, files) {
6593
+ (0, import_node_fs7.mkdirSync)(base, { recursive: true });
6594
+ const walk = (dir) => {
6595
+ for (const entry of (0, import_node_fs7.readdirSync)(dir, { withFileTypes: true })) {
6596
+ const full = import_node_path7.default.join(dir, entry.name);
6597
+ if (dir === base && entry.name === ".build") continue;
6598
+ if (entry.isDirectory()) walk(full);
6599
+ else if (!files.has(full)) (0, import_node_fs7.rmSync)(full, { force: true });
6604
6600
  }
6605
6601
  };
6606
- }
6607
- function swiftDistributionKey(id, host2) {
6608
- return `${id}/${host2}.tar.gz`;
6609
- }
6610
-
6611
- // src/swift-icu.ts
6612
- var import_node_child_process3 = require("node:child_process");
6613
- var import_node_crypto3 = require("node:crypto");
6614
- var import_node_fs8 = require("node:fs");
6615
- var import_node_path8 = __toESM(require("node:path"), 1);
6616
- var import_node_util = require("node:util");
6617
- var import_node_zlib = require("node:zlib");
6618
- var run = (0, import_node_util.promisify)(import_node_child_process3.execFile);
6619
- var deflate = (0, import_node_util.promisify)(import_node_zlib.gzip);
6620
- var ARCHIVE = "wasi/lib_FoundationICU.a";
6621
- var MEMBER = "icu_packaged_data.cpp.obj";
6622
- var raw = /* @__PURE__ */ new Map();
6623
- var assets = /* @__PURE__ */ new Map();
6624
- function memo(cache, key, load2) {
6625
- let pending = cache.get(key);
6626
- if (!pending) {
6627
- pending = load2();
6628
- pending.catch(() => cache.delete(key));
6629
- cache.set(key, pending);
6602
+ walk(base);
6603
+ for (const [full, contents] of files) {
6604
+ if ((0, import_node_fs7.existsSync)(full) && (0, import_node_fs7.readFileSync)(full, "utf8") === contents) continue;
6605
+ (0, import_node_fs7.mkdirSync)(import_node_path7.default.dirname(full), { recursive: true });
6606
+ (0, import_node_fs7.writeFileSync)(full, contents, "utf8");
6630
6607
  }
6631
- return pending;
6632
- }
6633
- function swiftIcuData(toolchainBin, sdk) {
6634
- return memo(raw, `${toolchainBin}\0${sdk}`, () => load(toolchainBin, sdk));
6635
- }
6636
- function swiftIcuAsset(toolchainBin, sdk) {
6637
- return memo(assets, `${toolchainBin}\0${sdk}`, async () => {
6638
- const zipped = await deflate(await swiftIcuData(toolchainBin, sdk));
6639
- return { sha256: (0, import_node_crypto3.createHash)("sha256").update(zipped).digest("hex"), gzip: zipped };
6640
- });
6641
6608
  }
6642
- async function load(toolchainBin, sdk) {
6643
- const { stdout } = await run(import_node_path8.default.join(toolchainBin, "swift"), [
6644
- "sdk",
6645
- "configure",
6646
- "--show-configuration",
6647
- sdk,
6648
- "wasm32-unknown-wasip1"
6649
- ]);
6650
- const resources = /^swiftStaticResourcesPath: (.+)$/m.exec(stdout)?.[1]?.trim();
6651
- if (!resources) throw new Error(`swift-icu: ${sdk} names no static resources`);
6652
- return Buffer.from(
6653
- icuSegment(archiveMember((0, import_node_fs8.readFileSync)(import_node_path8.default.join(resources, ARCHIVE)), MEMBER))
6654
- );
6609
+ var DIRECTIVE = /^[ \t]*#(?:if|elseif)\b/;
6610
+ var OS_IOS = /\bos\(\s*iOS\s*\)/g;
6611
+ var OBJC_ATTRIBUTE = /^@(?:objcMembers\b|objc\b(?:(\s*)\(([^()]*)\))?|IBAction\b)/;
6612
+ var SELECTOR = /^#selector\b/;
6613
+ var TYPE_AFTER_ATTRIBUTE = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/|@\w+(?:\([^()]*\))?|\b(?:public|open|final|internal|fileprivate|private|package|nonisolated|indirect)\b)*\b(?:class(?!\s+(?:func|var|let|subscript)\b)|struct|enum|protocol|extension|actor)\b/;
6614
+ var DELEGATE_CLASS = /^class\s+[A-Za-z_]\w*\s*(?:<[^>{]*>)?\s*:[^{]*\b(?:UIApplicationDelegate|UISceneDelegate|UIWindowSceneDelegate)\b[^{]*\{/;
6615
+ var REUSABLE_INIT = /^override(?=\s+init\s*\(\s*(?:style\s*:[^,)]*,\s*reuseIdentifier|reuseIdentifier)\s*:)/;
6616
+ var REUSABLE_VIEW_BASES = [
6617
+ "UICollectionReusableView",
6618
+ "UICollectionViewCell",
6619
+ "UICollectionViewListCell"
6620
+ ];
6621
+ var CLASS_BASE = /^class\s+([A-Za-z_]\w*)\s*(?:<[^>{]*>)?\s*:\s*([A-Za-z_][\w.]*)[^{]*\{/;
6622
+ var FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/;
6623
+ var APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/;
6624
+ var EXTENSION_DECL = /^extension\s+([A-Za-z_][\w.]*)/;
6625
+ var CLASS_DECL = /^class\s+(?!(?:func|var|let|subscript)\b)([A-Za-z_]\w*)/;
6626
+ var MODIFIERS = /(?:^|\s)(public|open|internal|fileprivate|private|final|nonisolated|@MainActor)(?=\s)/g;
6627
+ var OVERRIDE_FUNC = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+func\s+([A-Za-z_]\w*)\s*(<[^>{}]*>)?\s*\(/;
6628
+ var OVERRIDE_VAR = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+var\s+([A-Za-z_]\w*)\s*:\s*([^{=]+?)\s*\{/;
6629
+ function splitTopLevel(text) {
6630
+ const parts = [];
6631
+ let depth = 0;
6632
+ let start = 0;
6633
+ for (let i = 0; i < text.length; i++) {
6634
+ const char = text[i];
6635
+ if (char === "(" || char === "[" || char === "<") depth++;
6636
+ else if (char === ")" || char === "]" || char === ">" && text[i - 1] !== "-")
6637
+ depth--;
6638
+ else if (char === "," && depth === 0) {
6639
+ parts.push(text.slice(start, i));
6640
+ start = i + 1;
6641
+ }
6642
+ }
6643
+ parts.push(text.slice(start));
6644
+ return parts.map((part) => part.trim()).filter((part) => part !== "");
6655
6645
  }
6656
- function archiveMember(archive, name2) {
6657
- if (archive.toString("latin1", 0, 8) !== "!<arch>\n")
6658
- throw new Error("swift-icu: not an ar archive");
6659
- let names = "";
6660
- for (let at = 8; at + 60 <= archive.length; ) {
6661
- const raw2 = archive.toString("latin1", at, at + 16).trimEnd();
6662
- const size = Number(archive.toString("latin1", at + 48, at + 58).trim());
6663
- const body = archive.subarray(at + 60, at + 60 + size);
6664
- if (raw2 === "//") names = body.toString("latin1");
6665
- const member = /^\/\d+$/.test(raw2) ? names.slice(Number(raw2.slice(1)), names.indexOf("/\n", Number(raw2.slice(1)))) : raw2.replace(/\/$/, "");
6666
- if (member === name2) return body;
6667
- at += 60 + size + size % 2;
6646
+ function forwardedArguments(parameters) {
6647
+ const args = [];
6648
+ for (const parameter of splitTopLevel(parameters)) {
6649
+ const match = /^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([\s\S]*)$/.exec(parameter);
6650
+ if (!match || match[3].includes("...")) return null;
6651
+ const label = match[1] ?? match[2];
6652
+ const value = (/^(?:@\w+\s+)*inout\b/.test(match[3]) ? "&" : "") + match[2];
6653
+ args.push(label === "_" ? value : `${label}: ${value}`);
6668
6654
  }
6669
- throw new Error(`swift-icu: ${name2} is not in the sdk's icu archive`);
6655
+ return args.join(", ");
6670
6656
  }
6671
- function icuSegment(object) {
6672
- let at = 8;
6673
- const leb = () => {
6674
- let result = 0;
6675
- let shift = 0;
6676
- let byte;
6677
- do {
6678
- byte = object[at++];
6679
- result += (byte & 127) * 2 ** shift;
6680
- shift += 7;
6681
- } while (byte & 128);
6682
- return result;
6657
+ function liftExtensionOverrides(source) {
6658
+ const { tokens } = swiftCodeScan(source);
6659
+ const stack = [];
6660
+ let pending = null;
6661
+ const classes = /* @__PURE__ */ new Map();
6662
+ let declaredBase = null;
6663
+ let declaredObjCMembers = false;
6664
+ const lifted = [];
6665
+ const closing = (open) => {
6666
+ let depth = 0;
6667
+ for (const at of tokens) {
6668
+ if (at < open) continue;
6669
+ if (source[at] === "{") depth++;
6670
+ else if (source[at] === "}" && --depth === 0) return at + 1;
6671
+ }
6672
+ return source.length;
6683
6673
  };
6684
- const found = [];
6685
- while (at < object.length) {
6686
- const id = object[at++];
6687
- const size = leb();
6688
- const end = at + size;
6689
- if (id === 11) {
6690
- for (let count = leb(); count > 0; count--) {
6691
- if (leb() !== 0) throw new Error("swift-icu: unexpected data segment kind");
6692
- at++;
6693
- leb();
6694
- at++;
6695
- const length = leb();
6696
- const bytes = object.subarray(at, at + length);
6697
- if (bytes[2] === 218 && bytes[3] === 39) found.push(bytes);
6698
- at += length;
6699
- }
6674
+ for (const at of tokens) {
6675
+ const rest = source.slice(at, at + 600);
6676
+ if (rest.startsWith("{")) {
6677
+ const frame = pending ?? { kind: "other", name: "" };
6678
+ if (frame.kind === "class" && !classes.has(frame.name))
6679
+ classes.set(frame.name, {
6680
+ brace: at,
6681
+ base: declaredBase,
6682
+ objcMembers: declaredObjCMembers
6683
+ });
6684
+ stack.push(frame);
6685
+ pending = null;
6686
+ continue;
6700
6687
  }
6701
- at = end;
6702
- }
6703
- if (found.length !== 1)
6704
- throw new Error(`swift-icu: expected one icu data segment, found ${found.length}`);
6705
- return found[0];
6706
- }
6707
-
6708
- // src/swift-package.ts
6709
- function swiftManifestTargets(manifest) {
6710
- const code = manifest.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
6711
- const targets = [];
6712
- const pattern = /\.(executableTarget|target)\s*\(/g;
6713
- let match;
6714
- while ((match = pattern.exec(code)) !== null) {
6715
- const executable = match[1] === "executableTarget";
6716
- let depth = 1;
6717
- const start = pattern.lastIndex;
6718
- let i = start;
6719
- let inString = false;
6720
- let escaped = false;
6721
- let flat = "";
6722
- while (i < code.length && depth > 0) {
6723
- const ch = code[i];
6724
- if (inString) {
6725
- if (escaped) escaped = false;
6726
- else if (ch === "\\") escaped = true;
6727
- else if (ch === '"') inString = false;
6728
- if (depth === 1) flat += ch;
6729
- } else if (ch === '"') {
6730
- inString = true;
6731
- if (depth === 1) flat += ch;
6732
- } else if (ch === "(") {
6733
- depth++;
6734
- if (depth === 1) flat += ch;
6735
- } else if (ch === ")") {
6736
- depth--;
6737
- if (depth >= 1) flat += ch;
6738
- } else if (depth === 1) {
6739
- flat += ch;
6688
+ if (rest.startsWith("}")) {
6689
+ stack.pop();
6690
+ continue;
6691
+ }
6692
+ const declared = CLASS_DECL.exec(rest);
6693
+ if (declared) {
6694
+ pending = { kind: "class", name: declared[1] };
6695
+ declaredBase = CLASS_BASE.exec(rest)?.[2]?.split(".").pop() ?? null;
6696
+ const lines = source.lastIndexOf("\n", source.lastIndexOf("\n", at - 1) - 1) + 1;
6697
+ declaredObjCMembers = /@objcMembers\b/.test(source.slice(lines, at));
6698
+ continue;
6699
+ }
6700
+ const extended = EXTENSION_DECL.exec(rest);
6701
+ if (extended) {
6702
+ pending = { kind: "extension", name: extended[1].split(".").pop() };
6703
+ continue;
6704
+ }
6705
+ const top = stack.at(-1);
6706
+ if (!rest.startsWith("override") || top?.kind !== "extension" || pending) continue;
6707
+ const line = source.slice(source.lastIndexOf("\n", at - 1) + 1, at);
6708
+ const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim());
6709
+ const func = OVERRIDE_FUNC.exec(rest);
6710
+ if (func) {
6711
+ const name2 = func[2];
6712
+ const open = at + func[0].length - 1;
6713
+ let depth = 0;
6714
+ let close = open;
6715
+ for (; close < source.length; close++) {
6716
+ if (source[close] === "(") depth++;
6717
+ else if (source[close] === ")" && --depth === 0) break;
6740
6718
  }
6741
- i++;
6719
+ const body = tokens.find((token) => token > close && source[token] === "{");
6720
+ if (body === void 0) continue;
6721
+ const clause = source.slice(close + 1, body).trim();
6722
+ const args = forwardedArguments(source.slice(open + 1, close));
6723
+ if (args === null) continue;
6724
+ const call = (clause.includes("->") ? "return " : "") + (/\b(?:throws|rethrows)\b/.test(clause) ? "try " : "") + (/\basync\b/.test(clause) ? "await " : "") + `__peach_ext_${name2}(${args})`;
6725
+ const signature = `func ${name2}${func[3] ?? ""}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ""}`;
6726
+ lifted.push({
6727
+ type: top.name,
6728
+ member: name2,
6729
+ stub: `${[...modifiers, "override"].join(" ")} ${signature} { ${call} };`,
6730
+ edits: [
6731
+ [at, "override".length, " ".repeat("override".length)],
6732
+ [
6733
+ at + rest.indexOf(
6734
+ name2,
6735
+ rest.indexOf("func", "override".length + func[1].length) + 4
6736
+ ),
6737
+ 0,
6738
+ "__peach_ext_"
6739
+ ]
6740
+ ]
6741
+ });
6742
+ continue;
6743
+ }
6744
+ const property = OVERRIDE_VAR.exec(rest);
6745
+ if (property) {
6746
+ const open = at + property[0].length - 1;
6747
+ if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue;
6748
+ const name2 = property[2];
6749
+ lifted.push({
6750
+ type: top.name,
6751
+ member: name2,
6752
+ stub: `${[...modifiers, "override"].join(" ")} var ${name2}: ${property[3].trim()} { __peach_ext_${name2} };`,
6753
+ edits: [
6754
+ [at, "override".length, " ".repeat("override".length)],
6755
+ [at + rest.indexOf(name2, rest.indexOf("var")), 0, "__peach_ext_"]
6756
+ ]
6757
+ });
6742
6758
  }
6743
- const name2 = /\bname\s*:\s*"([^"]+)"/.exec(flat)?.[1];
6744
- if (!name2) continue;
6745
- const rawPath = /\bpath\s*:\s*"([^"]*)"/.exec(flat)?.[1];
6746
- const targetPath = rawPath == null || rawPath === "" ? `Sources/${name2}` : rawPath.replace(/^\.\//, "").replace(/\/+$/, "");
6747
- const call = code.slice(start, i);
6748
- const languageMode = Number(
6749
- /\.swiftLanguageMode\(\s*\.v(\d+)\s*\)/.exec(call)?.[1] ?? "5"
6750
- );
6751
- const mainActorIsolation = /\.defaultIsolation\(\s*MainActor\.self\s*\)/.test(call);
6752
- const resources = /\bresources\s*:/.test(flat);
6753
- targets.push({
6754
- name: name2,
6755
- path: targetPath,
6756
- executable,
6757
- languageMode,
6758
- mainActorIsolation,
6759
- resources
6760
- });
6761
6759
  }
6762
- return targets;
6763
- }
6764
- function swiftPackagePartition(manifest) {
6765
- const targets = swiftManifestTargets(manifest);
6766
- return targets.length === 1 && targets[0].executable && targets[0].path === "." ? [] : targets;
6760
+ const overridesObjC = (type, member) => {
6761
+ let base = classes.get(type)?.base ?? null;
6762
+ while (base !== null) {
6763
+ if (APPLE_CLASS.test(base)) return true;
6764
+ const declaredClass = classes.get(base);
6765
+ if (!declaredClass) return false;
6766
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace));
6767
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body);
6768
+ if (found) {
6769
+ const line = body.slice(body.lastIndexOf("\n", found.index) + 1, found.index);
6770
+ return declaredClass.objcMembers || /@objc\b/.test(line);
6771
+ }
6772
+ base = declaredClass.base;
6773
+ }
6774
+ return false;
6775
+ };
6776
+ const edits = [];
6777
+ const stubs = /* @__PURE__ */ new Map();
6778
+ for (const entry of lifted) {
6779
+ const brace = classes.get(entry.type)?.brace;
6780
+ if (brace === void 0 || !overridesObjC(entry.type, entry.member)) continue;
6781
+ edits.push(...entry.edits);
6782
+ stubs.set(brace, [...stubs.get(brace) ?? [], entry.stub]);
6783
+ }
6784
+ for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(" ")}`]);
6785
+ let out = source;
6786
+ for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
6787
+ out = out.slice(0, at) + insert + out.slice(at + remove);
6788
+ return out;
6767
6789
  }
6768
-
6769
- // src/swift-compile.ts
6770
- var run2 = (0, import_node_util2.promisify)(import_node_child_process4.execFile);
6771
- var WASM_TRIPLE = "wasm32-unknown-wasip1";
6772
- var cores = import_node_os3.default.availableParallelism();
6773
- var BUILD_ENV = { ...process.env, BINARYEN_CORES: String(Math.min(4, cores)) };
6774
- var BUILD_JOBS = String(Math.max(1, Math.floor(cores / 2)));
6775
- function swiftDistributionAt(root) {
6776
- const file = import_node_path9.default.join(root, SWIFT_DISTRIBUTION_MANIFEST);
6777
- if (!(0, import_node_fs9.existsSync)(file)) return null;
6778
- return parseSwiftDistributionManifest(JSON.parse((0, import_node_fs9.readFileSync)(file, "utf8")));
6790
+ function swiftSourceAsIOS(original) {
6791
+ const source = liftExtensionOverrides(original);
6792
+ const { lineStarts, tokens } = swiftCodeScan(source);
6793
+ let offset = 0;
6794
+ const conditioned = source.split("\n").map((line) => {
6795
+ const start = offset;
6796
+ offset += line.length + 1;
6797
+ if (!lineStarts.has(start) || !DIRECTIVE.test(line)) return line;
6798
+ return line.replace(OS_IOS, (match) => "true".padEnd(match.length));
6799
+ }).join("\n");
6800
+ let out = "";
6801
+ let copied = 0;
6802
+ const reusableViews = new Set(REUSABLE_VIEW_BASES);
6803
+ const reusableBodies = [];
6804
+ let depth = 0;
6805
+ let opensReusableBody = false;
6806
+ for (const at of tokens) {
6807
+ const rest = conditioned.slice(at, at + 400);
6808
+ if (rest.startsWith("{")) {
6809
+ depth++;
6810
+ if (opensReusableBody) reusableBodies.push(depth);
6811
+ opensReusableBody = false;
6812
+ continue;
6813
+ }
6814
+ if (rest.startsWith("}")) {
6815
+ if (reusableBodies.at(-1) === depth) reusableBodies.pop();
6816
+ depth--;
6817
+ continue;
6818
+ }
6819
+ if (rest.startsWith("override")) {
6820
+ if (REUSABLE_INIT.test(rest) || reusableBodies.at(-1) === depth && FRAME_INIT.test(rest)) {
6821
+ out += `${conditioned.slice(copied, at)}required`;
6822
+ copied = at + "override".length;
6823
+ }
6824
+ continue;
6825
+ }
6826
+ const imported = /^import\s+CoreImage\.CIFilterBuiltins\b/.exec(rest);
6827
+ if (imported) {
6828
+ out += conditioned.slice(copied, at) + "import CoreImage".padEnd(imported[0].length);
6829
+ copied = at + imported[0].length;
6830
+ continue;
6831
+ }
6832
+ if (/^NSClassFromString\b/.test(rest)) {
6833
+ out += conditioned.slice(copied, at) + "_peachClassFromString";
6834
+ copied = at + "NSClassFromString".length;
6835
+ continue;
6836
+ }
6837
+ if (rest.startsWith("class")) {
6838
+ const declared = CLASS_BASE.exec(rest);
6839
+ if (declared && reusableViews.has(declared[2].split(".").pop())) {
6840
+ reusableViews.add(declared[1]);
6841
+ opensReusableBody = true;
6842
+ }
6843
+ const modifiers = conditioned.slice(conditioned.lastIndexOf("\n", at - 1) + 1, at);
6844
+ if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
6845
+ out += `${conditioned.slice(copied, at)}final `;
6846
+ copied = at;
6847
+ }
6848
+ continue;
6849
+ }
6850
+ const selector = SELECTOR.exec(rest);
6851
+ const match = selector ?? OBJC_ATTRIBUTE.exec(rest);
6852
+ if (!match) continue;
6853
+ let replacement = "@ObjC";
6854
+ if (selector) replacement = "#Selector";
6855
+ else if (match[0] === "@objcMembers") replacement = "@ObjCMembers";
6856
+ else if (match[0] === "@IBAction") replacement = "@ObjC".padEnd(match[0].length);
6857
+ else if (TYPE_AFTER_ATTRIBUTE.test(rest.slice(match[0].length)))
6858
+ replacement = " ".repeat(match[0].length);
6859
+ else if (match[2] !== void 0)
6860
+ replacement = `@ObjC${match[1]}("${match[2].trim()}")`;
6861
+ out += conditioned.slice(copied, at) + replacement;
6862
+ copied = at + match[0].length;
6863
+ }
6864
+ return out + conditioned.slice(copied);
6779
6865
  }
6780
- function swiftModuleSdk(root) {
6781
- const pin = swiftDistributionAt(root) ?? JSON.parse((0, import_node_fs9.readFileSync)(import_node_path9.default.join(root, "toolchain.json"), "utf8"));
6782
- if (!pin || typeof pin !== "object" || typeof Reflect.get(pin, "wasmSdkId") !== "string" || typeof Reflect.get(pin, "wasmSdkUrl") !== "string" || typeof Reflect.get(pin, "wasmSdkChecksum") !== "string")
6783
- throw new Error(`${root} pins no wasm SDK id, url and checksum`);
6784
- return {
6785
- wasmSdkId: String(Reflect.get(pin, "wasmSdkId")),
6786
- wasmSdkUrl: String(Reflect.get(pin, "wasmSdkUrl")),
6787
- wasmSdkChecksum: String(Reflect.get(pin, "wasmSdkChecksum"))
6866
+ function swiftCodeScan(source) {
6867
+ const starts = /* @__PURE__ */ new Set();
6868
+ const tokens = [];
6869
+ const stack = [{ kind: "code", parens: 0 }];
6870
+ const hashesAt = (at) => {
6871
+ let end = at;
6872
+ while (source[end] === "#") end++;
6873
+ return end - at;
6788
6874
  };
6789
- }
6790
- function swiftModuleInputFiles(root) {
6791
- if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST];
6792
- const files = [
6793
- "Package.swift",
6794
- "scripts/contrast-app-Package.swift",
6795
- "toolchain.json"
6796
- ];
6797
- const walk = (dir) => {
6798
- for (const entry of (0, import_node_fs9.readdirSync)(import_node_path9.default.join(root, dir), { withFileTypes: true })) {
6799
- const relative2 = `${dir}/${entry.name}`;
6800
- if (entry.isDirectory()) walk(relative2);
6801
- else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative2);
6875
+ const closes = (at, hashes) => source.startsWith("#".repeat(hashes), at);
6876
+ let i = 0;
6877
+ while (i < source.length) {
6878
+ const top = stack[stack.length - 1];
6879
+ if ((i === 0 || source[i - 1] === "\n") && top.kind === "code" && stack.length === 1)
6880
+ starts.add(i);
6881
+ const char = source[i];
6882
+ if (top.kind === "block") {
6883
+ if (source.startsWith("/*", i)) {
6884
+ top.depth++;
6885
+ i += 2;
6886
+ } else if (source.startsWith("*/", i)) {
6887
+ if (--top.depth === 0) stack.pop();
6888
+ i += 2;
6889
+ } else i++;
6890
+ continue;
6891
+ }
6892
+ if (top.kind === "string") {
6893
+ if (char === "\\" && closes(i + 1, top.hashes)) {
6894
+ const after = i + 1 + top.hashes;
6895
+ if (source[after] === "(") {
6896
+ stack.push({ kind: "code", parens: 0 });
6897
+ i = after + 1;
6898
+ } else i = after + 1;
6899
+ continue;
6900
+ }
6901
+ const quote = top.multiline ? '"""' : '"';
6902
+ if (source.startsWith(quote, i) && closes(i + quote.length, top.hashes)) {
6903
+ stack.pop();
6904
+ i += quote.length + top.hashes;
6905
+ } else i++;
6906
+ continue;
6907
+ }
6908
+ if (top.kind === "regex") {
6909
+ if (char === "/" && closes(i + 1, top.hashes)) {
6910
+ stack.pop();
6911
+ i += 1 + top.hashes;
6912
+ } else i++;
6913
+ continue;
6914
+ }
6915
+ if (source.startsWith("//", i)) {
6916
+ const end = source.indexOf("\n", i);
6917
+ i = end === -1 ? source.length : end;
6918
+ } else if (source.startsWith("/*", i)) {
6919
+ stack.push({ kind: "block", depth: 1 });
6920
+ i += 2;
6921
+ } else if (char === '"' || char === "#") {
6922
+ const hashes = hashesAt(i);
6923
+ const at = i + hashes;
6924
+ if (source.startsWith('"""', at)) {
6925
+ stack.push({ kind: "string", hashes, multiline: true });
6926
+ i = at + 3;
6927
+ } else if (source[at] === '"') {
6928
+ stack.push({ kind: "string", hashes, multiline: false });
6929
+ i = at + 1;
6930
+ } else if (hashes > 0 && source[at] === "/") {
6931
+ stack.push({ kind: "regex", hashes });
6932
+ i = at + 1;
6933
+ } else {
6934
+ if (hashes > 0) tokens.push(at - 1);
6935
+ i = Math.max(at, i + 1);
6936
+ }
6937
+ } else if (char === "{" || char === "}") {
6938
+ tokens.push(i);
6939
+ i++;
6940
+ } else if (char === "(") {
6941
+ top.parens++;
6942
+ i++;
6943
+ } else if (char === ")") {
6944
+ if (top.parens === 0 && stack.length > 1) stack.pop();
6945
+ else top.parens--;
6946
+ i++;
6947
+ } else {
6948
+ 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;
6949
+ if (keyword && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + keyword.length] ?? "")) {
6950
+ tokens.push(i);
6951
+ i += keyword.length;
6952
+ } else {
6953
+ if (char === "@") tokens.push(i);
6954
+ i++;
6955
+ }
6802
6956
  }
6803
- };
6804
- walk("Sources");
6805
- return files.sort();
6957
+ }
6958
+ return { lineStarts: starts, tokens };
6806
6959
  }
6807
- async function ensureMacroPlugins(moduleRoot, toolchainBin) {
6960
+ var compiledSource = (file, contents) => file.endsWith(".swift") ? swiftSourceAsIOS(contents) : contents;
6961
+ function writeSwiftProject(layout, input, moduleRoot) {
6808
6962
  const distribution = swiftDistributionAt(moduleRoot);
6809
- if (distribution)
6810
- return distribution.plugins.map((plugin) => import_node_path9.default.join(moduleRoot, plugin));
6811
- const dir = import_node_path9.default.join(moduleRoot, ".build/host/RnxPreviewMacros");
6812
- const ext = process.platform === "darwin" ? "dylib" : "so";
6813
- const plugins = [
6814
- {
6815
- library: import_node_path9.default.join(dir, `libRnxPreviewMacros.${ext}`),
6816
- source: import_node_path9.default.join(moduleRoot, "Sources/RnxPreviewMacros/PreviewMacro.swift")
6817
- },
6963
+ const targets = distribution && compileTargets(input).length === 0 ? [
6818
6964
  {
6819
- library: import_node_path9.default.join(dir, `libFoundationMacros.${ext}`),
6820
- source: import_node_path9.default.join(moduleRoot, "Sources/FoundationMacros/PredicateMacro.swift")
6965
+ name: "App",
6966
+ path: import_node_path7.default.relative(layout.root, layout.sources),
6967
+ executable: true,
6968
+ languageMode: 5,
6969
+ mainActorIsolation: false,
6970
+ resources: false
6821
6971
  }
6822
- ];
6823
- const stale = plugins.some(
6824
- ({ library, source }) => !(0, import_node_fs9.existsSync)(library) || (0, import_node_fs9.statSync)(source).mtimeMs > (0, import_node_fs9.statSync)(library).mtimeMs
6825
- );
6826
- if (stale) {
6827
- await run2("sh", [
6828
- import_node_path9.default.join(moduleRoot, "scripts/build-preview-plugin.sh"),
6829
- toolchainBin,
6830
- plugins[0].library
6831
- ]);
6832
- }
6833
- return plugins.map(({ library }) => library);
6834
- }
6835
- var linkedModuleDigests = /* @__PURE__ */ new Map();
6836
- function swiftModuleDigest(root) {
6837
- const files = swiftModuleInputFiles(root);
6838
- const stampHash = (0, import_node_crypto4.createHash)("sha256");
6839
- for (const file of files) {
6840
- const stat2 = (0, import_node_fs9.statSync)(import_node_path9.default.join(root, file), { bigint: true });
6841
- stampHash.update(file);
6842
- stampHash.update(
6843
- `${stat2.dev}:${stat2.ino}:${stat2.size}:${stat2.mtimeNs}:${stat2.ctimeNs}
6844
- `
6845
- );
6846
- }
6847
- const stamp = stampHash.digest("hex");
6848
- const cached3 = linkedModuleDigests.get(root);
6849
- if (cached3?.stamp === stamp) return cached3.digest;
6850
- const hash = (0, import_node_crypto4.createHash)("sha256");
6851
- for (const file of files) {
6852
- hash.update((0, import_node_crypto4.createHash)("sha256").update(file).digest());
6853
- hash.update(
6854
- (0, import_node_crypto4.createHash)("sha256").update((0, import_node_fs9.readFileSync)(import_node_path9.default.join(root, file))).digest()
6855
- );
6856
- }
6857
- const digest = hash.digest();
6858
- linkedModuleDigests.set(root, { stamp, digest });
6859
- return digest;
6860
- }
6861
- function compileTargets(input) {
6862
- const manifest = input.files["Package.swift"];
6863
- return manifest === void 0 ? [] : swiftPackagePartition(manifest);
6864
- }
6865
- function withNativeSourceGlue(input, glue) {
6866
- const targets = compileTargets(input);
6867
- if (targets.length > 1) {
6868
- throw new Error("swift native modules need one SwiftPM target");
6869
- }
6870
- const targetPath = targets[0]?.path === "." ? "" : targets[0]?.path ?? "";
6871
- return {
6872
- ...input,
6873
- files: {
6874
- ...input.files,
6875
- [import_node_path9.default.posix.join(targetPath, "OneNativeSource.generated.swift")]: glue
6876
- },
6877
- oneModule: true
6878
- };
6879
- }
6880
- var OPTIONAL_FRAMEWORK_DEPENDENCIES = {
6881
- Accelerate: [],
6882
- CryptoKit: [],
6883
- Security: [],
6884
- TikTokBusinessSDK: [],
6885
- nSure: [],
6886
- Statsig: [],
6887
- DatadogCore: [],
6888
- DatadogLogs: ["DatadogCore"],
6889
- DatadogRUM: ["DatadogCore"],
6890
- DatadogTrace: ["DatadogCore"]
6891
- };
6892
- var OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES));
6893
- function swiftTargetDependencies(files, targets) {
6894
- const names = /* @__PURE__ */ new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)]);
6895
- const siblings = /* @__PURE__ */ new Map();
6896
- for (const target of targets) {
6897
- const prefix = target.path === "." ? "" : `${target.path}/`;
6898
- const deps = /* @__PURE__ */ new Set();
6899
- for (const [file, contents] of Object.entries(files)) {
6900
- if (file === "Package.swift" || !file.startsWith(prefix)) continue;
6901
- if (targets.some(
6902
- (candidate) => candidate.name !== target.name && candidate.path !== "." && candidate.path.startsWith(prefix) && file.startsWith(`${candidate.path}/`)
6903
- ))
6904
- continue;
6905
- for (const match of contents.matchAll(
6906
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm
6907
- )) {
6908
- if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1]);
6972
+ ] : compileTargets(input);
6973
+ const files = /* @__PURE__ */ new Map();
6974
+ const moduleFiles = `
6975
+ // sootsim-swift files ${(0, import_node_crypto3.createHash)("sha256").update(swiftModuleInputFiles(moduleRoot).join("\n")).digest("hex").slice(0, 16)}
6976
+ `;
6977
+ if (targets.length === 0) {
6978
+ for (const [file, contents] of Object.entries(input.files)) {
6979
+ if (file === "Package.swift") continue;
6980
+ files.set(import_node_path7.default.join(layout.sources, file), compiledSource(file, contents));
6981
+ }
6982
+ let manifest = (0, import_node_fs7.readFileSync)(
6983
+ import_node_path7.default.join(moduleRoot, "scripts/contrast-app-Package.swift"),
6984
+ "utf8"
6985
+ ).replaceAll("__SOOTSIM_SWIFT_PACKAGE__", moduleRoot);
6986
+ const optionalProducts = swiftTargetDependencies(input.files, [{ name: "App", path: "." }]).get("App") ?? [];
6987
+ if (optionalProducts.length > 0) {
6988
+ const product = '.product(name: "SwiftUI", package: "sootsim-swift"),';
6989
+ if (!manifest.includes(product))
6990
+ throw new Error("Swift app template lost its framework dependency anchor");
6991
+ manifest = manifest.replace(
6992
+ product,
6993
+ [
6994
+ product,
6995
+ ...optionalProducts.map(
6996
+ (name2) => `.product(name: "${name2}", package: "sootsim-swift"),`
6997
+ )
6998
+ ].join("\n ")
6999
+ );
7000
+ }
7001
+ if (input.oneModule) {
7002
+ const product = '.product(name: "CoreLocation", package: "sootsim-swift"),';
7003
+ const flags = `"-Osize"${FOUNDATION_IMPLICIT_FLAGS}`;
7004
+ if (!manifest.includes(product) || !manifest.includes(flags)) {
7005
+ throw new Error(
7006
+ "scripts/contrast-app-Package.swift lost the lines the One module links at"
7007
+ );
6909
7008
  }
7009
+ manifest = manifest.replace(product, `${product}
7010
+ ${ONE_PRODUCT},`).replace(flags, `${flags}${ONE_IMPLICIT_FLAGS}`);
6910
7011
  }
6911
- siblings.set(target.name, [...deps].sort());
6912
- }
6913
- return siblings;
6914
- }
6915
- var ONE_PRODUCT = '.product(name: "One", package: "sootsim-swift")';
6916
- var SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")';
6917
- var importsSpriteKit = (files) => Object.entries(files).some(
6918
- ([file, contents]) => file.endsWith(".swift") && /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
6919
- contents
6920
- )
6921
- );
6922
- var FOUNDATION_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"';
6923
- var ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"';
6924
- var MULTI_MANIFEST_VERSION = 10;
6925
- function swiftArtifactHash(input, release, moduleRoot) {
6926
- const hash = (0, import_node_crypto4.createHash)("sha256");
6927
- hash.update(`swift-compile/v12
6928
- ${release}
6929
- `);
6930
- if (input.oneModule) hash.update("one-module\n");
6931
- hash.update(swiftModuleDigest(moduleRoot));
6932
- for (const file of Object.keys(input.files).sort()) {
6933
- hash.update((0, import_node_crypto4.createHash)("sha256").update(file).digest());
6934
- hash.update((0, import_node_crypto4.createHash)("sha256").update(input.files[file]).digest());
6935
- }
6936
- for (const base of Object.keys(input.resources ?? {}).sort()) {
6937
- hash.update((0, import_node_crypto4.createHash)("sha256").update(base).digest());
6938
- hash.update(
6939
- (0, import_node_crypto4.createHash)("sha256").update(input.resources?.[base] ?? "").digest()
6940
- );
6941
- }
6942
- for (const name2 of Object.keys(input.images ?? {}).sort()) {
6943
- const image = input.images?.[name2];
6944
- if (!image) continue;
6945
- hash.update((0, import_node_crypto4.createHash)("sha256").update(name2).digest());
6946
- hash.update((0, import_node_crypto4.createHash)("sha256").update(image.file).digest());
6947
- hash.update((0, import_node_crypto4.createHash)("sha256").update(image.data).digest());
6948
- }
6949
- const targets = compileTargets(input);
6950
- if (targets.length > 0) {
6951
- hash.update(`swift-multi/v${MULTI_MANIFEST_VERSION}
6952
- `);
6953
- hash.update(
6954
- JSON.stringify({
6955
- targets,
6956
- siblings: [...swiftTargetDependencies(input.files, targets)].sort(
6957
- (a, b) => String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0
6958
- )
6959
- })
6960
- );
6961
- }
6962
- return hash.digest("hex");
6963
- }
6964
- function emitSwiftPackageManifest(args) {
6965
- const { targets, siblings, moduleRoot, oneModule, spriteKit, distribution } = args;
6966
- const reachedFrameworks = new Set(
6967
- [...siblings.values()].flat().filter(
6968
- (name2) => OPTIONAL_FRAMEWORKS.has(name2) && !targets.some((target) => target.name === name2)
6969
- ).flatMap((name2) => [name2, ...OPTIONAL_FRAMEWORK_DEPENDENCIES[name2] ?? []])
6970
- );
6971
- const distributionObjects = distribution?.objects.filter(
6972
- (object) => [...OPTIONAL_FRAMEWORKS].every(
6973
- (name2) => !object.startsWith(`lib/${name2}-`) || reachedFrameworks.has(name2)
6974
- )
6975
- );
6976
- const executable = targets.find((target) => target.executable);
6977
- if (!executable) throw new Error("swift-compile: no executable target to emit");
6978
- const stanza = (target) => {
6979
- const isolation = target.mainActorIsolation ? " .defaultIsolation(MainActor.self)," : "";
6980
- const imports = distribution ? `, "-I", ${JSON.stringify(import_node_path9.default.join(moduleRoot, "modules"))}` : "";
6981
- const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${FOUNDATION_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ""}${imports}])]`;
6982
- const deps = [
6983
- ...distribution ? [] : [
6984
- '.product(name: "SwiftUI", package: "sootsim-swift")',
6985
- ...oneModule ? [ONE_PRODUCT] : [],
6986
- ...spriteKit ? [SPRITEKIT_PRODUCT] : []
6987
- ],
6988
- ...(siblings.get(target.name) ?? []).flatMap(
6989
- (dependency) => OPTIONAL_FRAMEWORKS.has(dependency) && !targets.some((candidate) => candidate.name === dependency) ? distribution ? [] : [`.product(name: "${dependency}", package: "sootsim-swift")`] : [`"${dependency}"`]
6990
- )
6991
- ].join(", ");
6992
- const library = distribution ? [
6993
- ...(distributionObjects ?? []).map((object) => import_node_path9.default.join(moduleRoot, object)),
6994
- ...distribution.link
6995
- ].map((flag) => `, ${JSON.stringify(flag)}`).join("") : "";
6996
- const kind = target.executable ? ".executableTarget" : ".target";
6997
- const link = target.executable ? `,
6998
- linkerSettings: [
6999
- .unsafeFlags([
7000
- "-Xclang-linker", "-mexec-model=reactor",
7001
- "-Xlinker", "--export-if-defined=__main_argc_argv"${library},
7002
- ]),
7003
- .unsafeFlags(["-Xlinker", "--strip-all"], .when(configuration: .release)),
7004
- ]` : "";
7005
- return [
7006
- ` ${kind}(`,
7007
- ` name: "${target.name}",`,
7008
- ` dependencies: [${deps}],`,
7009
- ` path: "${target.path}",`,
7010
- ` ${swiftSettings}${link}`,
7011
- ` ),`
7012
- ].join("\n");
7013
- };
7014
- return [
7015
- "// swift-tools-version: 6.2",
7016
- "import PackageDescription",
7017
- "",
7018
- "// generated by swift-compile from the project package partition.",
7019
- "let package = Package(",
7020
- ' name: "app",',
7021
- ` products: [.executable(name: "${executable.name}", targets: ["${executable.name}"])],`,
7022
- ` dependencies: [${distribution ? "" : `.package(path: "${moduleRoot}")`}],`,
7023
- " targets: [",
7024
- ...targets.map(stanza),
7025
- " ]",
7026
- ")",
7027
- ""
7028
- ].join("\n");
7029
- }
7030
- function syncSwiftTree(base, files) {
7031
- (0, import_node_fs9.mkdirSync)(base, { recursive: true });
7032
- const walk = (dir) => {
7033
- for (const entry of (0, import_node_fs9.readdirSync)(dir, { withFileTypes: true })) {
7034
- const full = import_node_path9.default.join(dir, entry.name);
7035
- if (dir === base && entry.name === ".build") continue;
7036
- if (entry.isDirectory()) walk(full);
7037
- else if (!files.has(full)) (0, import_node_fs9.rmSync)(full, { force: true });
7012
+ if (importsSpriteKit(input.files)) {
7013
+ const anchor = '.product(name: "CoreLocation", package: "sootsim-swift"),';
7014
+ if (!manifest.includes(anchor))
7015
+ throw new Error(
7016
+ "scripts/contrast-app-Package.swift lost the line the SpriteKit product links at"
7017
+ );
7018
+ manifest = manifest.replace(anchor, `${anchor}
7019
+ ${SPRITEKIT_PRODUCT},`);
7038
7020
  }
7039
- };
7040
- walk(base);
7041
- for (const [full, contents] of files) {
7042
- if ((0, import_node_fs9.existsSync)(full) && (0, import_node_fs9.readFileSync)(full, "utf8") === contents) continue;
7043
- (0, import_node_fs9.mkdirSync)(import_node_path9.default.dirname(full), { recursive: true });
7044
- (0, import_node_fs9.writeFileSync)(full, contents, "utf8");
7021
+ files.set(import_node_path7.default.join(layout.root, "Package.swift"), manifest + moduleFiles);
7022
+ } else {
7023
+ const base = layout.multi ? layout.root : layout.sources;
7024
+ for (const [file, contents] of Object.entries(input.files)) {
7025
+ if (file === "Package.swift") continue;
7026
+ files.set(import_node_path7.default.join(base, file), compiledSource(file, contents));
7027
+ }
7028
+ for (const target of targets) {
7029
+ if (!target.resources) continue;
7030
+ files.set(
7031
+ import_node_path7.default.join(layout.root, target.path, "ResourceBundleAccessor.generated.swift"),
7032
+ [
7033
+ "import Foundation",
7034
+ "",
7035
+ "extension Foundation.Bundle {",
7036
+ " static let module: Bundle = Bundle.main",
7037
+ "}",
7038
+ ""
7039
+ ].join("\n")
7040
+ );
7041
+ }
7042
+ files.set(
7043
+ import_node_path7.default.join(layout.root, "Package.swift"),
7044
+ emitSwiftPackageManifest({
7045
+ targets,
7046
+ siblings: swiftTargetDependencies(
7047
+ input.files,
7048
+ layout.multi ? targets : targets.map((target) => ({ ...target, path: "." }))
7049
+ ),
7050
+ moduleRoot,
7051
+ oneModule: input.oneModule,
7052
+ spriteKit: importsSpriteKit(input.files),
7053
+ distribution: distribution ?? void 0
7054
+ }) + moduleFiles
7055
+ );
7045
7056
  }
7057
+ syncSwiftTree(layout.root, files);
7046
7058
  }
7047
- var DIRECTIVE = /^[ \t]*#(?:if|elseif)\b/;
7048
- var OS_IOS = /\bos\(\s*iOS\s*\)/g;
7049
- var OBJC_ATTRIBUTE = /^@(?:objcMembers\b|objc\b(?:(\s*)\(([^()]*)\))?|IBAction\b)/;
7050
- var SELECTOR = /^#selector\b/;
7051
- var TYPE_AFTER_ATTRIBUTE = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/|@\w+(?:\([^()]*\))?|\b(?:public|open|final|internal|fileprivate|private|package|nonisolated|indirect)\b)*\b(?:class(?!\s+(?:func|var|let|subscript)\b)|struct|enum|protocol|extension|actor)\b/;
7052
- var DELEGATE_CLASS = /^class\s+[A-Za-z_]\w*\s*(?:<[^>{]*>)?\s*:[^{]*\b(?:UIApplicationDelegate|UISceneDelegate|UIWindowSceneDelegate)\b[^{]*\{/;
7053
- var REUSABLE_INIT = /^override(?=\s+init\s*\(\s*(?:style\s*:[^,)]*,\s*reuseIdentifier|reuseIdentifier)\s*:)/;
7054
- var REUSABLE_VIEW_BASES = [
7055
- "UICollectionReusableView",
7056
- "UICollectionViewCell",
7057
- "UICollectionViewListCell"
7058
- ];
7059
- var CLASS_BASE = /^class\s+([A-Za-z_]\w*)\s*(?:<[^>{]*>)?\s*:\s*([A-Za-z_][\w.]*)[^{]*\{/;
7060
- var FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/;
7061
- var APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/;
7062
- var EXTENSION_DECL = /^extension\s+([A-Za-z_][\w.]*)/;
7063
- var CLASS_DECL = /^class\s+(?!(?:func|var|let|subscript)\b)([A-Za-z_]\w*)/;
7064
- var MODIFIERS = /(?:^|\s)(public|open|internal|fileprivate|private|final|nonisolated|@MainActor)(?=\s)/g;
7065
- var OVERRIDE_FUNC = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+func\s+([A-Za-z_]\w*)\s*(<[^>{}]*>)?\s*\(/;
7066
- var OVERRIDE_VAR = /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+var\s+([A-Za-z_]\w*)\s*:\s*([^{=]+?)\s*\{/;
7067
- function splitTopLevel(text) {
7068
- const parts = [];
7069
- let depth = 0;
7070
- let start = 0;
7071
- for (let i = 0; i < text.length; i++) {
7072
- const char = text[i];
7073
- if (char === "(" || char === "[" || char === "<") depth++;
7074
- else if (char === ")" || char === "]" || char === ">" && text[i - 1] !== "-")
7075
- depth--;
7076
- else if (char === "," && depth === 0) {
7077
- parts.push(text.slice(start, i));
7078
- start = i + 1;
7079
- }
7059
+ function streamText(value) {
7060
+ if (typeof value === "string") return value.trim();
7061
+ if (Buffer.isBuffer(value)) return value.toString("utf8").trim();
7062
+ return "";
7063
+ }
7064
+ function outputOf(error) {
7065
+ if (error && typeof error === "object") {
7066
+ const streams = [
7067
+ streamText(Reflect.get(error, "stdout")),
7068
+ streamText(Reflect.get(error, "stderr"))
7069
+ ].filter(Boolean);
7070
+ if (streams.length > 0) return streams.join("\n");
7080
7071
  }
7081
- parts.push(text.slice(start));
7082
- return parts.map((part) => part.trim()).filter((part) => part !== "");
7072
+ return error instanceof Error ? error.message : String(error);
7083
7073
  }
7084
- function forwardedArguments(parameters) {
7085
- const args = [];
7086
- for (const parameter of splitTopLevel(parameters)) {
7087
- const match = /^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([\s\S]*)$/.exec(parameter);
7088
- if (!match || match[3].includes("...")) return null;
7089
- const label = match[1] ?? match[2];
7090
- const value = (/^(?:@\w+\s+)*inout\b/.test(match[3]) ? "&" : "") + match[2];
7091
- args.push(label === "_" ? value : `${label}: ${value}`);
7074
+ function builtArtifact(layout) {
7075
+ const binDir = import_node_path7.default.join(layout.root, ".build", WASM_TRIPLE, "release");
7076
+ const manifest = (0, import_node_fs7.readFileSync)(import_node_path7.default.join(layout.root, "Package.swift"), "utf8");
7077
+ const executable = swiftManifestTargets(manifest).find((target) => target.executable);
7078
+ if (executable === void 0) {
7079
+ throw new Error("swift-compile: the written manifest names no executable target");
7092
7080
  }
7093
- return args.join(", ");
7081
+ const file = import_node_path7.default.join(binDir, `${executable.name}.wasm`);
7082
+ if (!(0, import_node_fs7.existsSync)(file)) {
7083
+ const found = (0, import_node_fs7.existsSync)(binDir) ? (0, import_node_fs7.readdirSync)(binDir).filter((name2) => name2.endsWith(".wasm")).sort() : [];
7084
+ throw new Error(
7085
+ `swift-compile: the build produced no ${executable.name}.wasm (found: ${found.join(", ") || "none"})`
7086
+ );
7087
+ }
7088
+ return file;
7094
7089
  }
7095
- function liftExtensionOverrides(source) {
7096
- const { tokens } = swiftCodeScan(source);
7097
- const stack = [];
7098
- let pending = null;
7099
- const classes = /* @__PURE__ */ new Map();
7100
- let declaredBase = null;
7101
- let declaredObjCMembers = false;
7102
- const lifted = [];
7103
- const closing = (open) => {
7104
- let depth = 0;
7105
- for (const at of tokens) {
7106
- if (at < open) continue;
7107
- if (source[at] === "{") depth++;
7108
- else if (source[at] === "}" && --depth === 0) return at + 1;
7109
- }
7110
- return source.length;
7090
+ function projectDiagnostic(output, layout) {
7091
+ const base = layout.multi ? layout.root : layout.sources;
7092
+ const prefix = `${base}${import_node_path7.default.sep}`;
7093
+ return output.split("\n").map((line) => line.startsWith(prefix) ? line.slice(prefix.length) : line).join("\n").trim();
7094
+ }
7095
+ var ROOT_LOCKS = Symbol.for("peachsim.swiftCompile.rootLocks");
7096
+ var host = globalThis;
7097
+ var rootLocks = host[ROOT_LOCKS] ??= /* @__PURE__ */ new Map();
7098
+ function serialize(root, work) {
7099
+ const current = rootLocks.get(root) ?? Promise.resolve();
7100
+ const next = current.then(work, work);
7101
+ rootLocks.set(
7102
+ root,
7103
+ next.catch(() => {
7104
+ })
7105
+ );
7106
+ return next;
7107
+ }
7108
+ function compileSwiftProjectUnit(input, options) {
7109
+ (0, import_node_fs7.mkdirSync)(options.buildRoot, { recursive: true });
7110
+ const root = (0, import_node_fs7.realpathSync)(options.buildRoot);
7111
+ const moduleRoot = import_node_path7.default.resolve(options.moduleRoot);
7112
+ const layout = {
7113
+ root,
7114
+ sources: import_node_path7.default.join(root, "Sources", "App"),
7115
+ multi: compileTargets(input).length > 0
7111
7116
  };
7112
- for (const at of tokens) {
7113
- const rest = source.slice(at, at + 600);
7114
- if (rest.startsWith("{")) {
7115
- const frame = pending ?? { kind: "other", name: "" };
7116
- if (frame.kind === "class" && !classes.has(frame.name))
7117
- classes.set(frame.name, {
7118
- brace: at,
7119
- base: declaredBase,
7120
- objcMembers: declaredObjCMembers
7121
- });
7122
- stack.push(frame);
7123
- pending = null;
7124
- continue;
7125
- }
7126
- if (rest.startsWith("}")) {
7127
- stack.pop();
7128
- continue;
7129
- }
7130
- const declared = CLASS_DECL.exec(rest);
7131
- if (declared) {
7132
- pending = { kind: "class", name: declared[1] };
7133
- declaredBase = CLASS_BASE.exec(rest)?.[2]?.split(".").pop() ?? null;
7134
- const lines = source.lastIndexOf("\n", source.lastIndexOf("\n", at - 1) - 1) + 1;
7135
- declaredObjCMembers = /@objcMembers\b/.test(source.slice(lines, at));
7136
- continue;
7137
- }
7138
- const extended = EXTENSION_DECL.exec(rest);
7139
- if (extended) {
7140
- pending = { kind: "extension", name: extended[1].split(".").pop() };
7141
- continue;
7142
- }
7143
- const top = stack.at(-1);
7144
- if (!rest.startsWith("override") || top?.kind !== "extension" || pending) continue;
7145
- const line = source.slice(source.lastIndexOf("\n", at - 1) + 1, at);
7146
- const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim());
7147
- const func = OVERRIDE_FUNC.exec(rest);
7148
- if (func) {
7149
- const name2 = func[2];
7150
- const open = at + func[0].length - 1;
7151
- let depth = 0;
7152
- let close = open;
7153
- for (; close < source.length; close++) {
7154
- if (source[close] === "(") depth++;
7155
- else if (source[close] === ")" && --depth === 0) break;
7156
- }
7157
- const body = tokens.find((token) => token > close && source[token] === "{");
7158
- if (body === void 0) continue;
7159
- const clause = source.slice(close + 1, body).trim();
7160
- const args = forwardedArguments(source.slice(open + 1, close));
7161
- if (args === null) continue;
7162
- const call = (clause.includes("->") ? "return " : "") + (/\b(?:throws|rethrows)\b/.test(clause) ? "try " : "") + (/\basync\b/.test(clause) ? "await " : "") + `__peach_ext_${name2}(${args})`;
7163
- const signature = `func ${name2}${func[3] ?? ""}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ""}`;
7164
- lifted.push({
7165
- type: top.name,
7166
- member: name2,
7167
- stub: `${[...modifiers, "override"].join(" ")} ${signature} { ${call} };`,
7168
- edits: [
7169
- [at, "override".length, " ".repeat("override".length)],
7170
- [
7171
- at + rest.indexOf(
7172
- name2,
7173
- rest.indexOf("func", "override".length + func[1].length) + 4
7174
- ),
7175
- 0,
7176
- "__peach_ext_"
7177
- ]
7178
- ]
7179
- });
7180
- continue;
7117
+ const hash = swiftArtifactHash(input, options.release, moduleRoot);
7118
+ return serialize(root, async () => {
7119
+ writeSwiftProject(layout, input, moduleRoot);
7120
+ const swift = import_node_path7.default.join(options.toolchainBin, "swift");
7121
+ if (!(0, import_node_fs7.existsSync)(swift)) {
7122
+ throw new Error(
7123
+ `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`
7124
+ );
7181
7125
  }
7182
- const property = OVERRIDE_VAR.exec(rest);
7183
- if (property) {
7184
- const open = at + property[0].length - 1;
7185
- if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue;
7186
- const name2 = property[2];
7187
- lifted.push({
7188
- type: top.name,
7189
- member: name2,
7190
- stub: `${[...modifiers, "override"].join(" ")} var ${name2}: ${property[3].trim()} { __peach_ext_${name2} };`,
7191
- edits: [
7192
- [at, "override".length, " ".repeat("override".length)],
7193
- [at + rest.indexOf(name2, rest.indexOf("var")), 0, "__peach_ext_"]
7194
- ]
7195
- });
7126
+ const macroPlugins = await ensureMacroPlugins(moduleRoot, options.toolchainBin);
7127
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId;
7128
+ const icu = swiftIcuAsset(options.toolchainBin, sdk);
7129
+ try {
7130
+ await run2(
7131
+ swift,
7132
+ [
7133
+ "build",
7134
+ "-j",
7135
+ BUILD_JOBS,
7136
+ "--package-path",
7137
+ root,
7138
+ "--swift-sdk",
7139
+ sdk,
7140
+ "-c",
7141
+ "release",
7142
+ "-Xswiftc",
7143
+ "-Osize",
7144
+ ...macroPlugins.flatMap((plugin) => [
7145
+ "-Xswiftc",
7146
+ "-load-plugin-library",
7147
+ "-Xswiftc",
7148
+ plugin
7149
+ ])
7150
+ ],
7151
+ { env: BUILD_ENV, maxBuffer: 64 * 1024 * 1024, timeout: options.timeoutMs }
7152
+ );
7153
+ } catch (error) {
7154
+ throw new Error(projectDiagnostic(outputOf(error), layout), { cause: error });
7196
7155
  }
7156
+ return {
7157
+ hash,
7158
+ bytes: (0, import_node_fs7.readFileSync)(builtArtifact(layout)),
7159
+ icu: await icu
7160
+ };
7161
+ });
7162
+ }
7163
+
7164
+ // src/swift-distribution.ts
7165
+ var import_node_fs11 = __toESM(require("node:fs"), 1);
7166
+ var import_node_path11 = __toESM(require("node:path"), 1);
7167
+
7168
+ // ../contrast-runtime-delivery/src/index.ts
7169
+ var import_node_child_process4 = require("node:child_process");
7170
+ var import_node_crypto4 = __toESM(require("node:crypto"), 1);
7171
+ var import_node_fs9 = __toESM(require("node:fs"), 1);
7172
+ var import_node_os3 = __toESM(require("node:os"), 1);
7173
+ var import_node_path9 = __toESM(require("node:path"), 1);
7174
+ var import_node_stream = require("node:stream");
7175
+ var import_promises3 = require("node:stream/promises");
7176
+
7177
+ // ../contrast-runtime-delivery/src/product.ts
7178
+ var import_node_fs8 = __toESM(require("node:fs"), 1);
7179
+ var import_node_path8 = __toESM(require("node:path"), 1);
7180
+ function isValidRuntimeVersion(value) {
7181
+ return value.length <= 100 && /^[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value);
7182
+ }
7183
+ function listInstalledRuntimes(product) {
7184
+ try {
7185
+ return import_node_fs8.default.readdirSync(product.runtimesDir(), { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort(compareSemver);
7186
+ } catch {
7187
+ return [];
7197
7188
  }
7198
- const overridesObjC = (type, member) => {
7199
- let base = classes.get(type)?.base ?? null;
7200
- while (base !== null) {
7201
- if (APPLE_CLASS.test(base)) return true;
7202
- const declaredClass = classes.get(base);
7203
- if (!declaredClass) return false;
7204
- const body = source.slice(declaredClass.brace, closing(declaredClass.brace));
7205
- const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body);
7206
- if (found) {
7207
- const line = body.slice(body.lastIndexOf("\n", found.index) + 1, found.index);
7208
- return declaredClass.objcMembers || /@objc\b/.test(line);
7209
- }
7210
- base = declaredClass.base;
7211
- }
7212
- return false;
7189
+ }
7190
+ function runtimeTarballCacheName(product, version) {
7191
+ return import_node_path8.default.posix.basename(product.tarballPath(version));
7192
+ }
7193
+ function compareSemver(a, b) {
7194
+ const parse2 = (v) => {
7195
+ const hyphen = v.indexOf("-");
7196
+ const core = hyphen >= 0 ? v.slice(0, hyphen) : v;
7197
+ const pre = hyphen >= 0 ? v.slice(hyphen + 1) : "";
7198
+ const parts = core.split(".").map((n) => Number.parseInt(n, 10));
7199
+ if (parts.some((n) => !Number.isFinite(n))) return [[Number.POSITIVE_INFINITY], v];
7200
+ return [parts, pre];
7213
7201
  };
7214
- const edits = [];
7215
- const stubs = /* @__PURE__ */ new Map();
7216
- for (const entry of lifted) {
7217
- const brace = classes.get(entry.type)?.brace;
7218
- if (brace === void 0 || !overridesObjC(entry.type, entry.member)) continue;
7219
- edits.push(...entry.edits);
7220
- stubs.set(brace, [...stubs.get(brace) ?? [], entry.stub]);
7202
+ const [an, ap] = parse2(a);
7203
+ const [bn, bp] = parse2(b);
7204
+ for (let i = 0; i < Math.max(an.length, bn.length); i++) {
7205
+ const av = an[i] ?? 0;
7206
+ const bv = bn[i] ?? 0;
7207
+ if (av !== bv) return av - bv;
7221
7208
  }
7222
- for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(" ")}`]);
7223
- let out = source;
7224
- for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
7225
- out = out.slice(0, at) + insert + out.slice(at + remove);
7226
- return out;
7209
+ if (ap === bp) return 0;
7210
+ if (!ap) return 1;
7211
+ if (!bp) return -1;
7212
+ return ap < bp ? -1 : 1;
7227
7213
  }
7228
- function swiftSourceAsIOS(original) {
7229
- const source = liftExtensionOverrides(original);
7230
- const { lineStarts, tokens } = swiftCodeScan(source);
7231
- let offset = 0;
7232
- const conditioned = source.split("\n").map((line) => {
7233
- const start = offset;
7234
- offset += line.length + 1;
7235
- if (!lineStarts.has(start) || !DIRECTIVE.test(line)) return line;
7236
- return line.replace(OS_IOS, (match) => "true".padEnd(match.length));
7237
- }).join("\n");
7238
- let out = "";
7239
- let copied = 0;
7240
- const reusableViews = new Set(REUSABLE_VIEW_BASES);
7241
- const reusableBodies = [];
7242
- let depth = 0;
7243
- let opensReusableBody = false;
7244
- for (const at of tokens) {
7245
- const rest = conditioned.slice(at, at + 400);
7246
- if (rest.startsWith("{")) {
7247
- depth++;
7248
- if (opensReusableBody) reusableBodies.push(depth);
7249
- opensReusableBody = false;
7250
- continue;
7251
- }
7252
- if (rest.startsWith("}")) {
7253
- if (reusableBodies.at(-1) === depth) reusableBodies.pop();
7254
- depth--;
7255
- continue;
7214
+
7215
+ // ../contrast-runtime-delivery/src/index.ts
7216
+ var DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT = 2;
7217
+ function createRuntimeDelivery(product) {
7218
+ function readConfig() {
7219
+ try {
7220
+ const parsed = JSON.parse(
7221
+ import_node_fs9.default.readFileSync(product.configFile(), "utf8")
7222
+ );
7223
+ return parsed && typeof parsed === "object" ? parsed : {};
7224
+ } catch {
7225
+ return {};
7256
7226
  }
7257
- if (rest.startsWith("override")) {
7258
- if (REUSABLE_INIT.test(rest) || reusableBodies.at(-1) === depth && FRAME_INIT.test(rest)) {
7259
- out += `${conditioned.slice(copied, at)}required`;
7260
- copied = at + "override".length;
7261
- }
7262
- continue;
7227
+ }
7228
+ function resolveCdnOrigin(input) {
7229
+ const config = readConfig();
7230
+ const value = input || process.env[product.env.cdnOrigin] || config.cdnOrigin || product.defaultCdnOrigin;
7231
+ return value.replace(/\/+$/, "");
7232
+ }
7233
+ function resolveChannel(input) {
7234
+ const config = readConfig();
7235
+ return input || process.env[product.env.channel] || config.runtimeChannel || "stable";
7236
+ }
7237
+ function resolvePin() {
7238
+ if (!product.env.pin) return null;
7239
+ const env = process.env[product.env.pin];
7240
+ if (env && env.trim()) return env.trim();
7241
+ const config = readConfig();
7242
+ return typeof config.runtimeVersion === "string" && config.runtimeVersion.trim() ? config.runtimeVersion.trim() : null;
7243
+ }
7244
+ function manifestUrl(cdnOrigin) {
7245
+ const url = new URL(`${resolveCdnOrigin(cdnOrigin)}${product.manifestPath}`);
7246
+ url.searchParams.set("t", String(Date.now()));
7247
+ return url.toString();
7248
+ }
7249
+ function tarballUrl(version, cdnOrigin) {
7250
+ return `${resolveCdnOrigin(cdnOrigin)}${product.tarballPath(version)}`;
7251
+ }
7252
+ const UP_TO_DATE_CHECK_TIMEOUT_MS = 2e3;
7253
+ async function fetchManifest(cdnOrigin, timeoutMs) {
7254
+ const url = manifestUrl(cdnOrigin);
7255
+ const res = await fetch(url, {
7256
+ headers: { Accept: "application/json" },
7257
+ // an install is allowed to wait; a best-effort check is not. see
7258
+ // UP_TO_DATE_CHECK_TIMEOUT_MS.
7259
+ ...timeoutMs ? { signal: AbortSignal.timeout(timeoutMs) } : {}
7260
+ });
7261
+ if (!res.ok) {
7262
+ throw new Error(`manifest fetch failed: ${res.status} ${res.statusText} (${url})`);
7263
7263
  }
7264
- const imported = /^import\s+CoreImage\.CIFilterBuiltins\b/.exec(rest);
7265
- if (imported) {
7266
- out += conditioned.slice(copied, at) + "import CoreImage".padEnd(imported[0].length);
7267
- copied = at + imported[0].length;
7268
- continue;
7264
+ return await res.json();
7265
+ }
7266
+ function resolveVersion(manifest, opts = {}) {
7267
+ const channel = resolveChannel(opts.channel);
7268
+ const version = opts.version || resolvePin() || manifest.channels[channel]?.latest;
7269
+ if (!version) {
7270
+ throw new Error(
7271
+ `no version specified and channel '${channel}' has no latest entry in the manifest`
7272
+ );
7269
7273
  }
7270
- if (/^NSClassFromString\b/.test(rest)) {
7271
- out += conditioned.slice(copied, at) + "_peachClassFromString";
7272
- copied = at + "NSClassFromString".length;
7273
- continue;
7274
+ if (!isValidRuntimeVersion(version)) {
7275
+ throw new Error(`invalid runtime version: ${version}`);
7274
7276
  }
7275
- if (rest.startsWith("class")) {
7276
- const declared = CLASS_BASE.exec(rest);
7277
- if (declared && reusableViews.has(declared[2].split(".").pop())) {
7278
- reusableViews.add(declared[1]);
7279
- opensReusableBody = true;
7280
- }
7281
- const modifiers = conditioned.slice(conditioned.lastIndexOf("\n", at - 1) + 1, at);
7282
- if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
7283
- out += `${conditioned.slice(copied, at)}final `;
7284
- copied = at;
7285
- }
7286
- continue;
7277
+ const entry = manifest.versions[version];
7278
+ if (!entry) {
7279
+ throw new Error(
7280
+ `version ${version} not found in manifest; available: ${Object.keys(manifest.versions).slice(-10).join(", ") || "(none)"}`
7281
+ );
7287
7282
  }
7288
- const selector = SELECTOR.exec(rest);
7289
- const match = selector ?? OBJC_ATTRIBUTE.exec(rest);
7290
- if (!match) continue;
7291
- let replacement = "@ObjC";
7292
- if (selector) replacement = "#Selector";
7293
- else if (match[0] === "@objcMembers") replacement = "@ObjCMembers";
7294
- else if (match[0] === "@IBAction") replacement = "@ObjC".padEnd(match[0].length);
7295
- else if (TYPE_AFTER_ATTRIBUTE.test(rest.slice(match[0].length)))
7296
- replacement = " ".repeat(match[0].length);
7297
- else if (match[2] !== void 0)
7298
- replacement = `@ObjC${match[1]}("${match[2].trim()}")`;
7299
- out += conditioned.slice(copied, at) + replacement;
7300
- copied = at + match[0].length;
7283
+ return { version, channel, entry };
7301
7284
  }
7302
- return out + conditioned.slice(copied);
7303
- }
7304
- function swiftCodeScan(source) {
7305
- const starts = /* @__PURE__ */ new Set();
7306
- const tokens = [];
7307
- const stack = [{ kind: "code", parens: 0 }];
7308
- const hashesAt = (at) => {
7309
- let end = at;
7310
- while (source[end] === "#") end++;
7311
- return end - at;
7312
- };
7313
- const closes = (at, hashes) => source.startsWith("#".repeat(hashes), at);
7314
- let i = 0;
7315
- while (i < source.length) {
7316
- const top = stack[stack.length - 1];
7317
- if ((i === 0 || source[i - 1] === "\n") && top.kind === "code" && stack.length === 1)
7318
- starts.add(i);
7319
- const char = source[i];
7320
- if (top.kind === "block") {
7321
- if (source.startsWith("/*", i)) {
7322
- top.depth++;
7323
- i += 2;
7324
- } else if (source.startsWith("*/", i)) {
7325
- if (--top.depth === 0) stack.pop();
7326
- i += 2;
7327
- } else i++;
7328
- continue;
7285
+ async function install(opts = {}) {
7286
+ product.ensureHome();
7287
+ const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
7288
+ const manifest = await fetchManifest(cdnOrigin);
7289
+ const { version, channel, entry } = resolveVersion(manifest, opts);
7290
+ const destDir = product.runtimeDir(version);
7291
+ const setActive = opts.setActive !== false;
7292
+ const protectVersions = [version, ...opts.protectVersions ?? []];
7293
+ pruneLocalRetention({ protectVersions });
7294
+ if (!opts.force && import_node_fs9.default.existsSync(import_node_path9.default.join(destDir, product.installedMarker))) {
7295
+ if (setActive) product.writeActiveRuntime(version);
7296
+ pruneLocalRetention({ protectVersions });
7297
+ return {
7298
+ version,
7299
+ channel,
7300
+ cdnOrigin,
7301
+ runtimeDir: destDir,
7302
+ installed: false,
7303
+ activated: setActive,
7304
+ manifest
7305
+ };
7329
7306
  }
7330
- if (top.kind === "string") {
7331
- if (char === "\\" && closes(i + 1, top.hashes)) {
7332
- const after = i + 1 + top.hashes;
7333
- if (source[after] === "(") {
7334
- stack.push({ kind: "code", parens: 0 });
7335
- i = after + 1;
7336
- } else i = after + 1;
7337
- continue;
7307
+ if (!opts.quiet)
7308
+ process.stderr.write(`${product.id}: downloading runtime ${version}\u2026
7309
+ `);
7310
+ await installVerifiedTarball({
7311
+ url: entry.tarball || tarballUrl(version, cdnOrigin),
7312
+ digest: { algorithm: "sha256", encoding: "hex", value: entry.sha256 },
7313
+ destDir,
7314
+ installedMarker: product.installedMarker,
7315
+ label: `runtime ${version}`
7316
+ });
7317
+ if (setActive) product.writeActiveRuntime(version);
7318
+ pruneLocalRetention({ protectVersions });
7319
+ return {
7320
+ version,
7321
+ channel,
7322
+ cdnOrigin,
7323
+ runtimeDir: destDir,
7324
+ installed: true,
7325
+ activated: setActive,
7326
+ manifest
7327
+ };
7328
+ }
7329
+ async function updateToLatest(opts = {}) {
7330
+ product.ensureHome();
7331
+ pruneLocalRetention({ protectVersions: opts.protectVersions });
7332
+ const cdnOrigin = resolveCdnOrigin(opts.cdnOrigin);
7333
+ const channel = resolveChannel(opts.channel);
7334
+ const pin = resolvePin();
7335
+ if (pin) {
7336
+ const activeVersion2 = product.readActiveRuntime();
7337
+ const pinInstalled = import_node_fs9.default.existsSync(
7338
+ import_node_path9.default.join(product.runtimeDir(pin), product.installedMarker)
7339
+ );
7340
+ if (activeVersion2 === pin && pinInstalled) {
7341
+ return {
7342
+ checked: true,
7343
+ updated: false,
7344
+ reason: `runtime is pinned to ${pin}`,
7345
+ activeVersion: activeVersion2,
7346
+ latestVersion: pin
7347
+ };
7338
7348
  }
7339
- const quote = top.multiline ? '"""' : '"';
7340
- if (source.startsWith(quote, i) && closes(i + quote.length, top.hashes)) {
7341
- stack.pop();
7342
- i += quote.length + top.hashes;
7343
- } else i++;
7344
- continue;
7349
+ const installed2 = await install({
7350
+ version: pin,
7351
+ channel,
7352
+ cdnOrigin,
7353
+ setActive: false,
7354
+ protectVersions: opts.protectVersions
7355
+ });
7356
+ return {
7357
+ checked: true,
7358
+ updated: true,
7359
+ reason: `runtime is pinned to ${pin}`,
7360
+ activeVersion: pin,
7361
+ latestVersion: pin,
7362
+ install: installed2
7363
+ };
7345
7364
  }
7346
- if (top.kind === "regex") {
7347
- if (char === "/" && closes(i + 1, top.hashes)) {
7348
- stack.pop();
7349
- i += 1 + top.hashes;
7350
- } else i++;
7351
- continue;
7365
+ const manifest = await fetchManifest(cdnOrigin);
7366
+ const latestVersion = manifest.channels[channel]?.latest;
7367
+ if (!latestVersion) {
7368
+ return {
7369
+ checked: true,
7370
+ updated: false,
7371
+ reason: `channel '${channel}' has no latest runtime`,
7372
+ activeVersion: product.readActiveRuntime()
7373
+ };
7352
7374
  }
7353
- if (source.startsWith("//", i)) {
7354
- const end = source.indexOf("\n", i);
7355
- i = end === -1 ? source.length : end;
7356
- } else if (source.startsWith("/*", i)) {
7357
- stack.push({ kind: "block", depth: 1 });
7358
- i += 2;
7359
- } else if (char === '"' || char === "#") {
7360
- const hashes = hashesAt(i);
7361
- const at = i + hashes;
7362
- if (source.startsWith('"""', at)) {
7363
- stack.push({ kind: "string", hashes, multiline: true });
7364
- i = at + 3;
7365
- } else if (source[at] === '"') {
7366
- stack.push({ kind: "string", hashes, multiline: false });
7367
- i = at + 1;
7368
- } else if (hashes > 0 && source[at] === "/") {
7369
- stack.push({ kind: "regex", hashes });
7370
- i = at + 1;
7371
- } else {
7372
- if (hashes > 0) tokens.push(at - 1);
7373
- i = Math.max(at, i + 1);
7374
- }
7375
- } else if (char === "{" || char === "}") {
7376
- tokens.push(i);
7377
- i++;
7378
- } else if (char === "(") {
7379
- top.parens++;
7380
- i++;
7381
- } else if (char === ")") {
7382
- if (top.parens === 0 && stack.length > 1) stack.pop();
7383
- else top.parens--;
7384
- i++;
7385
- } else {
7386
- 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;
7387
- if (keyword && !/[\w$]/.test(source[i - 1] ?? "") && !/[\w$]/.test(source[i + keyword.length] ?? "")) {
7388
- tokens.push(i);
7389
- i += keyword.length;
7390
- } else {
7391
- if (char === "@") tokens.push(i);
7392
- i++;
7393
- }
7375
+ const entry = manifest.versions[latestVersion];
7376
+ if (!entry) {
7377
+ return {
7378
+ checked: true,
7379
+ updated: false,
7380
+ reason: `manifest is missing version ${latestVersion}`,
7381
+ activeVersion: product.readActiveRuntime(),
7382
+ latestVersion
7383
+ };
7394
7384
  }
7395
- }
7396
- return { lineStarts: starts, tokens };
7397
- }
7398
- var compiledSource = (file, contents) => file.endsWith(".swift") ? swiftSourceAsIOS(contents) : contents;
7399
- function writeSwiftProject(layout, input, moduleRoot) {
7400
- const distribution = swiftDistributionAt(moduleRoot);
7401
- const targets = distribution && compileTargets(input).length === 0 ? [
7402
- {
7403
- name: "App",
7404
- path: import_node_path9.default.relative(layout.root, layout.sources),
7405
- executable: true,
7406
- languageMode: 5,
7407
- mainActorIsolation: false,
7408
- resources: false
7385
+ const activeVersion = product.readActiveRuntime();
7386
+ const activeDir = activeVersion ? product.runtimeDir(activeVersion) : null;
7387
+ const activeInstalled = activeDir ? import_node_fs9.default.existsSync(import_node_path9.default.join(activeDir, product.installedMarker)) : false;
7388
+ const shouldInstall = !activeVersion || !activeInstalled || compareSemver(latestVersion, activeVersion) > 0;
7389
+ if (!shouldInstall) {
7390
+ return {
7391
+ checked: true,
7392
+ updated: false,
7393
+ reason: "active runtime is current",
7394
+ activeVersion,
7395
+ latestVersion
7396
+ };
7409
7397
  }
7410
- ] : compileTargets(input);
7411
- const files = /* @__PURE__ */ new Map();
7412
- const moduleFiles = `
7413
- // sootsim-swift files ${(0, import_node_crypto4.createHash)("sha256").update(swiftModuleInputFiles(moduleRoot).join("\n")).digest("hex").slice(0, 16)}
7414
- `;
7415
- if (targets.length === 0) {
7416
- for (const [file, contents] of Object.entries(input.files)) {
7417
- if (file === "Package.swift") continue;
7418
- files.set(import_node_path9.default.join(layout.sources, file), compiledSource(file, contents));
7398
+ const installed = await install({
7399
+ version: latestVersion,
7400
+ channel,
7401
+ cdnOrigin,
7402
+ setActive: false,
7403
+ protectVersions: opts.protectVersions
7404
+ });
7405
+ return {
7406
+ checked: true,
7407
+ updated: true,
7408
+ activeVersion: latestVersion,
7409
+ latestVersion,
7410
+ install: installed
7411
+ };
7412
+ }
7413
+ async function checkUpToDate(opts = {}) {
7414
+ const active = product.readActiveRuntime();
7415
+ const pinned = resolvePin();
7416
+ if (pinned) {
7417
+ return { active, latest: pinned, pinned, outdated: active !== pinned };
7419
7418
  }
7420
- let manifest = (0, import_node_fs9.readFileSync)(
7421
- import_node_path9.default.join(moduleRoot, "scripts/contrast-app-Package.swift"),
7422
- "utf8"
7423
- ).replaceAll("__SOOTSIM_SWIFT_PACKAGE__", moduleRoot);
7424
- const optionalProducts = swiftTargetDependencies(input.files, [{ name: "App", path: "." }]).get("App") ?? [];
7425
- if (optionalProducts.length > 0) {
7426
- const product = '.product(name: "SwiftUI", package: "sootsim-swift"),';
7427
- if (!manifest.includes(product))
7428
- throw new Error("Swift app template lost its framework dependency anchor");
7429
- manifest = manifest.replace(
7430
- product,
7431
- [
7432
- product,
7433
- ...optionalProducts.map(
7434
- (name2) => `.product(name: "${name2}", package: "sootsim-swift"),`
7435
- )
7436
- ].join("\n ")
7419
+ try {
7420
+ const manifest = await fetchManifest(
7421
+ resolveCdnOrigin(opts.cdnOrigin),
7422
+ UP_TO_DATE_CHECK_TIMEOUT_MS
7437
7423
  );
7424
+ const channel = resolveChannel(opts.channel);
7425
+ const latest = manifest.channels[channel]?.latest ?? null;
7426
+ const outdated = !!(latest && (!active || compareSemver(latest, active) > 0));
7427
+ return { active, latest, pinned: null, outdated };
7428
+ } catch {
7429
+ return { active, latest: null, pinned: null, outdated: false };
7438
7430
  }
7439
- if (input.oneModule) {
7440
- const product = '.product(name: "CoreLocation", package: "sootsim-swift"),';
7441
- const flags = `"-Osize"${FOUNDATION_IMPLICIT_FLAGS}`;
7442
- if (!manifest.includes(product) || !manifest.includes(flags)) {
7443
- throw new Error(
7444
- "scripts/contrast-app-Package.swift lost the lines the One module links at"
7445
- );
7446
- }
7447
- manifest = manifest.replace(product, `${product}
7448
- ${ONE_PRODUCT},`).replace(flags, `${flags}${ONE_IMPLICIT_FLAGS}`);
7431
+ }
7432
+ function planLocalRetention(opts = {}) {
7433
+ product.ensureHome();
7434
+ const retainVersions = Math.max(
7435
+ 1,
7436
+ Math.floor(opts.retainVersions ?? DEFAULT_LOCAL_RUNTIME_RETENTION_COUNT)
7437
+ );
7438
+ const installed = listInstalledRuntimes(product);
7439
+ const installedSet = new Set(installed);
7440
+ const activeVersion = product.readActiveRuntime();
7441
+ const pinnedVersion = resolvePin();
7442
+ const keep = /* @__PURE__ */ new Set();
7443
+ for (const version of [
7444
+ activeVersion,
7445
+ pinnedVersion,
7446
+ ...opts.protectVersions ?? []
7447
+ ]) {
7448
+ if (version && installedSet.has(version)) keep.add(version);
7449
+ }
7450
+ for (const version of [...installed].reverse()) {
7451
+ if (keep.size >= retainVersions) break;
7452
+ keep.add(version);
7453
+ }
7454
+ const cacheTemplateMarker = "__RUNTIME_VERSION__";
7455
+ const cacheTemplate = runtimeTarballCacheName(product, cacheTemplateMarker);
7456
+ const markerOffset = cacheTemplate.indexOf(cacheTemplateMarker);
7457
+ const cachePrefix = cacheTemplate.slice(0, markerOffset);
7458
+ const cacheSuffix = cacheTemplate.slice(markerOffset + cacheTemplateMarker.length);
7459
+ let removeCacheFiles = [];
7460
+ if (markerOffset >= 0) {
7461
+ try {
7462
+ removeCacheFiles = import_node_fs9.default.readdirSync(product.cacheDir(), { withFileTypes: true }).filter((entry) => {
7463
+ if (!entry.isFile()) return false;
7464
+ const complete = entry.name.startsWith(cachePrefix) && entry.name.endsWith(cacheSuffix);
7465
+ const partial = entry.name.startsWith(cachePrefix) && entry.name.endsWith(`${cacheSuffix}.partial`);
7466
+ return complete || partial;
7467
+ }).map((entry) => import_node_path9.default.join(product.cacheDir(), entry.name)).sort();
7468
+ } catch {
7469
+ }
7449
7470
  }
7450
- if (importsSpriteKit(input.files)) {
7451
- const anchor = '.product(name: "CoreLocation", package: "sootsim-swift"),';
7452
- if (!manifest.includes(anchor))
7453
- throw new Error(
7454
- "scripts/contrast-app-Package.swift lost the line the SpriteKit product links at"
7455
- );
7456
- manifest = manifest.replace(anchor, `${anchor}
7457
- ${SPRITEKIT_PRODUCT},`);
7471
+ return {
7472
+ activeVersion,
7473
+ pinnedVersion,
7474
+ keepVersions: installed.filter((version) => keep.has(version)),
7475
+ removeVersions: installed.filter((version) => !keep.has(version)),
7476
+ removeCacheFiles
7477
+ };
7478
+ }
7479
+ function pruneLocalRetention(opts = {}) {
7480
+ const plan = planLocalRetention(opts);
7481
+ for (const version of plan.removeVersions) {
7482
+ import_node_fs9.default.rmSync(product.runtimeDir(version), { recursive: true, force: true });
7458
7483
  }
7459
- files.set(import_node_path9.default.join(layout.root, "Package.swift"), manifest + moduleFiles);
7460
- } else {
7461
- const base = layout.multi ? layout.root : layout.sources;
7462
- for (const [file, contents] of Object.entries(input.files)) {
7463
- if (file === "Package.swift") continue;
7464
- files.set(import_node_path9.default.join(base, file), compiledSource(file, contents));
7484
+ for (const cacheFile of plan.removeCacheFiles) {
7485
+ import_node_fs9.default.rmSync(cacheFile, { force: true });
7465
7486
  }
7466
- for (const target of targets) {
7467
- if (!target.resources) continue;
7468
- files.set(
7469
- import_node_path9.default.join(layout.root, target.path, "ResourceBundleAccessor.generated.swift"),
7470
- [
7471
- "import Foundation",
7472
- "",
7473
- "extension Foundation.Bundle {",
7474
- " static let module: Bundle = Bundle.main",
7475
- "}",
7476
- ""
7477
- ].join("\n")
7487
+ return plan;
7488
+ }
7489
+ return {
7490
+ product,
7491
+ resolveCdnOrigin,
7492
+ resolveChannel,
7493
+ resolvePin,
7494
+ manifestUrl,
7495
+ tarballUrl,
7496
+ fetchManifest,
7497
+ resolveVersion,
7498
+ install,
7499
+ updateToLatest,
7500
+ checkUpToDate,
7501
+ planLocalRetention,
7502
+ pruneLocalRetention,
7503
+ listInstalled: () => listInstalledRuntimes(product)
7504
+ };
7505
+ }
7506
+ async function installVerifiedTarball(tarball) {
7507
+ const { url, digest, destDir, installedMarker, label } = tarball;
7508
+ const downloadDir = import_node_fs9.default.mkdtempSync(import_node_path9.default.join(import_node_os3.default.tmpdir(), "runtime-delivery-download-"));
7509
+ const archivePath = import_node_path9.default.join(downloadDir, "archive.tar.gz");
7510
+ import_node_fs9.default.mkdirSync(import_node_path9.default.dirname(destDir), { recursive: true });
7511
+ const tmpDir = import_node_fs9.default.mkdtempSync(
7512
+ import_node_path9.default.join(import_node_path9.default.dirname(destDir), `.installing-${import_node_path9.default.basename(destDir)}-`)
7513
+ );
7514
+ try {
7515
+ await downloadToFile(url, archivePath);
7516
+ const actual = await digestFile(archivePath, digest.algorithm, digest.encoding);
7517
+ if (actual !== digest.value) {
7518
+ throw new Error(
7519
+ `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
7478
7520
  );
7479
7521
  }
7480
- files.set(
7481
- import_node_path9.default.join(layout.root, "Package.swift"),
7482
- emitSwiftPackageManifest({
7483
- targets,
7484
- siblings: swiftTargetDependencies(
7485
- input.files,
7486
- layout.multi ? targets : targets.map((target) => ({ ...target, path: "." }))
7487
- ),
7488
- moduleRoot,
7489
- oneModule: input.oneModule,
7490
- spriteKit: importsSpriteKit(input.files),
7491
- distribution: distribution ?? void 0
7492
- }) + moduleFiles
7493
- );
7522
+ await extractTarball(archivePath, tmpDir, tarball.stripComponents ?? 0);
7523
+ if (!import_node_fs9.default.existsSync(import_node_path9.default.join(tmpDir, installedMarker))) {
7524
+ throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
7525
+ }
7526
+ try {
7527
+ import_node_fs9.default.renameSync(tmpDir, destDir);
7528
+ } catch (err) {
7529
+ if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
7530
+ const aside = `${tmpDir}-replaced`;
7531
+ try {
7532
+ import_node_fs9.default.renameSync(destDir, aside);
7533
+ } catch (moveErr) {
7534
+ if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
7535
+ }
7536
+ try {
7537
+ import_node_fs9.default.renameSync(tmpDir, destDir);
7538
+ } catch (landErr) {
7539
+ if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !import_node_fs9.default.existsSync(import_node_path9.default.join(destDir, installedMarker))) {
7540
+ throw landErr;
7541
+ }
7542
+ } finally {
7543
+ import_node_fs9.default.rmSync(aside, { recursive: true, force: true });
7544
+ }
7545
+ }
7546
+ } finally {
7547
+ import_node_fs9.default.rmSync(tmpDir, { recursive: true, force: true });
7548
+ import_node_fs9.default.rmSync(downloadDir, { recursive: true, force: true });
7494
7549
  }
7495
- syncSwiftTree(layout.root, files);
7496
- }
7497
- function streamText(value) {
7498
- if (typeof value === "string") return value.trim();
7499
- if (Buffer.isBuffer(value)) return value.toString("utf8").trim();
7500
- return "";
7501
7550
  }
7502
- function outputOf(error) {
7503
- if (error && typeof error === "object") {
7504
- const streams = [
7505
- streamText(Reflect.get(error, "stdout")),
7506
- streamText(Reflect.get(error, "stderr"))
7507
- ].filter(Boolean);
7508
- if (streams.length > 0) return streams.join("\n");
7509
- }
7510
- return error instanceof Error ? error.message : String(error);
7551
+ function isErrnoCode(err, ...codes) {
7552
+ return err instanceof Error && "code" in err && codes.includes(String(err.code));
7511
7553
  }
7512
- function builtArtifact(layout) {
7513
- const binDir = import_node_path9.default.join(layout.root, ".build", WASM_TRIPLE, "release");
7514
- const manifest = (0, import_node_fs9.readFileSync)(import_node_path9.default.join(layout.root, "Package.swift"), "utf8");
7515
- const executable = swiftManifestTargets(manifest).find((target) => target.executable);
7516
- if (executable === void 0) {
7517
- throw new Error("swift-compile: the written manifest names no executable target");
7554
+ async function downloadToFile(url, destPath) {
7555
+ const res = await fetch(url);
7556
+ if (!res.ok || !res.body) {
7557
+ throw new Error(`download failed: ${res.status} ${res.statusText} (${url})`);
7518
7558
  }
7519
- const file = import_node_path9.default.join(binDir, `${executable.name}.wasm`);
7520
- if (!(0, import_node_fs9.existsSync)(file)) {
7521
- const found = (0, import_node_fs9.existsSync)(binDir) ? (0, import_node_fs9.readdirSync)(binDir).filter((name2) => name2.endsWith(".wasm")).sort() : [];
7522
- throw new Error(
7523
- `swift-compile: the build produced no ${executable.name}.wasm (found: ${found.join(", ") || "none"})`
7559
+ import_node_fs9.default.mkdirSync(import_node_path9.default.dirname(destPath), { recursive: true });
7560
+ const tmp = `${destPath}.partial`;
7561
+ try {
7562
+ await (0, import_promises3.pipeline)(
7563
+ import_node_stream.Readable.fromWeb(res.body),
7564
+ import_node_fs9.default.createWriteStream(tmp)
7524
7565
  );
7566
+ import_node_fs9.default.renameSync(tmp, destPath);
7567
+ } catch (err) {
7568
+ try {
7569
+ import_node_fs9.default.unlinkSync(tmp);
7570
+ } catch {
7571
+ }
7572
+ throw err;
7525
7573
  }
7526
- return file;
7527
- }
7528
- function projectDiagnostic(output, layout) {
7529
- const base = layout.multi ? layout.root : layout.sources;
7530
- const prefix = `${base}${import_node_path9.default.sep}`;
7531
- return output.split("\n").map((line) => line.startsWith(prefix) ? line.slice(prefix.length) : line).join("\n").trim();
7532
7574
  }
7533
- var ROOT_LOCKS = Symbol.for("peachsim.swiftCompile.rootLocks");
7534
- var host = globalThis;
7535
- var rootLocks = host[ROOT_LOCKS] ??= /* @__PURE__ */ new Map();
7536
- function serialize(root, work) {
7537
- const current = rootLocks.get(root) ?? Promise.resolve();
7538
- const next = current.then(work, work);
7539
- rootLocks.set(
7540
- root,
7541
- next.catch(() => {
7542
- })
7543
- );
7544
- return next;
7575
+ function digestFile(filePath, algorithm, encoding) {
7576
+ return new Promise((resolve5, reject) => {
7577
+ const hash = import_node_crypto4.default.createHash(algorithm);
7578
+ const stream = import_node_fs9.default.createReadStream(filePath);
7579
+ stream.on("data", (chunk) => hash.update(chunk));
7580
+ stream.on("error", reject);
7581
+ stream.on("end", () => resolve5(hash.digest(encoding)));
7582
+ });
7545
7583
  }
7546
- function compileSwiftProjectUnit(input, options) {
7547
- (0, import_node_fs9.mkdirSync)(options.buildRoot, { recursive: true });
7548
- const root = (0, import_node_fs9.realpathSync)(options.buildRoot);
7549
- const moduleRoot = import_node_path9.default.resolve(options.moduleRoot);
7550
- const layout = {
7551
- root,
7552
- sources: import_node_path9.default.join(root, "Sources", "App"),
7553
- multi: compileTargets(input).length > 0
7554
- };
7555
- const hash = swiftArtifactHash(input, options.release, moduleRoot);
7556
- return serialize(root, async () => {
7557
- writeSwiftProject(layout, input, moduleRoot);
7558
- const swift = import_node_path9.default.join(options.toolchainBin, "swift");
7559
- if (!(0, import_node_fs9.existsSync)(swift)) {
7560
- throw new Error(
7561
- `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`
7562
- );
7563
- }
7564
- const macroPlugins = await ensureMacroPlugins(moduleRoot, options.toolchainBin);
7565
- const sdk = swiftModuleSdk(moduleRoot).wasmSdkId;
7566
- const icu = swiftIcuAsset(options.toolchainBin, sdk);
7567
- try {
7568
- await run2(
7569
- swift,
7570
- [
7571
- "build",
7572
- "-j",
7573
- BUILD_JOBS,
7574
- "--package-path",
7575
- root,
7576
- "--swift-sdk",
7577
- sdk,
7578
- "-c",
7579
- "release",
7580
- "-Xswiftc",
7581
- "-Osize",
7582
- ...macroPlugins.flatMap((plugin) => [
7583
- "-Xswiftc",
7584
- "-load-plugin-library",
7585
- "-Xswiftc",
7586
- plugin
7587
- ])
7588
- ],
7589
- { env: BUILD_ENV, maxBuffer: 64 * 1024 * 1024, timeout: options.timeoutMs }
7590
- );
7591
- } catch (error) {
7592
- throw new Error(projectDiagnostic(outputOf(error), layout), { cause: error });
7593
- }
7594
- return {
7595
- hash,
7596
- bytes: (0, import_node_fs9.readFileSync)(builtArtifact(layout)),
7597
- icu: await icu
7598
- };
7584
+ function extractTarball(tarPath, destDir, stripComponents) {
7585
+ return new Promise((resolve5, reject) => {
7586
+ const args = ["-xzf", tarPath, "-C", destDir];
7587
+ if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
7588
+ const child = (0, import_node_child_process4.spawn)("tar", args, {
7589
+ stdio: ["ignore", "inherit", "inherit"]
7590
+ });
7591
+ child.on("error", reject);
7592
+ child.on("exit", (code) => {
7593
+ if (code === 0) resolve5();
7594
+ else reject(new Error(`tar exited with code ${code}`));
7595
+ });
7599
7596
  });
7600
7597
  }
7601
7598
 
7599
+ // src/swift-distribution.ts
7600
+ init_home_paths();
7601
+
7602
7602
  // src/swift-distribution.lock.json
7603
7603
  var swift_distribution_lock_default = {
7604
7604
  id: "42c53105b2e06d39",
@@ -8055,7 +8055,7 @@ var MAX_SWIFT_COMPILE_RESOURCE_TOTAL_BYTES = 8 * 1024 * 1024;
8055
8055
  var MAX_SWIFT_COMPILE_IMAGES = 128;
8056
8056
  var MAX_SWIFT_COMPILE_IMAGE_BYTES = 4 * 1024 * 1024;
8057
8057
  var MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES = 16 * 1024 * 1024;
8058
- var SWIFT_HOST_ABI = 15;
8058
+ var SWIFT_HOST_ABI = 16;
8059
8059
  var POLL_INTERVAL_MS = 1500;
8060
8060
  function httpSwiftCompileSubmit(context) {
8061
8061
  const { assetReadToken, authorization, endpoint } = context;
@@ -8738,10 +8738,10 @@ async function collectExpoSwiftSources(appRoot) {
8738
8738
  const resolved = JSON.parse(resolvedText);
8739
8739
  const resolutions = resolved && typeof resolved === "object" ? Reflect.get(resolved, "modules") : null;
8740
8740
  if (!Array.isArray(resolutions)) throw new Error("invalid Expo Apple resolution");
8741
- const files = {};
8742
- const targets = [];
8743
- const classes = [];
8741
+ const units = [];
8742
+ const namespacesSeen = /* @__PURE__ */ new Set();
8744
8743
  let bytes = 0;
8744
+ let fileCount = 0;
8745
8745
  for (const entry of Object.values(search)) {
8746
8746
  if (!entry || typeof entry !== "object")
8747
8747
  throw new Error("invalid Expo autolinking entry");
@@ -8761,9 +8761,11 @@ async function collectExpoSwiftSources(appRoot) {
8761
8761
  `${sourceRoot}: local Expo Swift modules need one Apple Swift module`
8762
8762
  );
8763
8763
  const namespace = namespaces[0];
8764
- if (targets.includes(namespace))
8764
+ if (namespacesSeen.has(namespace))
8765
8765
  throw new Error(`duplicate local Expo Swift module ${namespace}`);
8766
- targets.push(namespace);
8766
+ namespacesSeen.add(namespace);
8767
+ const files = {};
8768
+ const classes = [];
8767
8769
  for (const module2 of modules) {
8768
8770
  const className = module2 && typeof module2 === "object" ? Reflect.get(module2, "class") : null;
8769
8771
  const name2 = module2 && typeof module2 === "object" ? Reflect.get(module2, "name") : null;
@@ -8788,25 +8790,61 @@ async function collectExpoSwiftSources(appRoot) {
8788
8790
  if (!child.name.endsWith(".swift")) continue;
8789
8791
  const size = import_node_fs14.default.statSync(file).size;
8790
8792
  bytes += size;
8791
- if (Object.keys(files).length + 1 > MAX_SWIFT_COMPILE_FILES - 2 || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES)
8793
+ fileCount++;
8794
+ if (fileCount > MAX_SWIFT_COMPILE_FILES - 2 || bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES)
8792
8795
  throw new Error("Expo Swift sources exceed compile service caps");
8793
8796
  files[`Sources/${namespace}/${import_node_path14.default.relative(ios, file).split(import_node_path14.default.sep).join("/")}`] = `#sourceLocation(file: ${JSON.stringify(file)}, line: 1)
8794
8797
  ${import_node_fs14.default.readFileSync(file, "utf8")}`;
8795
8798
  }
8796
8799
  };
8797
8800
  walk(ios);
8798
- }
8799
- if (classes.length === 0) return null;
8800
- files["Package.swift"] = `// swift-tools-version: 6.0
8801
+ const unit = { namespace, classes, files };
8802
+ files[EXPO_SWIFT_ENTRY] = expoEntry([unit]);
8803
+ units.push(unit);
8804
+ }
8805
+ if (units.length === 0) return null;
8806
+ const allFiles = Object.assign(
8807
+ {},
8808
+ ...units.map((unit) => unit.files)
8809
+ );
8810
+ const targets = units.map((unit) => ({
8811
+ name: unit.namespace,
8812
+ path: `Sources/${unit.namespace}`
8813
+ }));
8814
+ const dependencies = swiftTargetDependencies(allFiles, targets);
8815
+ const byNamespace = new Map(units.map((unit) => [unit.namespace, unit]));
8816
+ for (const unit of units) {
8817
+ const included = /* @__PURE__ */ new Set([unit.namespace]);
8818
+ const visit = (namespace) => {
8819
+ for (const dependency of dependencies.get(namespace) ?? []) {
8820
+ if (!byNamespace.has(dependency) || included.has(dependency)) continue;
8821
+ included.add(dependency);
8822
+ visit(dependency);
8823
+ }
8824
+ };
8825
+ visit(unit.namespace);
8826
+ for (const namespace of included) {
8827
+ if (namespace === unit.namespace) continue;
8828
+ const dependency = byNamespace.get(namespace);
8829
+ if (!dependency) throw new Error(`missing local Swift namespace ${namespace}`);
8830
+ for (const [name2, source] of Object.entries(allFiles)) {
8831
+ if (name2.startsWith(`Sources/${namespace}/`)) unit.files[name2] = source;
8832
+ }
8833
+ }
8834
+ unit.files["Package.swift"] = `// swift-tools-version: 6.0
8801
8835
  import PackageDescription
8802
- let package = Package(name: "PeachExpo", targets: [${targets.map((name2) => `.target(name: ${JSON.stringify(name2)}, path: ${JSON.stringify(`Sources/${name2}`)})`).join(", ")}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])
8836
+ let package = Package(name: "PeachExpo", targets: [${[...included].map((name2) => `.target(name: ${JSON.stringify(name2)}, path: ${JSON.stringify(`Sources/${name2}`)})`).join(", ")}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])
8803
8837
  `;
8804
- files[EXPO_SWIFT_ENTRY] = `import SwiftUI
8838
+ }
8839
+ return units;
8840
+ }
8841
+ function expoEntry(units) {
8842
+ return `import SwiftUI
8805
8843
  import ExpoModulesCore
8806
- ${targets.map((name2) => `import ${name2}
8807
- `).join("")}
8844
+ ${units.map((unit) => `import ${unit.namespace}`).join("\n")}
8845
+
8808
8846
  @main struct PeachExpoApp: RNXPackage {
8809
- init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${classes.join(", ")}]) } }
8847
+ init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${units.flatMap((unit) => unit.classes).join(", ")}]) } }
8810
8848
  func view(props: JSON) -> PeachExpoNativeView { PeachExpoNativeView(props: props) }
8811
8849
  }
8812
8850
 
@@ -8816,9 +8854,9 @@ ${targets.map((name2) => `import ${name2}
8816
8854
  PeachExpoRuntime.dispatch(payload, length)
8817
8855
  }
8818
8856
  `;
8819
- return files;
8820
8857
  }
8821
8858
  var compiling = /* @__PURE__ */ new Map();
8859
+ var failedCompilations = /* @__PURE__ */ new Map();
8822
8860
  async function handleExpoSwiftRequest(req, res) {
8823
8861
  const url = new URL(req.url ?? "/", "http://localhost");
8824
8862
  if (!url.pathname.startsWith("/__peach/swift") && url.pathname !== EXPO_SWIFT_ROUTE)
@@ -8850,34 +8888,118 @@ async function handleExpoSwiftRequest(req, res) {
8850
8888
  let pending = compiling.get(root);
8851
8889
  if (!pending) {
8852
8890
  pending = (async () => {
8853
- const files = await collectExpoSwiftSources(root);
8854
- if (!files) return null;
8891
+ const units = await collectExpoSwiftSources(root);
8892
+ if (!units) return null;
8855
8893
  const module2 = await resolveSwiftModule();
8856
- if (!module2) return null;
8894
+ const result = {
8895
+ namespaces: units.map((unit) => unit.namespace),
8896
+ modules: [],
8897
+ failures: []
8898
+ };
8857
8899
  const key = (0, import_node_crypto6.createHash)("sha256").update(import_node_fs14.default.realpathSync(root)).digest("hex");
8858
- const packagePath = import_node_path14.default.join(import_node_os6.default.tmpdir(), "peach-expo-swift", key);
8859
- const sources = import_node_path14.default.join(packagePath, "Sources");
8860
- import_node_fs14.default.rmSync(sources, { recursive: true, force: true });
8861
- import_node_fs14.default.mkdirSync(sources, { recursive: true });
8862
- for (const [name2, content] of Object.entries(files)) {
8863
- const target = import_node_path14.default.join(packagePath, name2);
8864
- import_node_fs14.default.mkdirSync(import_node_path14.default.dirname(target), { recursive: true });
8865
- import_node_fs14.default.writeFileSync(target, content);
8866
- }
8867
- const artifact = await artifactFor(
8868
- projectFor(packagePath),
8869
- EXPO_SWIFT_ENTRY,
8870
- module2.root
8871
- );
8872
8900
  const host2 = req.headers.host;
8873
8901
  if (!host2) throw new Error("Expo Swift request has no host");
8874
8902
  const base = `http://${host2}`;
8875
- return {
8876
- url: `${base}/__peach/swift/${artifact.hash}.wasm`,
8877
- hash: artifact.hash,
8878
- icuUrl: icuUrl(base, artifact),
8879
- rootId: `${key}/Expo`
8880
- };
8903
+ const linked = [];
8904
+ for (const unit of units) {
8905
+ if (!module2) {
8906
+ result.failures.push({
8907
+ namespace: unit.namespace,
8908
+ diagnostic: "No local Swift toolchain or distribution is available"
8909
+ });
8910
+ continue;
8911
+ }
8912
+ try {
8913
+ const packagePath = import_node_path14.default.join(
8914
+ import_node_os6.default.tmpdir(),
8915
+ "peach-expo-swift",
8916
+ key,
8917
+ unit.namespace
8918
+ );
8919
+ syncSwiftTree(
8920
+ packagePath,
8921
+ new Map(
8922
+ Object.entries(unit.files).map(([name2, source]) => [
8923
+ import_node_path14.default.join(packagePath, name2),
8924
+ source
8925
+ ])
8926
+ )
8927
+ );
8928
+ const stamp = sourceStamp(packagePath, module2.root);
8929
+ const failed = failedCompilations.get(packagePath);
8930
+ if (failed?.stamp === stamp) {
8931
+ result.failures.push({
8932
+ namespace: unit.namespace,
8933
+ diagnostic: failed.diagnostic
8934
+ });
8935
+ continue;
8936
+ }
8937
+ failedCompilations.delete(packagePath);
8938
+ await artifactFor(
8939
+ projectFor(packagePath),
8940
+ EXPO_SWIFT_ENTRY,
8941
+ module2.root
8942
+ ).catch((error) => {
8943
+ const diagnostic = error instanceof Error ? error.message : String(error);
8944
+ if (/^.+:\d+(?::\d+)?: error:/m.test(diagnostic) && sourceStamp(packagePath, module2.root) === stamp)
8945
+ failedCompilations.set(packagePath, { stamp, diagnostic });
8946
+ throw error;
8947
+ });
8948
+ linked.push(unit);
8949
+ } catch (error) {
8950
+ result.failures.push({
8951
+ namespace: unit.namespace,
8952
+ diagnostic: error instanceof Error ? error.message : String(error)
8953
+ });
8954
+ }
8955
+ }
8956
+ if (module2 && linked.length) {
8957
+ const files = Object.assign(
8958
+ {},
8959
+ ...linked.map((unit) => unit.files)
8960
+ );
8961
+ files[EXPO_SWIFT_ENTRY] = expoEntry(linked);
8962
+ const targets = [
8963
+ ...new Set(
8964
+ Object.keys(files).flatMap((name2) => {
8965
+ const match = /^Sources\/([^/]+)\//.exec(name2);
8966
+ return match && match[1] !== "PeachExpoApp" ? [match[1]] : [];
8967
+ })
8968
+ )
8969
+ ];
8970
+ files["Package.swift"] = `// swift-tools-version: 6.0
8971
+ import PackageDescription
8972
+ let package = Package(name: "PeachExpo", targets: [${targets.map((name2) => `.target(name: ${JSON.stringify(name2)}, path: ${JSON.stringify(`Sources/${name2}`)})`).join(", ")}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])
8973
+ `;
8974
+ const packagePath = import_node_path14.default.join(
8975
+ import_node_os6.default.tmpdir(),
8976
+ "peach-expo-swift",
8977
+ key,
8978
+ "linked-app"
8979
+ );
8980
+ syncSwiftTree(
8981
+ packagePath,
8982
+ new Map(
8983
+ Object.entries(files).map(([name2, source]) => [
8984
+ import_node_path14.default.join(packagePath, name2),
8985
+ source
8986
+ ])
8987
+ )
8988
+ );
8989
+ const artifact = await artifactFor(
8990
+ projectFor(packagePath),
8991
+ EXPO_SWIFT_ENTRY,
8992
+ module2.root
8993
+ );
8994
+ result.modules.push({
8995
+ namespaces: linked.map((unit) => unit.namespace),
8996
+ url: `${base}/__peach/swift/${artifact.hash}.wasm`,
8997
+ hash: artifact.hash,
8998
+ icuUrl: icuUrl(base, artifact),
8999
+ rootId: `${key}/Expo`
9000
+ });
9001
+ }
9002
+ return result;
8881
9003
  })();
8882
9004
  compiling.set(root, pending);
8883
9005
  }