peachsim 0.1.686 → 0.1.688

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 (116) hide show
  1. package/cli/cloud-client.ts +3 -3
  2. package/cli/command-registry.ts +2 -0
  3. package/cli/commands/control.ts +1 -0
  4. package/cli/commands/debug.ts +10 -33
  5. package/cli/commands/do-chain.ts +56 -6
  6. package/cli/commands/inspect/core.ts +2 -0
  7. package/cli/commands/inspect/list.ts +2 -1
  8. package/cli/commands/inspect/settling.ts +17 -3
  9. package/cli/commands/inspect/shared.ts +2 -0
  10. package/cli/commands/inspect/wait-idle.ts +2 -2
  11. package/cli/commands/inspect/wait-ready.ts +3 -3
  12. package/cli/commands/inspect.ts +33 -7
  13. package/cli/commands/location.ts +164 -0
  14. package/cli/commands/platform.ts +1 -1
  15. package/cli/drivers/playwright-sim-host.ts +46 -25
  16. package/cli/main.ts +6 -0
  17. package/detox/index.ts +13 -8
  18. package/dist-lib/agent-daemon-client.cjs +1 -1
  19. package/dist-lib/agent-events.cjs +1 -1
  20. package/dist-lib/agent-identity.cjs +1 -1
  21. package/dist-lib/agent-sessions.cjs +1 -1
  22. package/dist-lib/attached-projects.cjs +1 -1
  23. package/dist-lib/auth/shared-session.cjs +1 -1
  24. package/dist-lib/backend-origin.cjs +1 -1
  25. package/dist-lib/beta.cjs +1 -1
  26. package/dist-lib/beta.mjs +1 -1
  27. package/dist-lib/bridge-constants.cjs +4 -3
  28. package/dist-lib/bridge-contract-input.cjs +12 -1
  29. package/dist-lib/bridge-contract-input.mjs +12 -1
  30. package/dist-lib/bridge-contract.cjs +4 -3
  31. package/dist-lib/bridge-contract.mjs +4 -3
  32. package/dist-lib/capture-contract.cjs +1 -1
  33. package/dist-lib/capture-contract.mjs +1 -1
  34. package/dist-lib/cli-constants.cjs +1 -1
  35. package/dist-lib/cloud-contract.cjs +2 -1
  36. package/dist-lib/cloud-contract.mjs +2 -1
  37. package/dist-lib/cloud-test-args.cjs +1 -1
  38. package/dist-lib/cloud-test-args.mjs +1 -1
  39. package/dist-lib/cloud.cjs +2 -1
  40. package/dist-lib/cloud.mjs +2 -1
  41. package/dist-lib/config.cjs +1 -1
  42. package/dist-lib/detox/index.cjs +1197 -65
  43. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  44. package/dist-lib/home-paths.cjs +1 -1
  45. package/dist-lib/host/bridge-host.cjs +402 -113
  46. package/dist-lib/host/fetch-proxy-handler.cjs +50 -40
  47. package/dist-lib/host/fetch-proxy-overrides.cjs +50 -6
  48. package/dist-lib/host/fetch-proxy-overrides.mjs +48 -5
  49. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  50. package/dist-lib/host/websocket-proxy.cjs +1 -1
  51. package/dist-lib/index.cjs +29 -11
  52. package/dist-lib/jump-to-source-babel.cjs +1 -1
  53. package/dist-lib/jump-to-source-native.cjs +1 -1
  54. package/dist-lib/kotlin-host.cjs +89 -13
  55. package/dist-lib/menu.cjs +1 -1
  56. package/dist-lib/menu.mjs +1 -1
  57. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  58. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  59. package/dist-lib/metro-production-bundle.cjs +1 -1
  60. package/dist-lib/metro-production-bundle.mjs +1 -1
  61. package/dist-lib/metro.cjs +5 -3
  62. package/dist-lib/native-app-identity.cjs +8 -3
  63. package/dist-lib/native-app-identity.mjs +8 -3
  64. package/dist-lib/native-firebase-metadata.cjs +1 -1
  65. package/dist-lib/native-firebase-metadata.mjs +1 -1
  66. package/dist-lib/plist.cjs +1 -1
  67. package/dist-lib/plist.mjs +1 -1
  68. package/dist-lib/profiles.cjs +1 -1
  69. package/dist-lib/public-brand.cjs +1 -1
  70. package/dist-lib/react-native-host-modules.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.mjs +1 -1
  72. package/dist-lib/render-mode.cjs +1 -1
  73. package/dist-lib/scripts/dev-server-scanner.cjs +2 -2
  74. package/dist-lib/sdk.cjs +21 -6
  75. package/dist-lib/sdk.mjs +21 -6
  76. package/dist-lib/skills.cjs +441 -135
  77. package/dist-lib/swift-compile.cjs +317 -27
  78. package/dist-lib/swift-compile.mjs +315 -27
  79. package/dist-lib/swift-package.cjs +1 -1
  80. package/dist-lib/swift-package.mjs +1 -1
  81. package/dist-lib/swift-submit.cjs +2 -2
  82. package/dist-lib/swift-submit.mjs +2 -2
  83. package/dist-lib/swift-toolchain.cjs +10 -10
  84. package/dist-lib/swift.cjs +1 -1
  85. package/dist-lib/vite-swift.cjs +320 -49
  86. package/dist-lib/vite.cjs +1 -1
  87. package/kotlin/AppSources/android/content/res/Configuration.kt +2 -0
  88. package/kotlin/AppSources/android/content/res/Resources.kt +6 -3
  89. package/kotlin/AppSources/android/util/DisplayMetrics.kt +12 -0
  90. package/kotlin/AppSources/androidx/compose/ui/res/PainterResources.kt +70 -0
  91. package/kotlin/AppSources/dev/peach/app/PeachApp.kt +12 -10
  92. package/kotlin/AppSources/dev/peach/app/PeachDrawable.kt +95 -0
  93. package/kotlin/fixtures/kotlin-app-variants/Bitmaps.kt +50 -0
  94. package/kotlin/fixtures/kotlin-app-variants/Drawables.kt +53 -0
  95. package/package.json +2 -2
  96. package/scripts/dev-server-scanner.ts +3 -1
  97. package/skills/contrast/SKILL.md +1 -0
  98. package/src/android-drawables.ts +315 -0
  99. package/src/android-theme.ts +9 -0
  100. package/src/bridge-constants.ts +3 -2
  101. package/src/bridge-contract-input.ts +11 -0
  102. package/src/bridge-contract.ts +45 -3
  103. package/src/cloud-contract.ts +1 -0
  104. package/src/host/fetch-proxy-handler.ts +13 -49
  105. package/src/host/fetch-proxy-overrides.ts +69 -12
  106. package/src/kotlin-app.ts +6 -0
  107. package/src/kotlin-host.ts +103 -15
  108. package/src/native-app-identity.ts +16 -3
  109. package/src/swift-compile.ts +426 -29
  110. package/src/swift-distribution-contract.ts +11 -4
  111. package/src/swift-distribution.lock.json +11 -9
  112. package/src/swift-distribution.ts +4 -4
  113. package/src/swift-icu.ts +8 -11
  114. package/src/swift-submit.ts +13 -1
  115. package/src/swift-toolchain.ts +17 -9
  116. package/src/vite-plugin.ts +86 -34
@@ -1,6 +1,7 @@
1
1
  import { execFile } from 'node:child_process'
2
2
  import { createHash } from 'node:crypto'
3
3
  import {
4
+ cpSync,
4
5
  existsSync,
5
6
  mkdirSync,
6
7
  readFileSync,
@@ -25,6 +26,7 @@ import {
25
26
  type SwiftPackageTarget,
26
27
  } from './swift-package'
27
28
  import type { SwiftImageUpload } from './swift-submit'
29
+ import type { SwiftWasmSdk } from './swift-toolchain'
28
30
 
29
31
  export { swiftIcuAsset, type SwiftIcuAsset }
30
32
 
@@ -85,6 +87,27 @@ export function swiftDistributionAt(root: string): SwiftDistributionManifest | n
85
87
  return parseSwiftDistributionManifest(JSON.parse(readFileSync(file, 'utf8')))
86
88
  }
87
89
 
90
+ /** the wasm SDK a module root compiles with: a distribution's manifest names
91
+ * it, a source checkout's toolchain.json pins it. */
92
+ export function swiftModuleSdk(root: string): SwiftWasmSdk {
93
+ const pin: unknown =
94
+ swiftDistributionAt(root) ??
95
+ JSON.parse(readFileSync(path.join(root, 'toolchain.json'), 'utf8'))
96
+ if (
97
+ !pin ||
98
+ typeof pin !== 'object' ||
99
+ typeof Reflect.get(pin, 'wasmSdkId') !== 'string' ||
100
+ typeof Reflect.get(pin, 'wasmSdkUrl') !== 'string' ||
101
+ typeof Reflect.get(pin, 'wasmSdkChecksum') !== 'string'
102
+ )
103
+ throw new Error(`${root} pins no wasm SDK id, url and checksum`)
104
+ return {
105
+ wasmSdkId: String(Reflect.get(pin, 'wasmSdkId')),
106
+ wasmSdkUrl: String(Reflect.get(pin, 'wasmSdkUrl')),
107
+ wasmSdkChecksum: String(Reflect.get(pin, 'wasmSdkChecksum')),
108
+ }
109
+ }
110
+
88
111
  // toolchain.json is an input for its wasm sdk checksum: the sdk's icu blob,
89
112
  // which the host fills into every artifact, is part of what the address names.
90
113
  // a distribution's manifest names every file it ships by digest.
@@ -99,7 +122,7 @@ export function swiftModuleInputFiles(root: string): string[] {
99
122
  for (const entry of readdirSync(path.join(root, dir), { withFileTypes: true })) {
100
123
  const relative = `${dir}/${entry.name}`
101
124
  if (entry.isDirectory()) walk(relative)
102
- else if (/\.(swift|c|h)$/.test(entry.name)) files.push(relative)
125
+ else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative)
103
126
  }
104
127
  }
105
128
  walk('Sources')
@@ -212,17 +235,41 @@ export function withNativeSourceGlue(
212
235
  }
213
236
  }
214
237
 
215
- function swiftSiblingDependencies(
238
+ // optional families link only into an app whose sources import them, each
239
+ // with the optional families it depends on (packages/sootsim-swift/Package.swift).
240
+ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
241
+ Accelerate: [],
242
+ CryptoKit: [],
243
+ Security: [],
244
+ Statsig: [],
245
+ DatadogCore: [],
246
+ DatadogLogs: ['DatadogCore'],
247
+ DatadogRUM: ['DatadogCore'],
248
+ DatadogTrace: ['DatadogCore'],
249
+ }
250
+ const OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES))
251
+
252
+ export function swiftTargetDependencies(
216
253
  files: Record<string, string>,
217
- targets: SwiftPackageTarget[],
254
+ targets: Pick<SwiftPackageTarget, 'name' | 'path'>[],
218
255
  ): Map<string, string[]> {
219
- const names = new Set(targets.map((target) => target.name))
256
+ const names = new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)])
220
257
  const siblings = new Map<string, string[]>()
221
258
  for (const target of targets) {
222
- const prefix = `${target.path}/`
259
+ const prefix = target.path === '.' ? '' : `${target.path}/`
223
260
  const deps = new Set<string>()
224
261
  for (const [file, contents] of Object.entries(files)) {
225
262
  if (file === 'Package.swift' || !file.startsWith(prefix)) continue
263
+ if (
264
+ targets.some(
265
+ (candidate) =>
266
+ candidate.name !== target.name &&
267
+ candidate.path !== '.' &&
268
+ candidate.path.startsWith(prefix) &&
269
+ file.startsWith(`${candidate.path}/`),
270
+ )
271
+ )
272
+ continue
226
273
  // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
227
274
  // declaration kind (`import struct Nuke.ImageRequest`).
228
275
  for (const match of contents.matchAll(
@@ -248,15 +295,19 @@ const importsSpriteKit = (files: Record<string, string>): boolean =>
248
295
  contents,
249
296
  ),
250
297
  )
251
- // every iOS source sees the ObjectiveC module's selectors through Foundation;
252
- // PeachObjC stands in for it, so a source that imports only Foundation still
253
- // compiles `@objc` and `#selector`. scripts/contrast-app-Package.swift and
298
+ // every iOS source sees through Foundation what darwin's Foundation exports:
299
+ // PeachObjC supplies the ObjectiveC module's selectors, Dispatch Foundation's
300
+ // Darwin queue exports, and FoundationNetworking (re-exporting PeachFoundation)
301
+ // URLSession, NotificationCenter, OperationQueue and the CoreFoundation types.
302
+ // these modules export only names iOS has; Peach's host plumbing is `package`
303
+ // or lives in PeachJSON, which none of them re-exports. scripts/contrast-app-Package.swift and
254
304
  // example/Package.swift carry the same flags.
255
- const OBJC_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC"'
305
+ const FOUNDATION_IMPLICIT_FLAGS =
306
+ ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"'
256
307
  const ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"'
257
308
 
258
309
  /** bump with any change to the emitted multi-target manifest text. */
259
- export const MULTI_MANIFEST_VERSION = 7
310
+ export const MULTI_MANIFEST_VERSION = 10
260
311
 
261
312
  export function swiftArtifactHash(
262
313
  input: SwiftCompileInput,
@@ -264,11 +315,15 @@ export function swiftArtifactHash(
264
315
  moduleRoot: string,
265
316
  ): string {
266
317
  const hash = createHash('sha256')
318
+ // v12: overrides in an extension of a same-file class lift into the class
319
+ // v10: Foundation-only sources see Dispatch queues
320
+ // v9: table cell and header footer view initializers compile required
321
+ // v8: optional framework products and distribution objects link on import
267
322
  // v7: runtime class lookup uses the same objc class registry as messages
268
323
  // v6: app and scene delegate classes compile final
269
324
  // (v5: a target declaring resources gets SwiftPM's Bundle.module accessor;
270
325
  // v4: sources compile through swiftSourceAsIOS)
271
- hash.update(`swift-compile/v7\n${release}\n`)
326
+ hash.update(`swift-compile/v12\n${release}\n`)
272
327
  if (input.oneModule) hash.update('one-module\n')
273
328
  hash.update(swiftModuleDigest(moduleRoot))
274
329
  for (const file of Object.keys(input.files).sort()) {
@@ -296,7 +351,7 @@ export function swiftArtifactHash(
296
351
  hash.update(
297
352
  JSON.stringify({
298
353
  targets,
299
- siblings: [...swiftSiblingDependencies(input.files, targets)].sort((a, b) =>
354
+ siblings: [...swiftTargetDependencies(input.files, targets)].sort((a, b) =>
300
355
  String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0,
301
356
  ),
302
357
  }),
@@ -315,6 +370,23 @@ export function emitSwiftPackageManifest(args: {
315
370
  distribution?: SwiftDistributionManifest
316
371
  }): string {
317
372
  const { targets, siblings, moduleRoot, oneModule, spriteKit, distribution } = args
373
+ const reachedFrameworks = new Set(
374
+ [...siblings.values()]
375
+ .flat()
376
+ .filter(
377
+ (name) =>
378
+ OPTIONAL_FRAMEWORKS.has(name) &&
379
+ !targets.some((target) => target.name === name),
380
+ )
381
+ .flatMap((name) => [name, ...(OPTIONAL_FRAMEWORK_DEPENDENCIES[name] ?? [])]),
382
+ )
383
+ // the distribution builder names each object lib/<target>-<file>.o.
384
+ // preserve link order while leaving unreached optional module objects out.
385
+ const distributionObjects = distribution?.objects.filter((object) =>
386
+ [...OPTIONAL_FRAMEWORKS].every(
387
+ (name) => !object.startsWith(`lib/${name}-`) || reachedFrameworks.has(name),
388
+ ),
389
+ )
318
390
  const executable = targets.find((target) => target.executable)
319
391
  if (!executable) throw new Error('swift-compile: no executable target to emit')
320
392
  // each target compiles in the language mode and default isolation its
@@ -334,7 +406,7 @@ export function emitSwiftPackageManifest(args: {
334
406
  const imports = distribution
335
407
  ? `, "-I", ${JSON.stringify(path.join(moduleRoot, 'modules'))}`
336
408
  : ''
337
- const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${OBJC_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ''}${imports}])]`
409
+ const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${FOUNDATION_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ''}${imports}])]`
338
410
  const deps = [
339
411
  ...(distribution
340
412
  ? []
@@ -343,11 +415,18 @@ export function emitSwiftPackageManifest(args: {
343
415
  ...(oneModule ? [ONE_PRODUCT] : []),
344
416
  ...(spriteKit ? [SPRITEKIT_PRODUCT] : []),
345
417
  ]),
346
- ...(siblings.get(target.name) ?? []).map((sibling) => `"${sibling}"`),
418
+ ...(siblings.get(target.name) ?? []).flatMap((dependency) =>
419
+ OPTIONAL_FRAMEWORKS.has(dependency) &&
420
+ !targets.some((candidate) => candidate.name === dependency)
421
+ ? distribution
422
+ ? []
423
+ : [`.product(name: "${dependency}", package: "sootsim-swift")`]
424
+ : [`"${dependency}"`],
425
+ ),
347
426
  ].join(', ')
348
427
  const library = distribution
349
428
  ? [
350
- ...distribution.objects.map((object) => path.join(moduleRoot, object)),
429
+ ...(distributionObjects ?? []).map((object) => path.join(moduleRoot, object)),
351
430
  ...distribution.link,
352
431
  ]
353
432
  .map((flag) => `, ${JSON.stringify(flag)}`)
@@ -425,12 +504,18 @@ function syncSwiftTree(base: string, files: Map<string, string>): void {
425
504
  // `@objcMembers` `@ObjCMembers`, `@IBAction` `@ObjC` padded, and `#selector(`
426
505
  // `#Selector(`: the module's macros that expose a method to selector dispatch
427
506
  // (plans/peach/uikit-shell.md, gate B). all keep their width except an
428
- // explicit `@objc(name:)`, whose name becomes a string argument, and a
429
- // delegate class that becomes final (below).
507
+ // explicit `@objc(name:)` on a member, whose name becomes a string argument,
508
+ // and a delegate class that becomes final (below).
430
509
  const DIRECTIVE = /^[ \t]*#(?:if|elseif)\b/
431
510
  const OS_IOS = /\bos\(\s*iOS\s*\)/g
432
511
  const OBJC_ATTRIBUTE = /^@(?:objcMembers\b|objc\b(?:(\s*)\(([^()]*)\))?|IBAction\b)/
433
512
  const SELECTOR = /^#selector\b/
513
+ // `@objc` on a type exposes no selector here, and Swift rejects a peer macro
514
+ // that names arbitrary peers on a global declaration, so on a type it becomes
515
+ // blanks of its width; comments may sit between the attribute and the type.
516
+ // `class func` and `class var` are methods.
517
+ const TYPE_AFTER_ATTRIBUTE =
518
+ /^(?:\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/
434
519
  // uikit makes app and scene delegates from their class through the objc
435
520
  // runtime; here their protocols require init(), which a non-final class
436
521
  // meets only with a required one. a class declaring one of them that is
@@ -438,7 +523,233 @@ const SELECTOR = /^#selector\b/
438
523
  // compile naming itself.
439
524
  const DELEGATE_CLASS =
440
525
  /^class\s+[A-Za-z_]\w*\s*(?:<[^>{]*>)?\s*:[^{]*\b(?:UIApplicationDelegate|UISceneDelegate|UIWindowSceneDelegate)\b[^{]*\{/
441
- export function swiftSourceAsIOS(source: string): string {
526
+ // a table makes its cells and header footer views from their class, which
527
+ // here needs the initializer it calls to be required. a subclass's override
528
+ // of it says `required`, the same width: the cell's
529
+ // init(style:reuseIdentifier:) and the header footer view's
530
+ // init(reuseIdentifier:).
531
+ const REUSABLE_INIT =
532
+ /^override(?=\s+init\s*\(\s*(?:style\s*:[^,)]*,\s*reuseIdentifier|reuseIdentifier)\s*:)/
533
+ // a collection view makes its cells and supplementary views with
534
+ // init(frame:), so inside a class that inherits from one, directly or
535
+ // through a class declared earlier in the file, an override of it says
536
+ // `required` too. a class whose base is declared in another file is not
537
+ // seen and fails to compile.
538
+ const REUSABLE_VIEW_BASES = [
539
+ 'UICollectionReusableView',
540
+ 'UICollectionViewCell',
541
+ 'UICollectionViewListCell',
542
+ ]
543
+ const CLASS_BASE =
544
+ /^class\s+([A-Za-z_]\w*)\s*(?:<[^>{]*>)?\s*:\s*([A-Za-z_][\w.]*)[^{]*\{/
545
+ const FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/
546
+ // uikit's members are @objc, so an app may override one from an extension;
547
+ // swift without an objc runtime rejects that. an `override` of an @objc
548
+ // member (overridesObjC below) that is a direct member of an extension of a
549
+ // class declared in the same file is lifted: the extension keeps it as `__peach_ext_<name>` with `override`
550
+ // blanked, and the class body gains, on its opening brace's line, an
551
+ // override that forwards to it, so lines keep their numbers and the
552
+ // override takes its place in the class as an objc one does. a class in
553
+ // another file, a property with a setter or observers, a subscript and a
554
+ // variadic parameter stay as written and fail to compile as before.
555
+ // an Apple framework class: an ObjC prefix and a capital
556
+ const APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/
557
+ const EXTENSION_DECL = /^extension\s+([A-Za-z_][\w.]*)/
558
+ const CLASS_DECL = /^class\s+(?!(?:func|var|let|subscript)\b)([A-Za-z_]\w*)/
559
+ const MODIFIERS =
560
+ /(?:^|\s)(public|open|internal|fileprivate|private|final|nonisolated|@MainActor)(?=\s)/g
561
+ const OVERRIDE_FUNC =
562
+ /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+func\s+([A-Za-z_]\w*)\s*(<[^>{}]*>)?\s*\(/
563
+ const OVERRIDE_VAR =
564
+ /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+var\s+([A-Za-z_]\w*)\s*:\s*([^{=]+?)\s*\{/
565
+
566
+ function splitTopLevel(text: string): string[] {
567
+ const parts: string[] = []
568
+ let depth = 0
569
+ let start = 0
570
+ for (let i = 0; i < text.length; i++) {
571
+ const char = text[i]
572
+ if (char === '(' || char === '[' || char === '<') depth++
573
+ else if (char === ')' || char === ']' || (char === '>' && text[i - 1] !== '-'))
574
+ depth--
575
+ else if (char === ',' && depth === 0) {
576
+ parts.push(text.slice(start, i))
577
+ start = i + 1
578
+ }
579
+ }
580
+ parts.push(text.slice(start))
581
+ return parts.map((part) => part.trim()).filter((part) => part !== '')
582
+ }
583
+
584
+ // the call that forwards a parameter list, or null when one cannot forward
585
+ function forwardedArguments(parameters: string): string | null {
586
+ const args: string[] = []
587
+ for (const parameter of splitTopLevel(parameters)) {
588
+ const match = /^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([\s\S]*)$/.exec(parameter)
589
+ if (!match || match[3]!.includes('...')) return null
590
+ const label = match[1] ?? match[2]!
591
+ const value = (/^(?:@\w+\s+)*inout\b/.test(match[3]!) ? '&' : '') + match[2]!
592
+ args.push(label === '_' ? value : `${label}: ${value}`)
593
+ }
594
+ return args.join(', ')
595
+ }
596
+
597
+ function liftExtensionOverrides(source: string): string {
598
+ const { tokens } = swiftCodeScan(source)
599
+ type Frame = { kind: 'class' | 'extension' | 'other'; name: string }
600
+ const stack: Frame[] = []
601
+ let pending: Frame | null = null
602
+ const classes = new Map<
603
+ string,
604
+ { brace: number; base: string | null; objcMembers: boolean }
605
+ >()
606
+ let declaredBase: string | null = null
607
+ let declaredObjCMembers = false
608
+ const lifted: {
609
+ type: string
610
+ member: string
611
+ stub: string
612
+ edits: [number, number, string][]
613
+ }[] = []
614
+ // the offset just past the brace that closes the one at `open`
615
+ const closing = (open: number): number => {
616
+ let depth = 0
617
+ for (const at of tokens) {
618
+ if (at < open) continue
619
+ if (source[at] === '{') depth++
620
+ else if (source[at] === '}' && --depth === 0) return at + 1
621
+ }
622
+ return source.length
623
+ }
624
+ for (const at of tokens) {
625
+ const rest = source.slice(at, at + 600)
626
+ if (rest.startsWith('{')) {
627
+ const frame = pending ?? { kind: 'other', name: '' }
628
+ if (frame.kind === 'class' && !classes.has(frame.name))
629
+ classes.set(frame.name, {
630
+ brace: at,
631
+ base: declaredBase,
632
+ objcMembers: declaredObjCMembers,
633
+ })
634
+ stack.push(frame)
635
+ pending = null
636
+ continue
637
+ }
638
+ if (rest.startsWith('}')) {
639
+ stack.pop()
640
+ continue
641
+ }
642
+ const declared = CLASS_DECL.exec(rest)
643
+ if (declared) {
644
+ pending = { kind: 'class', name: declared[1]! }
645
+ declaredBase = CLASS_BASE.exec(rest)?.[2]?.split('.').pop() ?? null
646
+ const lines = source.lastIndexOf('\n', source.lastIndexOf('\n', at - 1) - 1) + 1
647
+ declaredObjCMembers = /@objcMembers\b/.test(source.slice(lines, at))
648
+ continue
649
+ }
650
+ const extended = EXTENSION_DECL.exec(rest)
651
+ if (extended) {
652
+ pending = { kind: 'extension', name: extended[1]!.split('.').pop()! }
653
+ continue
654
+ }
655
+ const top = stack.at(-1)
656
+ if (!rest.startsWith('override') || top?.kind !== 'extension' || pending) continue
657
+ const line = source.slice(source.lastIndexOf('\n', at - 1) + 1, at)
658
+ const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim())
659
+ const func = OVERRIDE_FUNC.exec(rest)
660
+ if (func) {
661
+ const name = func[2]!
662
+ const open = at + func[0].length - 1
663
+ let depth = 0
664
+ let close = open
665
+ for (; close < source.length; close++) {
666
+ if (source[close] === '(') depth++
667
+ else if (source[close] === ')' && --depth === 0) break
668
+ }
669
+ const body = tokens.find((token) => token > close && source[token] === '{')
670
+ if (body === undefined) continue
671
+ const clause = source.slice(close + 1, body).trim()
672
+ const args = forwardedArguments(source.slice(open + 1, close))
673
+ if (args === null) continue
674
+ const call =
675
+ (clause.includes('->') ? 'return ' : '') +
676
+ (/\b(?:throws|rethrows)\b/.test(clause) ? 'try ' : '') +
677
+ (/\basync\b/.test(clause) ? 'await ' : '') +
678
+ `__peach_ext_${name}(${args})`
679
+ const signature = `func ${name}${func[3] ?? ''}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ''}`
680
+ lifted.push({
681
+ type: top.name,
682
+ member: name,
683
+ stub: `${[...modifiers, 'override'].join(' ')} ${signature} { ${call} };`,
684
+ edits: [
685
+ [at, 'override'.length, ' '.repeat('override'.length)],
686
+ [
687
+ at +
688
+ rest.indexOf(
689
+ name,
690
+ rest.indexOf('func', 'override'.length + func[1]!.length) + 4,
691
+ ),
692
+ 0,
693
+ '__peach_ext_',
694
+ ],
695
+ ],
696
+ })
697
+ continue
698
+ }
699
+ const property = OVERRIDE_VAR.exec(rest)
700
+ if (property) {
701
+ const open = at + property[0].length - 1
702
+ if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue
703
+ const name = property[2]!
704
+ lifted.push({
705
+ type: top.name,
706
+ member: name,
707
+ stub: `${[...modifiers, 'override'].join(' ')} var ${name}: ${property[3]!.trim()} { __peach_ext_${name} };`,
708
+ edits: [
709
+ [at, 'override'.length, ' '.repeat('override'.length)],
710
+ [at + rest.indexOf(name, rest.indexOf('var')), 0, '__peach_ext_'],
711
+ ],
712
+ })
713
+ }
714
+ }
715
+ // whether the member a class inherits is @objc, as an extension override
716
+ // needs on iOS: an Apple framework class's members are, and an app class
717
+ // in this file declares it with @objc or under @objcMembers. a base this
718
+ // file does not declare, or a plain Swift member, is not, and the override
719
+ // stays to fail as it does on iOS.
720
+ const overridesObjC = (type: string, member: string): boolean => {
721
+ let base = classes.get(type)?.base ?? null
722
+ while (base !== null) {
723
+ if (APPLE_CLASS.test(base)) return true
724
+ const declaredClass = classes.get(base)
725
+ if (!declaredClass) return false
726
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace))
727
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body)
728
+ if (found) {
729
+ const line = body.slice(body.lastIndexOf('\n', found.index) + 1, found.index)
730
+ return declaredClass.objcMembers || /@objc\b/.test(line)
731
+ }
732
+ base = declaredClass.base
733
+ }
734
+ return false
735
+ }
736
+ const edits: [number, number, string][] = []
737
+ const stubs = new Map<number, string[]>()
738
+ for (const entry of lifted) {
739
+ const brace = classes.get(entry.type)?.brace
740
+ if (brace === undefined || !overridesObjC(entry.type, entry.member)) continue
741
+ edits.push(...entry.edits)
742
+ stubs.set(brace, [...(stubs.get(brace) ?? []), entry.stub])
743
+ }
744
+ for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(' ')}`])
745
+ let out = source
746
+ for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
747
+ out = out.slice(0, at) + insert + out.slice(at + remove)
748
+ return out
749
+ }
750
+
751
+ export function swiftSourceAsIOS(original: string): string {
752
+ const source = liftExtensionOverrides(original)
442
753
  const { lineStarts, tokens } = swiftCodeScan(source)
443
754
  let offset = 0
444
755
  // equal width, so every token offset still holds
@@ -453,8 +764,34 @@ export function swiftSourceAsIOS(source: string): string {
453
764
  .join('\n')
454
765
  let out = ''
455
766
  let copied = 0
767
+ const reusableViews = new Set(REUSABLE_VIEW_BASES)
768
+ // the brace depth of each open reusable view class's body
769
+ const reusableBodies: number[] = []
770
+ let depth = 0
771
+ let opensReusableBody = false
456
772
  for (const at of tokens) {
457
773
  const rest = conditioned.slice(at, at + 400)
774
+ if (rest.startsWith('{')) {
775
+ depth++
776
+ if (opensReusableBody) reusableBodies.push(depth)
777
+ opensReusableBody = false
778
+ continue
779
+ }
780
+ if (rest.startsWith('}')) {
781
+ if (reusableBodies.at(-1) === depth) reusableBodies.pop()
782
+ depth--
783
+ continue
784
+ }
785
+ if (rest.startsWith('override')) {
786
+ if (
787
+ REUSABLE_INIT.test(rest) ||
788
+ (reusableBodies.at(-1) === depth && FRAME_INIT.test(rest))
789
+ ) {
790
+ out += `${conditioned.slice(copied, at)}required`
791
+ copied = at + 'override'.length
792
+ }
793
+ continue
794
+ }
458
795
  const imported = /^import\s+CoreImage\.CIFilterBuiltins\b/.exec(rest)
459
796
  if (imported) {
460
797
  out += conditioned.slice(copied, at) + 'import CoreImage'.padEnd(imported[0].length)
@@ -467,6 +804,11 @@ export function swiftSourceAsIOS(source: string): string {
467
804
  continue
468
805
  }
469
806
  if (rest.startsWith('class')) {
807
+ const declared = CLASS_BASE.exec(rest)
808
+ if (declared && reusableViews.has(declared[2]!.split('.').pop()!)) {
809
+ reusableViews.add(declared[1]!)
810
+ opensReusableBody = true
811
+ }
470
812
  const modifiers = conditioned.slice(conditioned.lastIndexOf('\n', at - 1) + 1, at)
471
813
  if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
472
814
  out += `${conditioned.slice(copied, at)}final `
@@ -481,6 +823,8 @@ export function swiftSourceAsIOS(source: string): string {
481
823
  if (selector) replacement = '#Selector'
482
824
  else if (match[0] === '@objcMembers') replacement = '@ObjCMembers'
483
825
  else if (match[0] === '@IBAction') replacement = '@ObjC'.padEnd(match[0].length)
826
+ else if (TYPE_AFTER_ATTRIBUTE.test(rest.slice(match[0].length)))
827
+ replacement = ' '.repeat(match[0].length)
484
828
  else if (match[2] !== undefined)
485
829
  replacement = `@ObjC${match[1]}("${match[2].trim()}")`
486
830
  out += conditioned.slice(copied, at) + replacement
@@ -489,8 +833,8 @@ export function swiftSourceAsIOS(source: string): string {
489
833
  return out + conditioned.slice(copied)
490
834
  }
491
835
 
492
- // the offsets of the lines that begin in code, and of every `@`, `#` and
493
- // `class` keyword that stands in code (an interpolation's code included), from a scan of Swift's
836
+ // the offsets of the lines that begin in code, and of every `@`, `#`,
837
+ // `class`, `extension` and `override` keyword that stands in code (an interpolation's code included), from a scan of Swift's
494
838
  // lexical contexts: nested block comments, line comments, string literals (single and
495
839
  // multiline, raw with any number of #, interpolations holding code and
496
840
  // strings of their own) and #/ /# regex literals. a bare /regex/ literal
@@ -571,6 +915,9 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
571
915
  if (hashes > 0) tokens.push(at - 1)
572
916
  i = Math.max(at, i + 1)
573
917
  }
918
+ } else if (char === '{' || char === '}') {
919
+ tokens.push(i)
920
+ i++
574
921
  } else if (char === '(') {
575
922
  top.parens++
576
923
  i++
@@ -581,11 +928,15 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
581
928
  } else {
582
929
  const keyword = source.startsWith('class', i)
583
930
  ? 'class'
584
- : source.startsWith('import', i)
585
- ? 'import'
586
- : source.startsWith('NSClassFromString', i)
587
- ? 'NSClassFromString'
588
- : null
931
+ : source.startsWith('extension', i)
932
+ ? 'extension'
933
+ : source.startsWith('override', i)
934
+ ? 'override'
935
+ : source.startsWith('import', i)
936
+ ? 'import'
937
+ : source.startsWith('NSClassFromString', i)
938
+ ? 'NSClassFromString'
939
+ : null
589
940
  if (
590
941
  keyword &&
591
942
  !/[\w$]/.test(source[i - 1] ?? '') &&
@@ -605,6 +956,32 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
605
956
  const compiledSource = (file: string, contents: string) =>
606
957
  file.endsWith('.swift') ? swiftSourceAsIOS(contents) : contents
607
958
 
959
+ /** a dependency package's build copy: the published tree with every Swift
960
+ * source rewritten as app sources are, so an unchanged upstream package that
961
+ * uses `@objc` and `#selector` reaches PeachObjC. its manifests stay as
962
+ * published and the upstream tree is never written. */
963
+ export function prepareSwiftDependency(source: string, destination: string): void {
964
+ rmSync(destination, { recursive: true, force: true })
965
+ const copy = (from: string, to: string, root: boolean) => {
966
+ mkdirSync(to, { recursive: true })
967
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
968
+ if (entry.name === '.git' || entry.name === '.build' || entry.name === '.swiftpm')
969
+ continue
970
+ const file = path.join(from, entry.name)
971
+ const target = path.join(to, entry.name)
972
+ if (entry.isDirectory()) copy(file, target, false)
973
+ else if (
974
+ entry.isFile() &&
975
+ entry.name.endsWith('.swift') &&
976
+ !(root && /^Package(@swift-[\d.]+)?\.swift$/.test(entry.name))
977
+ )
978
+ writeFileSync(target, compiledSource(file, readFileSync(file, 'utf8')))
979
+ else cpSync(file, target, { verbatimSymlinks: true })
980
+ }
981
+ }
982
+ copy(source, destination, true)
983
+ }
984
+
608
985
  export function writeSwiftProject(
609
986
  layout: SwiftProjectLayout,
610
987
  input: SwiftCompileInput,
@@ -641,11 +1018,27 @@ export function writeSwiftProject(
641
1018
  path.join(moduleRoot, 'scripts/contrast-app-Package.swift'),
642
1019
  'utf8',
643
1020
  ).replaceAll('__SOOTSIM_SWIFT_PACKAGE__', moduleRoot)
1021
+ const optionalProducts =
1022
+ swiftTargetDependencies(input.files, [{ name: 'App', path: '.' }]).get('App') ?? []
1023
+ if (optionalProducts.length > 0) {
1024
+ const product = '.product(name: "SwiftUI", package: "sootsim-swift"),'
1025
+ if (!manifest.includes(product))
1026
+ throw new Error('Swift app template lost its framework dependency anchor')
1027
+ manifest = manifest.replace(
1028
+ product,
1029
+ [
1030
+ product,
1031
+ ...optionalProducts.map(
1032
+ (name) => `.product(name: "${name}", package: "sootsim-swift"),`,
1033
+ ),
1034
+ ].join('\n '),
1035
+ )
1036
+ }
644
1037
  if (input.oneModule) {
645
1038
  // anchored on lines the template already has, so the template stays a
646
1039
  // valid manifest for a compiler build that predates the One module
647
1040
  const product = '.product(name: "CoreLocation", package: "sootsim-swift"),'
648
- const flags = `"-Osize"${OBJC_IMPLICIT_FLAGS}`
1041
+ const flags = `"-Osize"${FOUNDATION_IMPLICIT_FLAGS}`
649
1042
  if (!manifest.includes(product) || !manifest.includes(flags)) {
650
1043
  throw new Error(
651
1044
  'scripts/contrast-app-Package.swift lost the lines the One module links at',
@@ -691,7 +1084,10 @@ export function writeSwiftProject(
691
1084
  path.join(layout.root, 'Package.swift'),
692
1085
  emitSwiftPackageManifest({
693
1086
  targets,
694
- siblings: swiftSiblingDependencies(input.files, targets),
1087
+ siblings: swiftTargetDependencies(
1088
+ input.files,
1089
+ layout.multi ? targets : targets.map((target) => ({ ...target, path: '.' })),
1090
+ ),
695
1091
  moduleRoot,
696
1092
  oneModule: input.oneModule,
697
1093
  spriteKit: importsSpriteKit(input.files),
@@ -795,7 +1191,8 @@ export function compileSwiftProjectUnit(
795
1191
  const macroPlugins = await ensureMacroPlugins(moduleRoot, options.toolchainBin)
796
1192
  // memoized per toolchain, so only a process's first build waits on it,
797
1193
  // and that one reads and gzips it while swift builds
798
- const icu = swiftIcuAsset(options.toolchainBin, options.release)
1194
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId
1195
+ const icu = swiftIcuAsset(options.toolchainBin, sdk)
799
1196
  try {
800
1197
  await run(
801
1198
  swift,
@@ -806,7 +1203,7 @@ export function compileSwiftProjectUnit(
806
1203
  '--package-path',
807
1204
  root,
808
1205
  '--swift-sdk',
809
- `${options.release}_wasm`,
1206
+ sdk,
810
1207
  '-c',
811
1208
  'release',
812
1209
  '-Xswiftc',