peachsim 0.1.774 → 0.1.775

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 (74) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/agent-identity.cjs +1 -1
  4. package/dist-lib/agent-sessions.cjs +1 -1
  5. package/dist-lib/attached-projects.cjs +1 -1
  6. package/dist-lib/auth/shared-session.cjs +1 -1
  7. package/dist-lib/backend-origin.cjs +1 -1
  8. package/dist-lib/beta.cjs +1 -1
  9. package/dist-lib/beta.mjs +1 -1
  10. package/dist-lib/bridge-constants.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.mjs +1 -1
  13. package/dist-lib/bridge-contract.cjs +1 -1
  14. package/dist-lib/bridge-contract.mjs +1 -1
  15. package/dist-lib/capture-contract.cjs +1 -1
  16. package/dist-lib/capture-contract.mjs +1 -1
  17. package/dist-lib/cli-constants.cjs +1 -1
  18. package/dist-lib/cloud-contract.cjs +1 -1
  19. package/dist-lib/cloud-contract.mjs +1 -1
  20. package/dist-lib/cloud-test-args.cjs +1 -1
  21. package/dist-lib/cloud-test-args.mjs +1 -1
  22. package/dist-lib/cloud.cjs +1 -1
  23. package/dist-lib/cloud.mjs +1 -1
  24. package/dist-lib/config.cjs +1 -1
  25. package/dist-lib/detox/index.cjs +1 -1
  26. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  27. package/dist-lib/home-paths.cjs +1 -1
  28. package/dist-lib/host/bridge-host.cjs +1768 -799
  29. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  30. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  31. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  32. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  33. package/dist-lib/host/websocket-proxy.cjs +1 -1
  34. package/dist-lib/index.cjs +1 -1
  35. package/dist-lib/jump-to-source-babel.cjs +1 -1
  36. package/dist-lib/jump-to-source-native.cjs +1 -1
  37. package/dist-lib/kotlin-host.cjs +1 -1
  38. package/dist-lib/menu.cjs +1 -1
  39. package/dist-lib/menu.mjs +1 -1
  40. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  41. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  42. package/dist-lib/metro-production-bundle.cjs +1 -1
  43. package/dist-lib/metro-production-bundle.mjs +1 -1
  44. package/dist-lib/metro.cjs +1 -1
  45. package/dist-lib/native-app-identity.cjs +1 -1
  46. package/dist-lib/native-app-identity.mjs +1 -1
  47. package/dist-lib/native-firebase-metadata.cjs +1 -1
  48. package/dist-lib/native-firebase-metadata.mjs +1 -1
  49. package/dist-lib/plist.cjs +1 -1
  50. package/dist-lib/plist.mjs +1 -1
  51. package/dist-lib/profiles.cjs +1 -1
  52. package/dist-lib/public-brand.cjs +1 -1
  53. package/dist-lib/react-native-host-modules.cjs +1 -1
  54. package/dist-lib/react-native-host-modules.mjs +1 -1
  55. package/dist-lib/render-mode.cjs +1 -1
  56. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  57. package/dist-lib/sdk.cjs +1 -1
  58. package/dist-lib/sdk.mjs +1 -1
  59. package/dist-lib/skills.cjs +2136 -1154
  60. package/dist-lib/swift-compile.cjs +45 -15
  61. package/dist-lib/swift-compile.mjs +43 -15
  62. package/dist-lib/swift-package.cjs +1 -1
  63. package/dist-lib/swift-package.mjs +1 -1
  64. package/dist-lib/swift-submit.cjs +1 -1
  65. package/dist-lib/swift-submit.mjs +1 -1
  66. package/dist-lib/swift-toolchain.cjs +1 -1
  67. package/dist-lib/swift.cjs +1 -1
  68. package/dist-lib/vite-swift.cjs +1382 -413
  69. package/dist-lib/vite.cjs +1 -1
  70. package/package.json +1 -1
  71. package/src/swift-compile.ts +56 -18
  72. package/src/swift-host.ts +60 -11
  73. package/src/swift-packages.ts +18 -3
  74. package/src/swift-standins.ts +546 -0
@@ -0,0 +1,546 @@
1
+ // stand-ins for the binary targets an app's swift packages reach. a vendored
2
+ // xcframework holds iOS machine code peach cannot run, but its iOS simulator
3
+ // slice describes its public surface: a swift module's .swiftinterface, or a
4
+ // c module's modulemap and headers. from those this builds, on the compiling
5
+ // host, a source target under the module's own name whose every body traps
6
+ // naming the sdk and the symbol, so the app compiles and links and a call
7
+ // into the sdk fails loudly where it happens. objective-c headers get no
8
+ // stand-in, and the binary target stays missing with its reason.
9
+
10
+ import { execFileSync, spawnSync } from 'node:child_process'
11
+ import { createHash } from 'node:crypto'
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+ import {
16
+ swiftDistributionAt,
17
+ swiftMacroPlugins,
18
+ swiftModuleSdk,
19
+ swiftPeachModules,
20
+ swiftSdkPaths,
21
+ } from './swift-compile'
22
+ import { emitSwiftStandin, type SymbolGraph } from './swift-standin-emit'
23
+ import type { SwiftPackageBinary } from './swift-packages'
24
+
25
+ const TRIPLE = 'wasm32-unknown-wasip1'
26
+ const cacheDir = path.join(os.tmpdir(), 'peach-swift-standins')
27
+
28
+ export interface SwiftStandin {
29
+ /** the module it stands in for, which names its compile target. */
30
+ module: string
31
+ /** the binary target that ships the module. */
32
+ target: string
33
+ /** the target's files, relative to its directory. */
34
+ files: Record<string, string>
35
+ }
36
+
37
+ export interface SwiftStandins {
38
+ standins: SwiftStandin[]
39
+ /** binary targets with no stand-in, and why. */
40
+ gaps: Map<string, string>
41
+ }
42
+
43
+ interface Toolchain {
44
+ moduleRoot: string
45
+ toolchainBin: string
46
+ }
47
+
48
+ function exec(file: string, args: string[], cwd?: string): string {
49
+ return execFileSync(file, args, {
50
+ cwd,
51
+ encoding: 'utf8',
52
+ maxBuffer: 256 * 1024 * 1024,
53
+ stdio: ['ignore', 'pipe', 'pipe'],
54
+ })
55
+ }
56
+
57
+ // what a failed tool printed, cut to its errors.
58
+ function failure(error: unknown): string {
59
+ const output =
60
+ error && typeof error === 'object' && 'stderr' in error
61
+ ? `${String(error.stderr)}\n${'stdout' in error ? String(error.stdout) : ''}`
62
+ : String(error)
63
+ const errors = output
64
+ .split('\n')
65
+ .filter((line) => /\berror:/.test(line))
66
+ .map((line) => line.replace(/^.*?error:\s*/, '').trim())
67
+ return [...new Set(errors)].slice(0, 3).join('; ') || output.trim().slice(0, 400)
68
+ }
69
+
70
+ const key = (...parts: string[]) =>
71
+ createHash('sha256').update(parts.join('\0')).digest('hex').slice(0, 32)
72
+
73
+ // the xcframework a binary target names: a local directory, or a zip (local or
74
+ // remote) unpacked once per archive into the cache.
75
+ function xcframework(binary: SwiftPackageBinary): string {
76
+ if (!binary.url && !binary.dir.endsWith('.zip')) return binary.dir
77
+ const dir = path.join(cacheDir, 'archives', key(binary.url ?? binary.dir))
78
+ if (!fs.existsSync(path.join(dir, '.complete'))) {
79
+ fs.rmSync(dir, { recursive: true, force: true })
80
+ fs.mkdirSync(dir, { recursive: true })
81
+ const archive = path.join(dir, 'archive.zip')
82
+ if (binary.url) exec('curl', ['-fsSL', '--retry', '2', '-o', archive, binary.url])
83
+ else fs.copyFileSync(binary.dir, archive)
84
+ exec('unzip', ['-q', archive, '-d', path.join(dir, 'tree')])
85
+ fs.rmSync(archive)
86
+ fs.writeFileSync(path.join(dir, '.complete'), '')
87
+ }
88
+ const find = (root: string, depth: number): string | null => {
89
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
90
+ if (!entry.isDirectory() || entry.name === '__MACOSX') continue
91
+ const full = path.join(root, entry.name)
92
+ if (entry.name.endsWith('.xcframework')) return full
93
+ const nested = depth > 0 ? find(full, depth - 1) : null
94
+ if (nested) return nested
95
+ }
96
+ return null
97
+ }
98
+ const found = find(path.join(dir, 'tree'), 2)
99
+ if (!found) throw new Error('its archive holds no .xcframework')
100
+ return found
101
+ }
102
+
103
+ const files = (dir: string, test: (name: string) => boolean): string[] =>
104
+ fs.existsSync(dir)
105
+ ? fs
106
+ .readdirSync(dir, { recursive: true, encoding: 'utf8' })
107
+ .filter((file) => test(path.basename(file)))
108
+ .sort()
109
+ : []
110
+
111
+ /** the module surfaces an iOS simulator slice describes. */
112
+ type Surface =
113
+ | { kind: 'swift'; module: string; interface: string }
114
+ | { kind: 'c'; module: string; modulemap: string; headers: string }
115
+
116
+ function surfaces(xcframeworkDir: string): Surface[] {
117
+ const slice = fs
118
+ .readdirSync(xcframeworkDir)
119
+ .filter((name) => /^ios-.+-simulator$/.test(name))
120
+ .sort()[0]
121
+ if (!slice) throw new Error('it has no iOS simulator slice')
122
+ const root = path.join(xcframeworkDir, slice)
123
+ const found: Surface[] = []
124
+ for (const entry of fs.readdirSync(root).sort()) {
125
+ if (!entry.endsWith('.framework')) continue
126
+ const module = entry.slice(0, -'.framework'.length)
127
+ const framework = path.join(root, entry)
128
+ const swiftmodule = path.join(framework, 'Modules', `${module}.swiftmodule`)
129
+ const interfaces = files(
130
+ swiftmodule,
131
+ (name) =>
132
+ name.endsWith('.swiftinterface') &&
133
+ !name.endsWith('.private.swiftinterface') &&
134
+ !name.endsWith('.package.swiftinterface'),
135
+ )
136
+ const chosen =
137
+ interfaces.find((name) => name.startsWith('arm64-')) ?? interfaces[0] ?? null
138
+ if (chosen) {
139
+ found.push({
140
+ kind: 'swift',
141
+ module,
142
+ interface: path.join(swiftmodule, chosen),
143
+ })
144
+ continue
145
+ }
146
+ const modulemap = path.join(framework, 'Modules', 'module.modulemap')
147
+ if (fs.existsSync(modulemap))
148
+ found.push({
149
+ kind: 'c',
150
+ module,
151
+ modulemap,
152
+ headers: path.join(framework, 'Headers'),
153
+ })
154
+ }
155
+ // a library slice (`-library lib.a -headers Headers`) carries its modulemap
156
+ // among its headers, at the top or in a directory of its own
157
+ const headers = path.join(root, 'Headers')
158
+ for (const map of files(headers, (name) => name === 'module.modulemap')) {
159
+ const modulemap = path.join(headers, map)
160
+ const module = /(?:^|\s)module\s+(\w+)/.exec(fs.readFileSync(modulemap, 'utf8'))?.[1]
161
+ if (module) found.push({ kind: 'c', module, modulemap, headers })
162
+ }
163
+ return found
164
+ }
165
+
166
+ // the peach modules an interface imports, compiled for wasm: a distribution
167
+ // ships them; a checkout builds the ones named into its own build directory,
168
+ // with the flags scripts/build.sh uses, so the two share one build.
169
+ function peachModuleDirs(toolchain: Toolchain, imports: string[]): string[] {
170
+ const { moduleRoot, toolchainBin } = toolchain
171
+ if (swiftDistributionAt(moduleRoot)) return [path.join(moduleRoot, 'modules')]
172
+ const peach = new Set(swiftPeachModules(moduleRoot))
173
+ const plugins = swiftMacroPlugins(moduleRoot)
174
+ if (plugins.stale)
175
+ exec('sh', [
176
+ path.join(moduleRoot, 'scripts/build-preview-plugin.sh'),
177
+ toolchainBin,
178
+ plugins.libraries[0]!,
179
+ ])
180
+ for (const target of imports.filter((name) => peach.has(name)))
181
+ exec(
182
+ path.join(toolchainBin, 'swift'),
183
+ [
184
+ 'build',
185
+ '--swift-sdk',
186
+ swiftModuleSdk(moduleRoot).wasmSdkId,
187
+ '-c',
188
+ 'release',
189
+ '--target',
190
+ target,
191
+ '-Xswiftc',
192
+ '-Osize',
193
+ ...plugins.libraries.flatMap((library) => [
194
+ '-Xswiftc',
195
+ '-load-plugin-library',
196
+ '-Xswiftc',
197
+ library,
198
+ ]),
199
+ ],
200
+ moduleRoot,
201
+ )
202
+ return [path.join(moduleRoot, '.build', TRIPLE, 'release', 'Modules')]
203
+ }
204
+
205
+ // an iOS interface read for wasm: its own flags target wasm, and objective-c
206
+ // attributes, which need a runtime wasm swift lacks, come off its
207
+ // declarations; the declarations themselves stay as the vendor wrote them.
208
+ export function swiftInterfaceForWasm(text: string): string {
209
+ return text
210
+ .replace(/^(\/\/ swift-module-flags:.*)$/m, (flags) =>
211
+ flags
212
+ .replace(/-target \S+/, `-target ${TRIPLE}`)
213
+ .replace(/\s-enable-objc-interop\b/, '')
214
+ .replace(/\s-target-variant \S+/, ''),
215
+ )
216
+ .replace(
217
+ /@(?:objc(?:\s*\([^()]*\))?|objcMembers|nonobjc|IBOutlet|IBAction|IBInspectable|IBDesignable|_objcRuntimeName\([^()]*\))(?![\w(])/g,
218
+ '',
219
+ )
220
+ }
221
+
222
+ function swiftStandin(
223
+ surface: Extract<Surface, { kind: 'swift' }>,
224
+ binary: SwiftPackageBinary,
225
+ toolchain: Toolchain,
226
+ work: string,
227
+ ): SwiftStandin {
228
+ const text = swiftInterfaceForWasm(fs.readFileSync(surface.interface, 'utf8'))
229
+ const search = path.join(work, 'interfaces')
230
+ const moduleDir = path.join(search, `${surface.module}.swiftmodule`)
231
+ fs.mkdirSync(moduleDir, { recursive: true })
232
+ fs.writeFileSync(path.join(moduleDir, `${TRIPLE}.swiftinterface`), text)
233
+ const imports = [
234
+ ...text.matchAll(
235
+ /^(?:@_exported[ \t]+)?import[ \t]+(?:(?:struct|class|enum|protocol|typealias|func|var|let)[ \t]+)?(\w+)/gm,
236
+ ),
237
+ ].map((match) => match[1]!)
238
+ const { sysroot, resources } = swiftSdkPaths(
239
+ toolchain.moduleRoot,
240
+ toolchain.toolchainBin,
241
+ )
242
+ const target = ['-target', TRIPLE, '-sdk', sysroot, '-resource-dir', resources]
243
+ const peach = peachModuleDirs(toolchain, imports).flatMap((dir) => ['-I', dir])
244
+ const out = path.join(work, 'graphs')
245
+ fs.mkdirSync(out, { recursive: true })
246
+ exec(path.join(toolchain.toolchainBin, 'swift-symbolgraph-extract'), [
247
+ '-module-name',
248
+ surface.module,
249
+ ...target,
250
+ '-I',
251
+ search,
252
+ ...peach,
253
+ '-minimum-access-level',
254
+ 'public',
255
+ '-skip-synthesized-members',
256
+ '-omit-extension-block-symbols',
257
+ '-output-dir',
258
+ out,
259
+ ])
260
+ const graphs = fs
261
+ .readdirSync(out)
262
+ .filter((name) => name.endsWith('.symbols.json'))
263
+ .sort()
264
+ .map((name): SymbolGraph => JSON.parse(fs.readFileSync(path.join(out, name), 'utf8')))
265
+ // emit, typecheck for wasm against peach's modules, and leave out each
266
+ // declaration the compiler rejects, its error the reason, until the source
267
+ // is clean; a round that removes nothing fails the stand-in
268
+ const omit = new Map<string, string>()
269
+ const plain = new Set<string>()
270
+ const file = path.join(work, `${surface.module}.swift`)
271
+ for (;;) {
272
+ const { source, owners } = emitSwiftStandin(graphs, {
273
+ module: surface.module,
274
+ source: `${binary.target} (${binary.source})`,
275
+ omit,
276
+ plain,
277
+ })
278
+ fs.writeFileSync(file, source)
279
+ const check = spawnSync(
280
+ path.join(toolchain.toolchainBin, 'swiftc'),
281
+ [
282
+ '-typecheck',
283
+ '-parse-as-library',
284
+ '-swift-version',
285
+ '5',
286
+ '-module-name',
287
+ surface.module,
288
+ ...target,
289
+ ...peach,
290
+ file,
291
+ ],
292
+ { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 },
293
+ )
294
+ if (check.status === 0)
295
+ return {
296
+ module: surface.module,
297
+ target: binary.target,
298
+ files: { [`${surface.module}.swift`]: source },
299
+ }
300
+ const before = omit.size + plain.size
301
+ const elsewhere: string[] = []
302
+ for (const match of check.stderr.matchAll(/^(\S+?):(\d+):\d+: error: (.*)$/gm)) {
303
+ const owner = match[1] === file ? owners[Number(match[2]) - 1] : undefined
304
+ if (owner && /does not override any|overrides nothing/.test(match[3]!))
305
+ plain.add(owner)
306
+ else if (owner) omit.set(owner, `rejected by swiftc: ${match[3]}`)
307
+ else elsewhere.push(match[3]!)
308
+ }
309
+ if (omit.size + plain.size === before)
310
+ throw new Error(
311
+ `its generated source does not typecheck: ${elsewhere.slice(0, 3).join('; ') || check.stderr.trim().slice(0, 400)}`,
312
+ )
313
+ }
314
+ }
315
+
316
+ // objective-c needs a runtime and a compiler mode the wasm build lacks.
317
+ const OBJC = /^\s*(?:@interface|@protocol|@class|@import|#import)\b/m
318
+
319
+ // a clang json ast prints a location's file only when it changes, so the
320
+ // file a declaration sits in is the last one printed before it.
321
+ function functionDeclarations(
322
+ ast: unknown,
323
+ headers: ReadonlySet<string>,
324
+ ): { name: string; file: string; begin: number; end: number }[] {
325
+ const found: { name: string; file: string; begin: number; end: number }[] = []
326
+ let file = ''
327
+ const note = (location: unknown) => {
328
+ if (!location || typeof location !== 'object') return
329
+ const expansion = Reflect.get(location, 'expansionLoc')
330
+ const at = expansion && typeof expansion === 'object' ? expansion : location
331
+ const named = Reflect.get(at, 'file')
332
+ if (typeof named === 'string') file = named
333
+ }
334
+ const walk = (node: unknown) => {
335
+ if (Array.isArray(node)) {
336
+ for (const item of node) walk(item)
337
+ return
338
+ }
339
+ if (!node || typeof node !== 'object') return
340
+ for (const [field, value] of Object.entries(node)) {
341
+ if (field === 'loc') note(value)
342
+ else if (field === 'range' && value && typeof value === 'object') {
343
+ note(Reflect.get(value, 'begin'))
344
+ note(Reflect.get(value, 'end'))
345
+ } else if (value && typeof value === 'object') walk(value)
346
+ }
347
+ }
348
+ const top = ast && typeof ast === 'object' ? Reflect.get(ast, 'inner') : null
349
+ for (const decl of Array.isArray(top) ? top : []) {
350
+ note(Reflect.get(decl, 'loc'))
351
+ const declFile = file
352
+ walk(decl)
353
+ if (Reflect.get(decl, 'kind') !== 'FunctionDecl' || !headers.has(declFile)) continue
354
+ if (Reflect.get(decl, 'isImplicit') || Reflect.get(decl, 'storageClass') === 'static')
355
+ continue
356
+ const inner = Reflect.get(decl, 'inner')
357
+ if (
358
+ Array.isArray(inner) &&
359
+ inner.some((child) => Reflect.get(child, 'kind') === 'CompoundStmt')
360
+ )
361
+ continue
362
+ const range = Reflect.get(decl, 'range')
363
+ const offset = (end: 'begin' | 'end') => {
364
+ const at = Reflect.get(range, end)
365
+ const expansion = Reflect.get(at, 'expansionLoc')
366
+ return Number(Reflect.get(expansion ?? at, 'offset'))
367
+ }
368
+ found.push({
369
+ name: String(Reflect.get(decl, 'name')),
370
+ file: declFile,
371
+ begin: offset('begin'),
372
+ end: offset('end'),
373
+ })
374
+ }
375
+ return found
376
+ }
377
+
378
+ function cStandin(
379
+ surface: Extract<Surface, { kind: 'c' }>,
380
+ binary: SwiftPackageBinary,
381
+ toolchain: Toolchain,
382
+ work: string,
383
+ ): SwiftStandin {
384
+ const named = [
385
+ ...fs
386
+ .readFileSync(surface.modulemap, 'utf8')
387
+ .matchAll(/(?:umbrella\s+)?header\s+"([^"]+)"/g),
388
+ ].map((match) => match[1]!)
389
+ const headers = files(surface.headers, (name) => name.endsWith('.h'))
390
+ const texts = new Map(
391
+ headers.map((file) => [
392
+ file,
393
+ fs.readFileSync(path.join(surface.headers, file), 'utf8'),
394
+ ]),
395
+ )
396
+ const objc = headers.find((file) => OBJC.test(texts.get(file)!))
397
+ if (objc) throw new Error(`its header ${objc} is Objective-C`)
398
+ // the module's own headers, under the target's public include directory
399
+ const include = path.join(work, 'include')
400
+ for (const [file, text] of texts) {
401
+ fs.mkdirSync(path.dirname(path.join(include, file)), { recursive: true })
402
+ fs.writeFileSync(path.join(include, file), text)
403
+ }
404
+ const roots = named.length > 0 ? named : headers
405
+ const modulemap = `module ${surface.module} {\n${roots.map((file) => ` header "${file}"\n`).join('')} export *\n}\n`
406
+ const probe = path.join(work, 'declarations.c')
407
+ fs.writeFileSync(probe, roots.map((file) => `#include "${file}"\n`).join(''))
408
+ const { sysroot } = swiftSdkPaths(toolchain.moduleRoot, toolchain.toolchainBin)
409
+ const ast: unknown = JSON.parse(
410
+ exec(path.join(toolchain.toolchainBin, 'clang'), [
411
+ '-target',
412
+ TRIPLE,
413
+ '--sysroot',
414
+ sysroot,
415
+ '-fsyntax-only',
416
+ '-I',
417
+ include,
418
+ '-Xclang',
419
+ '-ast-dump=json',
420
+ probe,
421
+ ]),
422
+ )
423
+ const byPath = new Map(headers.map((file) => [path.join(include, file), file]))
424
+ const declarations = functionDeclarations(ast, new Set(byPath.keys()))
425
+ const seen = new Set<string>()
426
+ const definitions: string[] = []
427
+ for (const { name, file, begin, end } of declarations) {
428
+ if (seen.has(name)) continue
429
+ seen.add(name)
430
+ const text = texts.get(byPath.get(file)!)!
431
+ const close = text.indexOf(';', end)
432
+ if (close < 0)
433
+ throw new Error(`${name} has no declaration end in ${byPath.get(file)}`)
434
+ definitions.push(
435
+ `${text.slice(begin, close).trim()} {\n peach_standin_trap("${name}");\n}\n`,
436
+ )
437
+ }
438
+ const sdk = JSON.stringify(`${binary.target} (${binary.source})`)
439
+ const source = [
440
+ `// generated by peach from ${surface.module}'s headers: ${binary.target} ships`,
441
+ '// iOS machine code only, so every function traps naming itself.',
442
+ ...roots.map((file) => `#include "${file}"`),
443
+ '#include <stdio.h>',
444
+ '#include <stdlib.h>',
445
+ '',
446
+ 'static _Noreturn void peach_standin_trap(const char *symbol) {',
447
+ ` fprintf(stderr, "Peach: %s is a vendored binary framework with no WebAssembly build; ${surface.module}.%s cannot run\\n", ${sdk}, symbol);`,
448
+ ' abort();',
449
+ '}',
450
+ '',
451
+ ...definitions,
452
+ ].join('\n')
453
+ return {
454
+ module: surface.module,
455
+ target: binary.target,
456
+ files: {
457
+ ...Object.fromEntries(
458
+ [...texts].map(([file, text]) => [`include/${file}`, text] as const),
459
+ ),
460
+ 'include/module.modulemap': modulemap,
461
+ [`${surface.module}.c`]: source,
462
+ },
463
+ }
464
+ }
465
+
466
+ const built = new Map<string, SwiftStandin[] | string>()
467
+
468
+ // one binary target's stand-ins, or why it has none, cached by what they are
469
+ // generated from: the slice's surface files and the compiling toolchain.
470
+ function binaryStandins(
471
+ binary: SwiftPackageBinary,
472
+ toolchain: Toolchain,
473
+ ): SwiftStandin[] | string {
474
+ let found: Surface[]
475
+ try {
476
+ found = surfaces(xcframework(binary))
477
+ } catch (error) {
478
+ return error instanceof Error ? error.message : String(error)
479
+ }
480
+ if (found.length === 0)
481
+ return 'its iOS simulator slice has no Swift interface or C modulemap'
482
+ const hash = createHash('sha256').update(
483
+ `standin/v1\0${toolchain.toolchainBin}\0${swiftModuleSdk(toolchain.moduleRoot).wasmSdkId}\0${toolchain.moduleRoot}\0${binary.target}\0${binary.source}\0`,
484
+ )
485
+ for (const surface of found) {
486
+ hash.update(`${surface.kind}\0${surface.module}\0`)
487
+ for (const file of surface.kind === 'swift'
488
+ ? [surface.interface]
489
+ : [
490
+ surface.modulemap,
491
+ ...files(surface.headers, (name) => name.endsWith('.h')).map((file) =>
492
+ path.join(surface.headers, file),
493
+ ),
494
+ ])
495
+ hash.update(fs.readFileSync(file))
496
+ }
497
+ const id = hash.digest('hex').slice(0, 32)
498
+ const memo = built.get(id)
499
+ if (memo) return memo
500
+ const cached = path.join(cacheDir, 'standins', `${id}.json`)
501
+ if (fs.existsSync(cached)) {
502
+ const value: SwiftStandin[] = JSON.parse(fs.readFileSync(cached, 'utf8'))
503
+ built.set(id, value)
504
+ return value
505
+ }
506
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'peach-standin-'))
507
+ let result: SwiftStandin[] | string
508
+ try {
509
+ result = found.map((surface) => {
510
+ const dir = path.join(work, surface.module)
511
+ try {
512
+ return surface.kind === 'swift'
513
+ ? swiftStandin(surface, binary, toolchain, dir)
514
+ : cStandin(surface, binary, toolchain, dir)
515
+ } catch (error) {
516
+ throw new Error(
517
+ `no stand-in for ${surface.module}: ${error instanceof Error && !('stderr' in error) ? error.message : failure(error)}`,
518
+ )
519
+ }
520
+ })
521
+ fs.mkdirSync(path.dirname(cached), { recursive: true })
522
+ fs.writeFileSync(cached, JSON.stringify(result))
523
+ built.set(id, result)
524
+ } catch (error) {
525
+ // a failure is not cached: a fixed peach module or interface retries it
526
+ result = error instanceof Error ? error.message : String(error)
527
+ } finally {
528
+ fs.rmSync(work, { recursive: true, force: true })
529
+ }
530
+ return result
531
+ }
532
+
533
+ /** stand-ins for the binary targets the app reaches, built on this host. */
534
+ export function swiftStandins(
535
+ binaries: readonly SwiftPackageBinary[],
536
+ toolchain: Toolchain,
537
+ ): SwiftStandins {
538
+ const standins: SwiftStandin[] = []
539
+ const gaps = new Map<string, string>()
540
+ for (const binary of binaries) {
541
+ const result = binaryStandins(binary, toolchain)
542
+ if (typeof result === 'string') gaps.set(binary.target, result)
543
+ else standins.push(...result)
544
+ }
545
+ return { standins, gaps }
546
+ }