peachsim 0.1.2438 → 0.1.2439

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 (175) hide show
  1. package/README.md +30 -98
  2. package/cli/app-catalog.ts +4 -73
  3. package/cli/catalog/content.ts +1 -1
  4. package/cli/cloud-box-artifact.ts +26 -39
  5. package/cli/cloud-client.ts +69 -117
  6. package/cli/cloud-session.ts +2 -9
  7. package/cli/commands/box.ts +6 -6
  8. package/cli/commands/control.ts +4 -11
  9. package/cli/commands/flow.ts +5 -9
  10. package/cli/commands/kotlin.ts +2 -1
  11. package/cli/commands/platform.ts +21 -39
  12. package/cli/commands/record-three.ts +1 -1
  13. package/cli/commands/shell-url.ts +29 -23
  14. package/cli/dev-build-freshness.ts +4 -3
  15. package/cli/native-input.ts +2 -2
  16. package/cli/outbound-endpoints.ts +20 -45
  17. package/cli/remote-project-bundle.ts +8 -14
  18. package/cli/remote-simulators.ts +1 -1
  19. package/cli/send-to-box.ts +2 -1
  20. package/detox/jest-preset.cjs +1 -1
  21. package/detox/jest-transform.cjs +40 -2
  22. package/dist-lib/agent-daemon-client.cjs +34 -24
  23. package/dist-lib/agent-events.cjs +1 -1
  24. package/dist-lib/attached-projects.cjs +19 -17
  25. package/dist-lib/auth/shared-session.cjs +18 -16
  26. package/dist-lib/backend-origin.cjs +1 -1
  27. package/dist-lib/beta.cjs +1 -1
  28. package/dist-lib/beta.mjs +2 -1
  29. package/dist-lib/bridge-constants.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.cjs +1 -1
  31. package/dist-lib/bridge-contract-input.mjs +20 -583
  32. package/dist-lib/bridge-contract.cjs +1 -1
  33. package/dist-lib/bridge-contract.mjs +17 -99
  34. package/dist-lib/bundle-channel.cjs +8718 -5552
  35. package/dist-lib/capture-contract.cjs +1 -1
  36. package/dist-lib/capture-contract.mjs +13 -363
  37. package/dist-lib/cloud-contract.cjs +1 -1
  38. package/dist-lib/cloud-contract.mjs +34 -155
  39. package/dist-lib/cloud-test-args.cjs +1 -1
  40. package/dist-lib/cloud-test-args.mjs +2 -1
  41. package/dist-lib/cloud.cjs +1 -1
  42. package/dist-lib/cloud.mjs +26 -155
  43. package/dist-lib/config.cjs +1 -4
  44. package/dist-lib/config.mjs +11 -30
  45. package/dist-lib/detox/index.cjs +2554 -230
  46. package/dist-lib/detox/jest-preset.cjs +1 -1
  47. package/dist-lib/detox/jest-transform.cjs +40 -2
  48. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  49. package/dist-lib/esm-chunks/acorn-FGE4PYDJ.mjs +50 -0
  50. package/dist-lib/esm-chunks/chunk-2EUHEBIJ.mjs +664 -0
  51. package/dist-lib/esm-chunks/chunk-2NPABFPN.mjs +5719 -0
  52. package/dist-lib/esm-chunks/chunk-4ZFNH7TU.mjs +10 -0
  53. package/dist-lib/esm-chunks/chunk-5T4XBUJP.mjs +1353 -0
  54. package/dist-lib/esm-chunks/chunk-6VY6HTJC.mjs +18951 -0
  55. package/dist-lib/esm-chunks/chunk-7HANEMO4.mjs +188 -0
  56. package/dist-lib/esm-chunks/chunk-C3WBGYP6.mjs +186 -0
  57. package/dist-lib/esm-chunks/chunk-CVGDRROP.mjs +57 -0
  58. package/dist-lib/esm-chunks/chunk-DADGQELM.mjs +375 -0
  59. package/dist-lib/esm-chunks/chunk-DEGYKHN7.mjs +12 -0
  60. package/dist-lib/esm-chunks/chunk-HIDNO3RP.mjs +10992 -0
  61. package/dist-lib/esm-chunks/chunk-HSADZOVN.mjs +30 -0
  62. package/dist-lib/esm-chunks/chunk-IWJUYJQO.mjs +42 -0
  63. package/dist-lib/esm-chunks/chunk-JCKI3VZ6.mjs +10 -0
  64. package/dist-lib/esm-chunks/chunk-KSQ5KM5Y.mjs +17 -0
  65. package/dist-lib/esm-chunks/chunk-KVTIDLBK.mjs +598 -0
  66. package/dist-lib/esm-chunks/chunk-MIQSRBVU.mjs +10 -0
  67. package/dist-lib/esm-chunks/chunk-YB27R6JG.mjs +115 -0
  68. package/dist-lib/esm-chunks/metro-layout-parser-MVUAXRUJ.mjs +58 -0
  69. package/dist-lib/expo-swift-bundle.cjs +7856 -4707
  70. package/dist-lib/expo-swift-metadata.cjs +1 -1
  71. package/dist-lib/expo-swift-metadata.mjs +16 -165
  72. package/dist-lib/home-paths.cjs +1 -1
  73. package/dist-lib/host/bridge-host.cjs +15658 -11404
  74. package/dist-lib/host/fetch-proxy-handler.cjs +3927 -342
  75. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  76. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -1
  77. package/dist-lib/host/replacement-module-handler.cjs +4 -4
  78. package/dist-lib/host/websocket-proxy.cjs +1 -1
  79. package/dist-lib/index.cjs +9145 -32150
  80. package/dist-lib/jump-to-source-babel.cjs +1 -1
  81. package/dist-lib/jump-to-source-native.cjs +2 -2
  82. package/dist-lib/kotlin-host.cjs +260 -253
  83. package/dist-lib/menu.cjs +1 -1
  84. package/dist-lib/menu.mjs +5 -13
  85. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  86. package/dist-lib/metro-fingerprint-registry.mjs +5 -6
  87. package/dist-lib/metro-production-bundle.cjs +22 -3
  88. package/dist-lib/metro-production-bundle.mjs +26 -92
  89. package/dist-lib/native-app-identity-project.cjs +663 -451
  90. package/dist-lib/native-app-identity-project.mjs +509 -2318
  91. package/dist-lib/native-app-identity.cjs +1 -1
  92. package/dist-lib/native-app-identity.mjs +27 -1340
  93. package/dist-lib/native-firebase-metadata.cjs +1 -1
  94. package/dist-lib/native-firebase-metadata.mjs +5 -18
  95. package/dist-lib/pdfium-raster.cjs +1 -1
  96. package/dist-lib/pdfium-raster.mjs +2 -1
  97. package/dist-lib/plist.cjs +2 -2
  98. package/dist-lib/plist.mjs +5 -7
  99. package/dist-lib/profiles.cjs +2 -1
  100. package/dist-lib/public-brand.cjs +1 -1
  101. package/dist-lib/public-origins-lib-esm.json +246 -187
  102. package/dist-lib/public-origins-lib-static.json +1 -1
  103. package/dist-lib/public-origins-lib.json +1059 -1238
  104. package/dist-lib/react-native-host-modules.cjs +1 -1
  105. package/dist-lib/react-native-host-modules.mjs +2 -1
  106. package/dist-lib/reap-browser.cjs +18 -7
  107. package/dist-lib/scripts/dev-server-scanner.cjs +6 -230
  108. package/dist-lib/sdk.cjs +1 -1
  109. package/dist-lib/sdk.mjs +22 -78
  110. package/dist-lib/skills.cjs +21657 -17374
  111. package/dist-lib/swift-compile.cjs +1343 -1318
  112. package/dist-lib/swift-compile.mjs +68 -19013
  113. package/dist-lib/swift-package.cjs +1 -1
  114. package/dist-lib/swift-package.mjs +35 -630
  115. package/dist-lib/swift-submit.cjs +1 -1
  116. package/dist-lib/swift-submit.mjs +9 -24
  117. package/dist-lib/swift-toolchain.cjs +1 -1
  118. package/dist-lib/swift.cjs +1 -1
  119. package/dist-lib/vendor/@peculiar/x509.cjs +18061 -0
  120. package/dist-lib/vendor/acorn.cjs +5699 -0
  121. package/dist-lib/vendor/bplist-parser.cjs +1589 -0
  122. package/dist-lib/vendor/ignore.cjs +455 -0
  123. package/dist-lib/vendor/magic-string.cjs +1693 -0
  124. package/dist-lib/vendor/plist.cjs +10978 -0
  125. package/dist-lib/vendor/smol-toml.cjs +768 -0
  126. package/dist-lib/vendor/stream-json.cjs +1997 -0
  127. package/dist-lib/vendor/sucrase/dist/index.js.cjs +23593 -0
  128. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +15750 -0
  129. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +11316 -0
  130. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +482 -0
  131. package/dist-lib/vendor/sucrase.cjs +23593 -0
  132. package/dist-lib/vendor/terser.cjs +36874 -0
  133. package/dist-lib/vendor/valibot.cjs +6253 -0
  134. package/dist-lib/vendor/zod.cjs +23262 -0
  135. package/dist-lib/worklet-executable.cjs +3 -3
  136. package/dist-lib/worklet-executable.mjs +11 -16
  137. package/dist-types/packages/peach-engine/src/config.d.ts +1 -1
  138. package/kotlin/fork/NOTICE +3 -0
  139. package/kotlin/sdk.tar.gz +0 -0
  140. package/kotlin/toolchain.json +6 -6
  141. package/package.json +17 -121
  142. package/runtime-companion.json +1 -1
  143. package/scripts/dev-server-scanner.ts +13 -223
  144. package/src/android-autolinking.ts +2 -2
  145. package/src/bundle-channel.mjs +3 -15
  146. package/src/cloud-contract.ts +3 -4
  147. package/src/config.ts +0 -5
  148. package/src/host/bridge-host.ts +19 -1
  149. package/src/host/server-scan-handler.ts +1 -9
  150. package/src/index.ts +0 -2
  151. package/src/kotlin-host.ts +1 -2
  152. package/src/kotlinDiscoveryContract.ts +1 -0
  153. package/src/metro-production-bundle.ts +28 -6
  154. package/src/native-seam-manifest.ts +0 -13
  155. package/src/one-native-app-catalog.ts +8 -27
  156. package/src/one-native-app-config.ts +95 -0
  157. package/src/one-native-source.ts +250 -0
  158. package/src/one-widget-metadata.ts +45 -126
  159. package/src/oneWidgetContract.ts +80 -117
  160. package/src/serverDiscoveryContract.ts +0 -1
  161. package/src/simulator-route.ts +8 -0
  162. package/src/vite-plugin.ts +2 -2
  163. package/src/xcode-project.ts +1 -1
  164. package/dist-lib/metro.cjs +0 -27984
  165. package/dist-lib/vite-swift.cjs +0 -43376
  166. package/dist-lib/vite.cjs +0 -21456
  167. package/src/androidAutolinkingContract.ts +0 -48
  168. package/src/androidRootModuleContract.ts +0 -39
  169. package/src/dev-server-open.ts +0 -92
  170. package/src/metro-plugin.ts +0 -578
  171. package/src/one-widget-discovery.ts +0 -23
  172. package/src/swift-vite-lifetime.ts +0 -42
  173. package/src/vite-plugin-one.ts +0 -746
  174. package/src/vite-plugin-swift.ts +0 -225
  175. package/src/vite.d.ts +0 -10
@@ -1,746 +0,0 @@
1
- // peach plugin for One/Vite: serves the installed peach runtime at /__peachsim/
2
- // from ~/.peach/runtimes/<version>. version-owned localhost origins remain
3
- // bound to that directory across an active-runtime update.
4
- //
5
- // usage in vite.config.ts:
6
- // import { peachPlugin } from 'peachsim/vite'
7
- // export default { plugins: [one(), peachPlugin()] }
8
-
9
- import fs from 'fs'
10
- import { randomUUID } from 'node:crypto'
11
- import http from 'node:http'
12
- import https from 'node:https'
13
- import { fileURLToPath } from 'node:url'
14
- import path from 'path'
15
- import { pipeline } from 'stream/promises'
16
- import {
17
- insertPackageVersionsFooter,
18
- PACKAGE_VERSIONS_HEADER,
19
- } from '@peach/globals/package-versions'
20
- import { WebSocket, WebSocketServer } from 'ws'
21
- import { resolveAppProject } from '../cli/app-project'
22
- import { loadRNXAppConfig } from './app-config'
23
- import { DEFAULT_SOOTSIM_BRIDGE_PORT } from './bridge-constants'
24
- import { loadCliRuntime } from './cli-runtime'
25
- import { matchConfigModule, PEACH_WORKSPACE_MODULE_MARKER } from './config'
26
- import {
27
- launchRnxDesktop,
28
- resolveRnxDesktopAppName,
29
- resolveRnxDesktopLaunchTarget,
30
- tagRnxBundleForPlugin,
31
- } from './dev-server-open'
32
- import { isDaemonLockfileFresh, readDaemonLockfile } from './home-paths'
33
- import { serveBrowserProxyRoute } from './host/fetch-proxy-handler'
34
- import { handleReplacementModuleRequest } from './host/replacement-module-handler'
35
- import { forwardRolldownBundleResponse } from './host/rolldown-bundle-forward'
36
- import { readInstalledNativePackageVersions } from './installed-package-versions'
37
- import {
38
- ONE_NATIVE_APP_CATALOG_ROUTE,
39
- readOneNativeAppCatalog,
40
- } from './one-native-app-catalog'
41
- import { configuredOneWidget } from './one-widget-metadata'
42
- import {
43
- isRootRuntimeAssetPath,
44
- resolveRuntimeFilePath,
45
- resolveRuntimeRootForRequestHost,
46
- sendShellHtml,
47
- serveRuntimeFile,
48
- SOOTSIM_RUNTIME_MISSING_MESSAGE,
49
- } from './runtime-assets'
50
- import { ensureRuntimePackFor } from './runtime-packs'
51
- import { SWIFT_HMR_PATH, SWIFT_PACKAGE_PATH } from './swift-submit'
52
- import { privateSwiftDistributionRoot } from './swift-toolchain'
53
- import { swiftViteLifetime } from './swift-vite-lifetime'
54
- import type { PeachConfig } from './config'
55
- import type { OneWidgetPackage } from './oneWidgetContract'
56
- import type { PeachPluginOptions } from './vite'
57
- import type { IncomingMessage, ServerResponse } from 'node:http'
58
- import type { Plugin } from 'vite'
59
-
60
- function requestAuthority(req: IncomingMessage): string | undefined {
61
- const authority = req.headers[':authority']
62
- return req.headers.host ?? (typeof authority === 'string' ? authority : undefined)
63
- }
64
-
65
- // a shell on another origin reads only the response headers it is told about
66
- function exposeHeader(res: ServerResponse, name: string) {
67
- const exposed = res.getHeader('access-control-expose-headers')
68
- const names = typeof exposed === 'string' && exposed ? exposed.split(/,\s*/) : []
69
- if (!names.includes(name))
70
- res.setHeader('access-control-expose-headers', [...names, name].join(', '))
71
- }
72
-
73
- // marks the plugin's own request for the bundle One builds, so the .bundle
74
- // route forwards One's response instead of answering itself again.
75
- const BUNDLE_SOURCE_REQUEST_HEADER = 'x-peach-bundle-source'
76
-
77
- // every swift route sits under this prefix. the swift host (compiler client,
78
- // resource packer, module glue) loads on the first request for one, so an app
79
- // that imports no swift never evaluates it.
80
- const SWIFT_ROUTE_PREFIX = '/__peach/swift'
81
- let swiftHost: Promise<typeof import('peachsim/vite-swift')> | undefined
82
- const loadSwiftHost = () => (swiftHost ??= import('peachsim/vite-swift'))
83
- // the Kotlin host (toolchain fetch, compile, artifact serving) loads the same
84
- // way, on the first /__peach/kotlin request from an Android device
85
- const KOTLIN_ROUTE_PREFIX = '/__peach/kotlin'
86
- let kotlinHost: Promise<typeof import('peachsim/kotlin-host')> | undefined
87
- const loadKotlinHost = () => (kotlinHost ??= import('peachsim/kotlin-host'))
88
-
89
- export function peachPlugin(options: PeachPluginOptions = {}): Plugin {
90
- const prefix = options.prefix || '/__peachsim'
91
- let closeSwiftHost: (() => Promise<void>) | undefined
92
-
93
- return {
94
- name: 'sootsim-one',
95
-
96
- api: {
97
- vxrnNative({ root, dev }: { root: string; dev: boolean }): Plugin {
98
- let modules: PeachConfig['modules']
99
- return {
100
- name: 'peach:package-versions',
101
- async buildStart() {
102
- if (options.enabled === false || dev) return
103
- modules = (await loadRNXAppConfig(resolveAppProject(root)))?.modules
104
- },
105
- transform(code, id) {
106
- if (!modules || id.includes('/node_modules/')) return
107
- const match = matchConfigModule(id.split('?')[0], modules)
108
- if (!match) return
109
- // production rolldown reads a module's exports by direct binding, so
110
- // the tag lists each export name with the local it reads
111
- const exported: string[] = []
112
- for (const node of this.parse(code, {
113
- lang: id.split('?')[0].endsWith('x') ? 'tsx' : 'ts',
114
- }).body) {
115
- if (node.type === 'ExportDefaultDeclaration') {
116
- const declaration = node.declaration
117
- if (!('id' in declaration) || declaration.id?.type !== 'Identifier')
118
- throw new Error(
119
- `${id}: a configured module needs a named default export`,
120
- )
121
- exported.push(`default:()=>${declaration.id.name}`)
122
- } else if (
123
- node.type === 'ExportNamedDeclaration' &&
124
- node.exportKind !== 'type'
125
- ) {
126
- if (node.source)
127
- throw new Error(
128
- `${id}: a configured module cannot re-export from another module`,
129
- )
130
- for (const specifier of node.specifiers) {
131
- const { exported: name, local } = specifier
132
- if (specifier.exportKind === 'type') continue
133
- if (local.type !== 'Identifier')
134
- throw new Error(`${id}: a configured module needs plain exports`)
135
- exported.push(
136
- `${JSON.stringify('name' in name ? name.name : name.value)}:()=>${local.name}`,
137
- )
138
- }
139
- const declaration = node.declaration
140
- if (declaration?.type === 'VariableDeclaration') {
141
- for (const declarator of declaration.declarations) {
142
- if (declarator.id.type !== 'Identifier')
143
- throw new Error(
144
- `${id}: a configured module needs plain exported variables`,
145
- )
146
- exported.push(`${declarator.id.name}:()=>${declarator.id.name}`)
147
- }
148
- } else if (
149
- (declaration?.type === 'FunctionDeclaration' ||
150
- declaration?.type === 'ClassDeclaration' ||
151
- declaration?.type === 'TSEnumDeclaration') &&
152
- declaration.id?.type === 'Identifier'
153
- ) {
154
- exported.push(`${declaration.id.name}:()=>${declaration.id.name}`)
155
- }
156
- } else if (node.type === 'ExportAllDeclaration') {
157
- throw new Error(
158
- `${id}: a configured module cannot re-export from another module`,
159
- )
160
- }
161
- }
162
- return `${code}\nglobalThis.${PEACH_WORKSPACE_MODULE_MARKER}=[${JSON.stringify(match.pattern)},{${exported.join(',')}}];`
163
- },
164
- async generateBundle(_options, bundle) {
165
- if (options.enabled === false || dev) return
166
- const versions = readInstalledNativePackageVersions(root)
167
- const { attachRolldownBundleInventory } = (await loadCliRuntime())
168
- .rolldown_bundle_inventory
169
- for (const output of Object.values(bundle)) {
170
- if (output.type !== 'chunk') continue
171
- output.code = await attachRolldownBundleInventory(
172
- insertPackageVersionsFooter(output.code, versions),
173
- )
174
- }
175
- },
176
- }
177
- },
178
- },
179
-
180
- // use-latest-callback ships a CJS main (module.exports, no default) with
181
- // an esm.mjs shim that re-imports it. react-native-bottom-tabs
182
- // default-imports it from source served live, so vite hands the browser
183
- // the raw CJS file and the import fails with 'does not provide an export
184
- // named default' before anything mounts. forcing it through dep
185
- // optimization lets esbuild's CJS interop answer the default import, and
186
- // every bare import of it (including the nested copy's) resolves to the
187
- // one pre-bundled instance.
188
- config() {
189
- return { optimizeDeps: { include: ['use-latest-callback'] } }
190
- },
191
-
192
- async closeBundle() {
193
- await closeSwiftHost?.()
194
- },
195
-
196
- async configureServer(server) {
197
- if (options.enabled === false) return
198
- const lifetime = swiftViteLifetime(server)
199
- const { signal, compiles: swiftCompiles, projects: swiftProjects } = lifetime
200
- closeSwiftHost = () => lifetime.close()
201
- // a native bundle carries the install it was built from, as hosted
202
- // bundles do: any shell that launches it, including one that found this
203
- // server by scanning, learns the installed native package versions. a
204
- // page that fetches the bundle from this server directly (the shell at
205
- // the plugin prefix, or a hosted page reaching this loopback server)
206
- // gets the rolldown inventory the bundle proxy attaches for everyone
207
- // else: the request is answered again by One's own handler and forwarded
208
- // through the same producer. placed at the front of the stack so it runs
209
- // ahead of One's .bundle handler even when one() precedes peachPlugin().
210
- server.middlewares.use((req, res, next) => {
211
- if (!(req.url ?? '').split('?')[0].endsWith('.bundle')) {
212
- next()
213
- return
214
- }
215
- res.setHeader(
216
- PACKAGE_VERSIONS_HEADER,
217
- JSON.stringify(readInstalledNativePackageVersions(server.config.root)),
218
- )
219
- exposeHeader(res, PACKAGE_VERSIONS_HEADER)
220
- // a native app on a real simulator or device asks for hermes bytecode,
221
- // which carries no rolldown inventory; peach strips that parameter
222
- const query = new URLSearchParams((req.url ?? '').split('?')[1] ?? '')
223
- if (
224
- req.method !== 'GET' ||
225
- req.headers[BUNDLE_SOURCE_REQUEST_HEADER] ||
226
- query.has('bytecode') ||
227
- query.has('transform.bytecode')
228
- ) {
229
- next()
230
- return
231
- }
232
- const address = server.httpServer?.address()
233
- if (!address || typeof address !== 'object') {
234
- next()
235
- return
236
- }
237
- const loopback =
238
- address.address === '::' || address.address === '0.0.0.0'
239
- ? '127.0.0.1'
240
- : address.address
241
- const options: https.RequestOptions = {
242
- host: loopback,
243
- port: address.port,
244
- path: req.url,
245
- method: 'GET',
246
- headers: {
247
- ...Object.fromEntries(
248
- Object.entries(req.headers).filter(([key]) => !key.startsWith(':')),
249
- ),
250
- host: requestAuthority(req),
251
- 'accept-encoding': 'identity',
252
- [BUNDLE_SOURCE_REQUEST_HEADER]: '1',
253
- },
254
- rejectUnauthorized: false,
255
- }
256
- const respond = (upstream: http.IncomingMessage) => {
257
- res.statusCode = upstream.statusCode ?? 502
258
- for (const [key, value] of Object.entries(upstream.headers)) {
259
- const lowerKey = key.toLowerCase()
260
- if (
261
- value === undefined ||
262
- lowerKey === 'connection' ||
263
- lowerKey === 'keep-alive' ||
264
- lowerKey === 'transfer-encoding'
265
- ) {
266
- continue
267
- }
268
- res.setHeader(key, value)
269
- }
270
- const forward =
271
- res.statusCode === 200
272
- ? forwardRolldownBundleResponse(upstream, res)
273
- : pipeline(upstream, res)
274
- forward.catch((error: unknown) => {
275
- console.error('[peach] bundle forward failed', error)
276
- const failure = error instanceof Error ? error : new Error(String(error))
277
- // before the first byte the sim can still read the cause; a dropped
278
- // socket left its bundle request pending until wait ready timed out
279
- if (res.headersSent) {
280
- res.destroy(failure)
281
- return
282
- }
283
- upstream.destroy()
284
- res.statusCode = 500
285
- for (const key of res.getHeaderNames()) res.removeHeader(key)
286
- res.setHeader('content-type', 'text/plain; charset=utf-8')
287
- res.end(`peach bundle forward failed: ${failure.message}`)
288
- })
289
- }
290
- const upstreamReq = server.config.server.https
291
- ? https.request(options, respond)
292
- : http.request(options, respond)
293
- upstreamReq.once('error', next)
294
- res.once('close', () => {
295
- if (!res.writableFinished) upstreamReq.destroy()
296
- })
297
- upstreamReq.end()
298
- })
299
- const bundleLayer = server.middlewares.stack.pop()
300
- if (bundleLayer) server.middlewares.stack.unshift(bundleLayer)
301
- const { swiftPackageDirectories } = await import('vxrn')
302
- let swiftPackages: Map<string, string> | undefined
303
- // the workspace SwiftUI module beside peachsim compiles locally; an
304
- // npm install has none (null), and its packages compile on Contrast.
305
- let swiftModuleRoot: string | null | undefined
306
- const moduleRootFor = (): string | undefined => {
307
- if (privateSwiftDistributionRoot()) return undefined
308
- if (swiftModuleRoot === undefined) {
309
- // src/ or dist-lib/ → .. is peachsim; the module sits beside it
310
- const moduleRoot = path.resolve(
311
- path.dirname(fileURLToPath(import.meta.url)),
312
- '../../sootsim-swift',
313
- )
314
- swiftModuleRoot = fs.existsSync(path.join(moduleRoot, 'toolchain.json'))
315
- ? moduleRoot
316
- : null
317
- }
318
- return swiftModuleRoot ?? undefined
319
- }
320
- const activeSwiftPackages = new Set<string>()
321
- const packageMap = () => {
322
- swiftPackages ??= swiftPackageDirectories(server.config.root)
323
- return swiftPackages
324
- }
325
- let widgetPackage: OneWidgetPackage | null = null
326
- const servedPackage = async (packageName: string) => {
327
- const host = await loadSwiftHost()
328
- const existing = packageMap().get(packageName)
329
- if (packageName !== host.ONE_WIDGET_PACKAGE) return existing
330
- widgetPackage = await host.oneWidgetPackage(server.config.root)
331
- if (!widgetPackage) return existing
332
- if (existing)
333
- throw new Error(
334
- `swift package ${packageName} conflicts with One's generated widget extension`,
335
- )
336
- server.watcher.add(widgetPackage.watched)
337
- return widgetPackage.packagePath
338
- }
339
- const packageMetadata = async (
340
- packageName: string,
341
- moduleRoot: string | undefined,
342
- ) => {
343
- const pending = (async () => {
344
- signal.throwIfAborted()
345
- const packagePath = await servedPackage(packageName)
346
- if (!packagePath) throw new Error(`swift package ${packageName} was not found`)
347
- swiftProjects.add(packagePath)
348
- const host = await loadSwiftHost()
349
- const metadata = await host.swiftPackageMetadata(
350
- packagePath,
351
- packageName,
352
- moduleRoot,
353
- devOrigin(),
354
- undefined,
355
- signal,
356
- )
357
- return {
358
- ...metadata,
359
- hmrPath,
360
- ...(packageName === host.ONE_WIDGET_PACKAGE && widgetPackage
361
- ? { widget: widgetPackage.widget }
362
- : {}),
363
- }
364
- })()
365
- swiftCompiles.add(pending)
366
- try {
367
- return await pending
368
- } finally {
369
- swiftCompiles.delete(pending)
370
- }
371
- }
372
- const wsOptions = server.config.server.ws
373
- const httpServer =
374
- server.httpServer ??
375
- (wsOptions && typeof wsOptions === 'object' ? wsOptions.server : undefined)
376
- const swiftSockets = httpServer
377
- ? new WebSocketServer({ noServer: true })
378
- : undefined
379
- const hmrPath = SWIFT_HMR_PATH
380
- const configuredPort = server.config.server.port || 8081
381
- const listeningPort = (): number => {
382
- const address = server.httpServer?.address()
383
- return address && typeof address === 'object' ? address.port : configuredPort
384
- }
385
- const devOrigin = () => `http://localhost:${listeningPort()}`
386
- const requestOrigin = (req: IncomingMessage): string =>
387
- new URL(
388
- req.url || '/',
389
- `${server.config.server.https ? 'https' : 'http'}://${requestAuthority(req)}`,
390
- ).origin
391
- const sendSwiftChange = (change: object) => {
392
- const message = JSON.stringify(change)
393
- for (const client of swiftSockets?.clients ?? []) {
394
- if (client.readyState === WebSocket.OPEN) client.send(message)
395
- }
396
- }
397
- if (httpServer && swiftSockets) {
398
- httpServer.on('upgrade', (req, socket, head) => {
399
- if (new URL(req.url ?? '/', 'http://localhost').pathname !== SWIFT_HMR_PATH)
400
- return
401
- swiftSockets.handleUpgrade(req, socket, head, (client) => {
402
- swiftSockets.emit('connection', client, req)
403
- })
404
- })
405
- httpServer.once('close', () => {
406
- for (const client of swiftSockets.clients) client.terminate()
407
- swiftSockets.close()
408
- })
409
- }
410
- server.watcher.on('add', (file) => {
411
- if (path.basename(file) === 'Package.swift') swiftPackages = undefined
412
- })
413
- server.watcher.on('unlink', (file) => {
414
- if (path.basename(file) === 'Package.swift') swiftPackages = undefined
415
- })
416
- // a Kotlin source edit reaches the next call: the seam drops the module
417
- // it imported and asks for the app's Kotlin again
418
- let kotlinModuleRoot: string | undefined
419
- server.watcher.on('all', (_event, file) => {
420
- if (!kotlinModuleRoot) return
421
- if (file.endsWith('.kt') || file.startsWith(`${kotlinModuleRoot}${path.sep}`))
422
- sendSwiftChange({ type: 'kotlin', packageName: 'kotlin' })
423
- })
424
- server.middlewares.use((req, res, next) => {
425
- const pathname = (req.url ?? '').split('?')[0]
426
- if (!pathname.startsWith(KOTLIN_ROUTE_PREFIX)) return next()
427
- loadKotlinHost()
428
- .then(async (host) => {
429
- if (!kotlinModuleRoot) {
430
- const root = host.peachKotlinModuleRoot()
431
- kotlinModuleRoot = root
432
- server.watcher.add(
433
- ['sdk.tar.gz', 'toolchain.json'].map((file) => path.join(root, file)),
434
- )
435
- }
436
- const served = await host.serveKotlinRequest(pathname, res, {
437
- root: server.config.root,
438
- moduleRoot: kotlinModuleRoot,
439
- origin: devOrigin(),
440
- hmrPath,
441
- })
442
- if (!served) next()
443
- })
444
- .catch(next)
445
- })
446
- server.watcher.on('all', (event, file) => {
447
- if (event !== 'add' && event !== 'unlink' && event !== 'change') return
448
- if (activeSwiftPackages.size === 0) return
449
- const moduleRoot = moduleRootFor()
450
- let packages: Map<string, string>
451
- try {
452
- packages = packageMap()
453
- } catch (error) {
454
- for (const packageName of activeSwiftPackages)
455
- sendSwiftChange({
456
- type: 'error',
457
- packageName,
458
- message: error instanceof Error ? error.message : String(error),
459
- })
460
- return
461
- }
462
- for (const packageName of activeSwiftPackages) {
463
- const packagePath = packages.get(packageName)
464
- const widgetChanged =
465
- packageName === 'OneWidgets' && widgetPackage?.watched.includes(file)
466
- if (
467
- !widgetChanged &&
468
- !(packagePath && file.startsWith(`${packagePath}${path.sep}`)) &&
469
- !(moduleRoot && file.startsWith(`${moduleRoot}${path.sep}`))
470
- )
471
- continue
472
- void packageMetadata(packageName, moduleRoot)
473
- .then((metadata) => {
474
- sendSwiftChange({
475
- type: 'package',
476
- packageName,
477
- metadata: { ...metadata, hmrPath },
478
- })
479
- })
480
- .catch((error: unknown) => {
481
- sendSwiftChange({
482
- type: 'error',
483
- packageName,
484
- message: error instanceof Error ? error.message : String(error),
485
- })
486
- })
487
- }
488
- })
489
- server.middlewares.use((req, res, next) => {
490
- const pathname = (req.url ?? '').split('?')[0]
491
- if (!pathname.startsWith(SWIFT_ROUTE_PREFIX)) return next()
492
- // the simulator fetches across origins: an error without this header
493
- // reaches it as "Failed to fetch", hiding the message
494
- res.setHeader('access-control-allow-origin', '*')
495
- loadSwiftHost()
496
- .then(async (host) => {
497
- if (await host.serveSwiftPackageAsset(pathname, res)) return
498
- const prefix = SWIFT_PACKAGE_PATH
499
- if (!pathname.startsWith(prefix)) return next()
500
- if (!swiftSockets) {
501
- res.statusCode = 501
502
- res.end('Peach Swift hot reload requires a Vite HTTP server')
503
- return
504
- }
505
- const packageName = pathname.slice(prefix.length)
506
- let packagePath: string | undefined
507
- try {
508
- packagePath = await servedPackage(packageName)
509
- } catch (error) {
510
- res.statusCode = 500
511
- res.end(error instanceof Error ? error.message : String(error))
512
- return
513
- }
514
- if (!packagePath) {
515
- res.statusCode = 404
516
- res.end(`swift package ${packageName} was not found`)
517
- return
518
- }
519
- const moduleRoot = moduleRootFor()
520
- activeSwiftPackages.add(packageName)
521
- server.watcher.add(await host.swiftPackageWatchFiles(packagePath, moduleRoot))
522
- void packageMetadata(packageName, moduleRoot)
523
- .then((metadata) => {
524
- res.setHeader('content-type', 'application/json')
525
- res.end(JSON.stringify({ ...metadata, hmrPath }))
526
- })
527
- .catch((error: unknown) => {
528
- res.statusCode = 500
529
- res.end(error instanceof Error ? error.message : String(error))
530
- })
531
- })
532
- .catch(next)
533
- })
534
- const bundleUrl =
535
- options.bundleUrl ||
536
- '/node_modules/one/metro-entry.bundle?platform=ios&dev=true&minify=false'
537
- const appName = resolveRnxDesktopAppName(options.open, server.config.root)
538
- const replacementToken = randomUUID()
539
- const bundleForOrigin = (origin: string): string => {
540
- const fullBundleUrl = new URL(bundleUrl, `${origin}/`).toString()
541
- return tagRnxBundleForPlugin(
542
- fullBundleUrl,
543
- origin,
544
- replacementToken,
545
- server.config.root,
546
- appName,
547
- )
548
- }
549
-
550
- // build the shell HTML, injecting the bundle URL (so main.tsx loads this
551
- // app's bundle) AND window.__sootsimBridgePort. the bridge-port injection
552
- // mirrors the dev-stack bridge-host: without it the engine's
553
- // resolveBridgePort() falls back to a location-derived guess that mis-maps
554
- // a non-Contrast app port (the mobile template's :4400 -> 9068) and the sim
555
- // can't reach the bridge. resolved per-request from the daemon lockfile
556
- // (the CLI's `open` writes/uses it before the shell loads) so the engine
557
- // targets the SAME bridge the CLI does; default port otherwise.
558
- const buildShellHtml = (runtimeRoot: string, origin: string): string => {
559
- const html = fs.readFileSync(path.join(runtimeRoot, 'index.html'), 'utf8')
560
- const lock = readDaemonLockfile()
561
- const bridgePort =
562
- lock && isDaemonLockfileFresh(lock) && lock.bridgePort > 0
563
- ? lock.bridgePort
564
- : DEFAULT_SOOTSIM_BRIDGE_PORT
565
- // inject the bridge port + a default bundle for guest app launches.
566
- // embedded demo apps select shell content instead of a guest bundle.
567
- // preserve explicit bundles and the existing query.
568
- // preserving the query is essential: `peach open` stamps the open URL
569
- // with `inspectOpen=<token>` and matches the registered sim by that
570
- // token (waitForSimMatch). the old code forced `?bundle=` only and
571
- // stripped inspectOpen, so the sim registered but never matched and
572
- // `open` timed out after 60s.
573
- const inject =
574
- `<script>(function(){var u=new URL(location.href);` +
575
- `var b=${JSON.stringify(bundleForOrigin(origin))};` +
576
- `if(!u.searchParams.has('bundle')&&!u.searchParams.get('demoApp')?.trim())u.searchParams.set('bundle',b);` +
577
- `window.__sootsimBridgePort=${bridgePort};` +
578
- `window.__peachPageServingAuthority='contributor';` +
579
- `history.replaceState(null,'','${prefix}/'+u.search)})()</script>`
580
- return html.replace('</head>', inject + '</head>')
581
- }
582
-
583
- server.middlewares.use((req, res, next) => {
584
- if ((req.url ?? '').split('?')[0] !== ONE_NATIVE_APP_CATALOG_ROUTE) return next()
585
- res.setHeader('content-type', 'application/json')
586
- res.end(
587
- JSON.stringify(
588
- readOneNativeAppCatalog(
589
- Reflect.get(globalThis, '__vxrnNativeEntryConfig'),
590
- server.config.root,
591
- ),
592
- ),
593
- )
594
- })
595
-
596
- // mirror Set-Cookie into a readable header for sootsim's fetch wrapper
597
- server.middlewares.use((req, res, next) => {
598
- const origWriteHead = res.writeHead.bind(res)
599
- res.writeHead = function (statusCode: number, ...args: unknown[]) {
600
- const setCookie = res.getHeader('set-cookie')
601
- if (setCookie) {
602
- const value = Array.isArray(setCookie)
603
- ? setCookie.join(', ')
604
- : String(setCookie)
605
- res.setHeader('x-sootsim-set-cookie', value)
606
- exposeHeader(res, 'x-sootsim-set-cookie')
607
- }
608
- return (origWriteHead as (...args: unknown[]) => typeof res)(
609
- statusCode,
610
- ...args,
611
- )
612
- } as typeof res.writeHead
613
- next()
614
- })
615
-
616
- // serve a minimal /__server-scan describing THIS vite dev server, so a
617
- // sootsim shell loaded from <port>/__peachsim can resolve this app's native
618
- // bundle. dev-bundle-resolution's resolvePortViaServerScan fetches
619
- // `/__server-scan` RELATIVE to the shell origin; when the shell is loaded
620
- // from this target origin, that hits here. without it the request SPA-
621
- // falls-back to 404 and the bundle never resolves (peach open hangs).
622
- // we describe only this server (the shell drives THIS app) — no localhost-
623
- // wide scan, so the published plugin pulls in no shell-only scanner
624
- // internals. shape matches DiscoveredServer enough for the resolver.
625
- server.middlewares.use(async (req, res, next) => {
626
- if ((req.url || '').split('?')[0] !== '/__server-scan') return next()
627
- const scanPort = listeningPort()
628
- const absoluteBundleUrl = bundleForOrigin(requestOrigin(req))
629
- res.setHeader('content-type', 'application/json')
630
- res.setHeader('access-control-allow-origin', '*')
631
- res.setHeader('cache-control', 'no-store')
632
- let widget: Awaited<ReturnType<typeof configuredOneWidget>> = null
633
- let widgetError: string | undefined
634
- try {
635
- widget = await configuredOneWidget(server.config.root, absoluteBundleUrl)
636
- if (widget && packageMap().has('OneWidgets'))
637
- throw new Error(
638
- "swift package OneWidgets conflicts with One's generated widget extension",
639
- )
640
- } catch (error) {
641
- widget = null
642
- widgetError = String(error)
643
- }
644
- res.end(
645
- JSON.stringify([
646
- {
647
- port: scanPort,
648
- framework: 'one',
649
- bundleUrl: absoluteBundleUrl,
650
- widget,
651
- ...(widgetError ? { widgetError } : {}),
652
- ...(appName ? { projectName: appName } : {}),
653
- lastSeen: Date.now(),
654
- },
655
- ]),
656
- )
657
- })
658
-
659
- server.middlewares.use((req, res, next) => {
660
- void handleReplacementModuleRequest(req, res, {
661
- servedRoots: [server.config.root, ...server.config.server.fs.allow],
662
- requestToken: replacementToken,
663
- requireLoopbackOrigin: true,
664
- }).then((handled) => {
665
- if (!handled) next()
666
- })
667
- })
668
-
669
- server.middlewares.use(async (req, res, next) => {
670
- if (serveBrowserProxyRoute(req, res)) return
671
- const url = req.url || ''
672
- const pathname = url.split('?')[0]
673
- const runtimeRoot = resolveRuntimeRootForRequestHost(requestAuthority(req))
674
-
675
- if (!runtimeRoot) {
676
- if (
677
- pathname === prefix ||
678
- pathname === prefix + '/' ||
679
- pathname.startsWith(prefix + '/')
680
- ) {
681
- res.statusCode = 500
682
- res.end(SOOTSIM_RUNTIME_MISSING_MESSAGE)
683
- return
684
- }
685
- next()
686
- return
687
- }
688
-
689
- await ensureRuntimePackFor(runtimeRoot, pathname)
690
-
691
- // root-relative runtime assets emitted by the shell and engine vite
692
- // builds. only intercept when the asset exists in the active runtime.
693
- if (isRootRuntimeAssetPath(pathname)) {
694
- const fullPath = resolveRuntimeFilePath(runtimeRoot, pathname)
695
- if (fullPath) {
696
- serveRuntimeFile(req, res, fullPath)
697
- return
698
- }
699
- }
700
-
701
- // serve the peach HTML shell — inject bundle URL + bridge port
702
- if (pathname === prefix || pathname === prefix + '/') {
703
- sendShellHtml(res, buildShellHtml(runtimeRoot, requestOrigin(req)))
704
- return
705
- }
706
-
707
- // serve runtime files under /__peachsim/*.
708
- if (pathname.startsWith(prefix + '/')) {
709
- const fullPath = resolveRuntimeFilePath(
710
- runtimeRoot,
711
- pathname.slice(prefix.length),
712
- )
713
- if (fullPath) {
714
- serveRuntimeFile(req, res, fullPath)
715
- return
716
- }
717
-
718
- // extensionless in-shell routes should still load the shell.
719
- const ext = path.extname(pathname)
720
- if (!ext) {
721
- sendShellHtml(res, buildShellHtml(runtimeRoot, requestOrigin(req)))
722
- return
723
- }
724
- }
725
-
726
- next()
727
- })
728
-
729
- const port = configuredPort
730
- const sootsimUrl = `http://localhost:${port}${prefix}/`
731
- console.log(`[peach] serving at ${sootsimUrl}`)
732
-
733
- if (appName && !process.env.CI && !process.env.PEACH_NO_OPEN) {
734
- server.httpServer?.once('listening', () => {
735
- const openPort = listeningPort()
736
- launchRnxDesktop(
737
- resolveRnxDesktopLaunchTarget(openPort, bundleForOrigin(devOrigin())),
738
- appName,
739
- )
740
- })
741
- }
742
- },
743
- }
744
- }
745
-
746
- export default peachPlugin