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
@@ -142,19 +142,6 @@ export const NATIVE_SEAM_MANIFEST: NativeSeamEntry[] = [
142
142
  notes:
143
143
  'ImageResizer TurboModule following ios/ImageResizer.mm: loader decode, rotation, scaling, and the file written to the app container',
144
144
  },
145
- {
146
- pkg: 'react-native-adjust',
147
- // upstream's `index.js` reads `NativeModules.Adjust` and
148
- // `NativeModules.AdjustEventEmitter` directly — there is no NativeAdjust
149
- // spec file. listed for documentation parity; the actual seam delivery is
150
- // through the bundle-loader stub-registry routing the package entry to
151
- // `stubs/react-native-adjust.ts`, which imports the native seam from this
152
- // target.
153
- seamBasenames: ['index'],
154
- target: seamPath('react-native-adjust'),
155
- notes:
156
- 'Adjust attribution SAAS — noop native side (Adjust + AdjustEventEmitter NativeModules), pure-JS classes (AdjustConfig/AdjustEvent/...) live in stubs/react-native-adjust.ts',
157
- },
158
145
  {
159
146
  pkg: 'expo-clipboard',
160
147
  // src/ExpoClipboard.ts — `requireNativeModule<ExpoClipboardModule>('ExpoClipboard')`.
@@ -1,13 +1,10 @@
1
1
  // what `one prebuild` writes into Images.xcassets from `native.app.ios`: the
2
2
  // AccentColor asset from `accentColor` and the entries of the `assetCatalog`
3
- // folder. a One app with no ios/ on disk declares them only in the config its
4
- // dev server evaluated, so the plugin in that server reports them and the cli
5
- // stamps them into the page's app catalog the way it stamps a prebuilt one.
3
+ // folder. a One app with no ios/ on disk declares them only in its config.
6
4
 
7
5
  import path from 'node:path'
8
6
  import { isRecord } from './is-record'
9
-
10
- export const ONE_NATIVE_APP_CATALOG_ROUTE = '/__peach/native-app-catalog'
7
+ import { readOneNativeApp } from './one-native-app-config'
11
8
 
12
9
  const HEX_COLOR = /^#[\da-f]{6}$/i
13
10
 
@@ -32,28 +29,12 @@ function parseAccent(value: unknown): OneNativeAppAccent | null {
32
29
  return { light: value.light, dark }
33
30
  }
34
31
 
35
- export function parseOneNativeAppCatalog(value: unknown): OneNativeAppCatalog | null {
36
- if (!isRecord(value)) return null
37
- const accentColor = parseAccent(value.accentColor)
32
+ // the catalog folder resolves against the app root, as prebuild resolves it.
33
+ export function readOneNativeAppCatalog(root: string): OneNativeAppCatalog | null {
34
+ const ios = readOneNativeApp(root)?.ios
35
+ if (!isRecord(ios)) return null
36
+ const accentColor = parseAccent(ios.accentColor)
38
37
  const assetCatalog =
39
- typeof value.assetCatalog === 'string' && path.isAbsolute(value.assetCatalog)
40
- ? value.assetCatalog
41
- : null
38
+ typeof ios.assetCatalog === 'string' ? path.resolve(root, ios.assetCatalog) : null
42
39
  return accentColor || assetCatalog ? { accentColor, assetCatalog } : null
43
40
  }
44
-
45
- // the native entry config One's dev server holds on globalThis; the catalog
46
- // folder resolves against the app root, as prebuild resolves it.
47
- export function readOneNativeAppCatalog(
48
- entryConfig: unknown,
49
- root: string,
50
- ): OneNativeAppCatalog | null {
51
- const app = isRecord(entryConfig) ? entryConfig.app : undefined
52
- const ios = isRecord(app) ? app.ios : undefined
53
- if (!isRecord(ios)) return null
54
- return parseOneNativeAppCatalog({
55
- accentColor: ios.accentColor,
56
- assetCatalog:
57
- typeof ios.assetCatalog === 'string' ? path.resolve(root, ios.assetCatalog) : null,
58
- })
59
- }
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { parseSync, type Expression, type ObjectExpression } from 'oxc-parser'
4
+ import { isRecord } from './is-record'
5
+ import { visitParsedProgram } from './visit-parsed-program'
6
+
7
+ const CONFIG_FILES = [
8
+ 'vite.config.ts',
9
+ 'vite.config.mts',
10
+ 'vite.config.js',
11
+ 'vite.config.mjs',
12
+ ]
13
+
14
+ export function oneConfigPath(root: string): string | null {
15
+ for (const name of CONFIG_FILES) {
16
+ const file = path.join(root, name)
17
+ if (fs.existsSync(file)) return file
18
+ }
19
+ return null
20
+ }
21
+
22
+ const NOT_STATIC = Symbol('not static')
23
+
24
+ function staticValue(node: Expression): unknown {
25
+ switch (node.type) {
26
+ case 'Literal':
27
+ return node.value
28
+ case 'TemplateLiteral':
29
+ return node.expressions.length === 0
30
+ ? node.quasis.map((quasi) => quasi.value.cooked).join('')
31
+ : NOT_STATIC
32
+ case 'UnaryExpression':
33
+ if (node.operator === '-' && node.argument.type === 'Literal') {
34
+ const value = node.argument.value
35
+ return typeof value === 'number' ? -value : NOT_STATIC
36
+ }
37
+ return NOT_STATIC
38
+ case 'TSAsExpression':
39
+ case 'TSSatisfiesExpression':
40
+ case 'ParenthesizedExpression':
41
+ return staticValue(node.expression)
42
+ case 'ArrayExpression': {
43
+ const items: unknown[] = []
44
+ for (const element of node.elements) {
45
+ if (!element || element.type === 'SpreadElement') return NOT_STATIC
46
+ const value = staticValue(element)
47
+ if (value === NOT_STATIC) return NOT_STATIC
48
+ items.push(value)
49
+ }
50
+ return items
51
+ }
52
+ case 'ObjectExpression':
53
+ return staticObject(node)
54
+ default:
55
+ return NOT_STATIC
56
+ }
57
+ }
58
+
59
+ // properties computed at runtime read as absent, the way a config without them reads.
60
+ function staticObject(node: ObjectExpression): Record<string, unknown> {
61
+ const out: Record<string, unknown> = {}
62
+ for (const property of node.properties) {
63
+ if (property.type !== 'Property' || property.computed || property.kind !== 'init')
64
+ continue
65
+ const key =
66
+ property.key.type === 'Identifier'
67
+ ? property.key.name
68
+ : property.key.type === 'Literal'
69
+ ? String(property.key.value)
70
+ : null
71
+ if (key === null) continue
72
+ const value = staticValue(property.value)
73
+ if (value !== NOT_STATIC) out[key] = value
74
+ }
75
+ return out
76
+ }
77
+
78
+ // One's native.app is plain data, so it reads from the `one({ native: { app } })`
79
+ // call in the app's vite config without evaluating the config.
80
+ export function readOneNativeApp(root: string): Record<string, unknown> | null {
81
+ const file = oneConfigPath(root)
82
+ if (!file) return null
83
+ const { program } = parseSync(file, fs.readFileSync(file, 'utf8'))
84
+ let app: Record<string, unknown> | null = null
85
+ visitParsedProgram(program, {
86
+ CallExpression(call) {
87
+ if (app || call.callee.type !== 'Identifier' || call.callee.name !== 'one') return
88
+ const [options] = call.arguments
89
+ if (options?.type !== 'ObjectExpression') return
90
+ const { native } = staticObject(options)
91
+ if (isRecord(native) && isRecord(native.app)) app = native.app
92
+ },
93
+ })
94
+ return app
95
+ }
@@ -0,0 +1,250 @@
1
+ // a One app's Swift packages and Kotlin module, compiled for the app root the
2
+ // launch names (`?root=`), with one socket per root announcing edits, as
3
+ // prebuild compiles the same sources into the app.
4
+
5
+ import fs from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import path from 'node:path'
8
+ import { fileURLToPath, pathToFileURL } from 'node:url'
9
+ import { WebSocket, WebSocketServer } from 'ws'
10
+ import { isLoopbackHost } from './backend-origin'
11
+ import { KOTLIN_PACKAGE_PATH } from './kotlinDiscoveryContract'
12
+ import { configuredOneWidget } from './one-widget-metadata'
13
+ import { ONE_WIDGET_PACKAGE, oneWidgetPackage } from './one-widget-package'
14
+ import { ONE_WIDGET_PATH } from './oneWidgetContract'
15
+ import { swiftPackageMetadata, swiftPackageWatchFiles } from './swift-host'
16
+ import { SWIFT_HMR_PATH, SWIFT_PACKAGE_PATH } from './swift-submit'
17
+ import { privateSwiftDistributionRoot } from './swift-toolchain'
18
+ import type { IncomingMessage, ServerResponse } from 'node:http'
19
+ import type { Duplex } from 'node:stream'
20
+
21
+ interface App {
22
+ root: string
23
+ origin: string
24
+ sockets: WebSocketServer
25
+ watched: Set<string>
26
+ // active swift packages: each one's directory and the other files it rebuilds on
27
+ active: Map<string, { packagePath: string; files: Set<string> }>
28
+ packages?: Map<string, string>
29
+ kotlinModule?: string
30
+ }
31
+
32
+ const apps = new Map<string, App>()
33
+
34
+ // the workspace module beside peachsim compiles locally; an install has none,
35
+ // and its packages compile on Contrast
36
+ function swiftModuleRoot(): string | undefined {
37
+ if (privateSwiftDistributionRoot()) return undefined
38
+ const root = path.resolve(
39
+ path.dirname(fileURLToPath(import.meta.url)),
40
+ '../../sootsim-swift',
41
+ )
42
+ return fs.existsSync(path.join(root, 'toolchain.json')) ? root : undefined
43
+ }
44
+
45
+ function appFor(url: URL, origin: string): App | null {
46
+ const requested = url.searchParams.get('root')
47
+ if (!requested || !path.isAbsolute(requested) || !fs.existsSync(requested)) return null
48
+ const root = fs.realpathSync(requested)
49
+ let app = apps.get(root)
50
+ if (!app) {
51
+ app = {
52
+ root,
53
+ origin,
54
+ sockets: new WebSocketServer({ noServer: true }),
55
+ watched: new Set(),
56
+ active: new Map(),
57
+ }
58
+ apps.set(root, app)
59
+ }
60
+ return app
61
+ }
62
+
63
+ function send(app: App, change: object) {
64
+ const message = JSON.stringify(change)
65
+ for (const client of app.sockets.clients)
66
+ if (client.readyState === WebSocket.OPEN) client.send(message)
67
+ }
68
+
69
+ // One owns the package id rule, so the app's own One install names its packages
70
+ async function swiftPackages(root: string): Promise<Map<string, string>> {
71
+ const resolved = createRequire(path.join(root, 'package.json')).resolve(
72
+ 'vxrn/swift-package-id',
73
+ )
74
+ const loaded: { swiftPackageDirectories?: unknown } = await import(
75
+ pathToFileURL(resolved).href
76
+ )
77
+ const directories =
78
+ typeof loaded.swiftPackageDirectories === 'function'
79
+ ? loaded.swiftPackageDirectories(root)
80
+ : null
81
+ if (!(directories instanceof Map))
82
+ throw new Error('vxrn/swift-package-id has no swiftPackageDirectories')
83
+ const packages = new Map<string, string>()
84
+ for (const [name, directory] of directories)
85
+ if (typeof name === 'string' && typeof directory === 'string')
86
+ packages.set(name, directory)
87
+ return packages
88
+ }
89
+
90
+ async function packageMetadata(app: App, packageName: string) {
91
+ const widget =
92
+ packageName === ONE_WIDGET_PACKAGE ? await oneWidgetPackage(app.root) : null
93
+ app.packages ??= await swiftPackages(app.root)
94
+ if (widget && app.packages.has(packageName))
95
+ throw new Error(
96
+ `swift package ${packageName} conflicts with One's generated widget extension`,
97
+ )
98
+ const packagePath = widget?.packagePath ?? app.packages.get(packageName)
99
+ if (!packagePath) throw new Error(`swift package ${packageName} was not found`)
100
+ const moduleRoot = swiftModuleRoot()
101
+ const built = await swiftPackageMetadata(
102
+ packagePath,
103
+ packageName,
104
+ moduleRoot,
105
+ app.origin,
106
+ )
107
+ if (!app.active.has(packageName)) {
108
+ const files = [
109
+ ...(await swiftPackageWatchFiles(packagePath, moduleRoot)),
110
+ ...(widget?.watched ?? []),
111
+ ]
112
+ app.active.set(packageName, { packagePath, files: new Set(files) })
113
+ watch(app, packagePath, true)
114
+ for (const file of files)
115
+ if (!file.startsWith(`${packagePath}${path.sep}`)) watch(app, path.dirname(file))
116
+ }
117
+ return {
118
+ ...built,
119
+ hmrPath: SWIFT_HMR_PATH,
120
+ ...(widget ? { widget: widget.widget } : {}),
121
+ }
122
+ }
123
+
124
+ function changed(app: App, file: string) {
125
+ if (path.basename(file) === 'Package.swift') app.packages = undefined
126
+ for (const [packageName, { packagePath, files }] of app.active) {
127
+ if (!files.has(file) && !file.startsWith(`${packagePath}${path.sep}`)) continue
128
+ packageMetadata(app, packageName).then(
129
+ (metadata) => send(app, { type: 'package', packageName, metadata }),
130
+ (error: unknown) =>
131
+ send(app, {
132
+ type: 'error',
133
+ packageName,
134
+ message: error instanceof Error ? error.message : String(error),
135
+ }),
136
+ )
137
+ }
138
+ const kotlinModule = app.kotlinModule
139
+ if (
140
+ kotlinModule &&
141
+ (file.endsWith('.kt') || file.startsWith(`${kotlinModule}${path.sep}`))
142
+ )
143
+ send(app, { type: 'kotlin', packageName: 'kotlin' })
144
+ }
145
+
146
+ function watch(app: App, directory: string, recursive = false) {
147
+ if (app.watched.has(directory) || !fs.existsSync(directory)) return
148
+ app.watched.add(directory)
149
+ fs.watch(directory, { recursive }, (_event, name) => {
150
+ if (name && !name.split(path.sep).includes('node_modules'))
151
+ changed(app, path.join(directory, name))
152
+ })
153
+ }
154
+
155
+ function loopbackClient(req: IncomingMessage): boolean {
156
+ const remote = req.socket.remoteAddress?.replace(/^::ffff:/, '')
157
+ const origin = req.headers.origin
158
+ return (
159
+ !!remote &&
160
+ isLoopbackHost(remote) &&
161
+ (!origin || isLoopbackHost(new URL(origin).hostname))
162
+ )
163
+ }
164
+
165
+ // answers One's Swift package metadata and Kotlin module routes
166
+ export async function handleOneNativeSourceRequest(
167
+ req: IncomingMessage,
168
+ res: ServerResponse,
169
+ ): Promise<boolean> {
170
+ const url = new URL(req.url ?? '/', 'http://localhost')
171
+ const isSwift = url.pathname.startsWith(SWIFT_PACKAGE_PATH)
172
+ if (
173
+ !isSwift &&
174
+ url.pathname !== KOTLIN_PACKAGE_PATH &&
175
+ url.pathname !== ONE_WIDGET_PATH
176
+ )
177
+ return false
178
+ if (!loopbackClient(req)) {
179
+ res.writeHead(403)
180
+ res.end('native source requires a loopback client')
181
+ return true
182
+ }
183
+ res.setHeader('access-control-allow-origin', req.headers.origin ?? '*')
184
+ res.setHeader('vary', 'origin')
185
+ const app = req.headers.host ? appFor(url, `http://${req.headers.host}`) : null
186
+ if (!app) {
187
+ res.writeHead(400)
188
+ res.end('missing absolute app root')
189
+ return true
190
+ }
191
+ try {
192
+ if (url.pathname === ONE_WIDGET_PATH) {
193
+ const bundle = url.searchParams.get('bundle')
194
+ if (!bundle) {
195
+ res.writeHead(400)
196
+ res.end('missing bundle')
197
+ return true
198
+ }
199
+ const packageUrl = new URL(`${SWIFT_PACKAGE_PATH}${ONE_WIDGET_PACKAGE}`, app.origin)
200
+ packageUrl.searchParams.set('root', app.root)
201
+ const widget = await configuredOneWidget(app.root, bundle, packageUrl.href)
202
+ res.setHeader('content-type', 'application/json')
203
+ res.end(JSON.stringify(widget))
204
+ return true
205
+ }
206
+ if (isSwift) {
207
+ const packageName = decodeURIComponent(
208
+ url.pathname.slice(SWIFT_PACKAGE_PATH.length),
209
+ )
210
+ const metadata = await packageMetadata(app, packageName)
211
+ res.setHeader('content-type', 'application/json')
212
+ res.end(JSON.stringify(metadata))
213
+ return true
214
+ }
215
+ const kotlin = await import('./kotlin-host')
216
+ if (!app.kotlinModule) {
217
+ app.kotlinModule = kotlin.peachKotlinModuleRoot()
218
+ watch(app, app.root, true)
219
+ watch(app, app.kotlinModule, true)
220
+ }
221
+ return await kotlin.serveKotlinRequest(url.pathname, res, {
222
+ root: app.root,
223
+ moduleRoot: app.kotlinModule,
224
+ origin: app.origin,
225
+ hmrPath: SWIFT_HMR_PATH,
226
+ })
227
+ } catch (error) {
228
+ if (!res.headersSent) res.writeHead(500)
229
+ res.end(error instanceof Error ? error.message : String(error))
230
+ return true
231
+ }
232
+ }
233
+
234
+ export function handleOneNativeSourceUpgrade(
235
+ req: IncomingMessage,
236
+ socket: Duplex,
237
+ head: Buffer,
238
+ ): boolean {
239
+ const url = new URL(req.url ?? '/', 'http://localhost')
240
+ if (url.pathname !== SWIFT_HMR_PATH) return false
241
+ const app = req.headers.host ? appFor(url, `http://${req.headers.host}`) : null
242
+ if (!app || !loopbackClient(req)) {
243
+ socket.destroy()
244
+ return true
245
+ }
246
+ app.sockets.handleUpgrade(req, socket, head, (client) => {
247
+ app.sockets.emit('connection', client, req)
248
+ })
249
+ return true
250
+ }
@@ -1,146 +1,63 @@
1
- import { execFile } from 'node:child_process'
2
1
  import { createHash } from 'node:crypto'
3
2
  import fs from 'node:fs'
4
- import { createRequire } from 'node:module'
5
3
  import path from 'node:path'
6
- import { promisify } from 'node:util'
7
- import { PEACH_FORKED_SCRIPT_ENV } from './forked-script-contract'
8
4
  import { isRecord } from './is-record'
5
+ import { oneConfigPath, readOneNativeApp } from './one-native-app-config'
9
6
  import { isHomeWidgetFamily } from './oneWidgetContract'
10
7
  import { readPackageFile } from './swift-source-file'
11
- import { MAX_SWIFT_COMPILE_SOURCE_BYTES, SWIFT_PACKAGE_PATH } from './swift-submit'
8
+ import { MAX_SWIFT_COMPILE_SOURCE_BYTES } from './swift-submit'
12
9
  import type {
13
10
  ConfiguredOneWidget,
14
11
  HomeWidgetFamily,
15
12
  OneWidgetMetadata,
16
13
  } from './oneWidgetContract'
17
14
 
18
- const run = promisify(execFile)
19
15
  export const ONE_WIDGET_PACKAGE = 'OneWidgets'
20
16
 
21
17
  type WidgetConfig = Omit<OneWidgetMetadata, 'sources' | 'families'>
22
18
 
23
- interface ConfigRead {
24
- urlSchemes: string[]
25
- widget: WidgetConfig | null
26
- watched: string[]
27
- stamp: string
28
- }
29
-
30
- const configs = new Map<string, ConfigRead>()
31
- const reads = new Map<string, Promise<ConfigRead>>()
32
- const CONFIG_CHILD = `
33
- import fs from 'node:fs';
34
- import { loadUserOneOptions } from 'one/vite';
35
- const { config, oneOptions } = await loadUserOneOptions('serve', true);
36
- const app = oneOptions.native?.app;
37
- const widgets = app?.ios?.widgets;
38
- fs.writeFileSync(process.argv[2], JSON.stringify({
39
- widget: widgets ? { appName: app.name, bundleId: app.ios.bundleId,
40
- suite: widgets.appGroup, kind: widgets.kind, displayName: widgets.displayName,
41
- description: widgets.description } : null,
42
- urlSchemes: app?.scheme === undefined ? [] : Array.isArray(app.scheme) ? app.scheme : [app.scheme],
43
- watched: [config.path, ...config.dependencies]
44
- }));
45
- `
19
+ const nonEmpty = (value: unknown): value is string => typeof value === 'string' && !!value
46
20
 
47
- function configStamp(files: string[]): string {
48
- return JSON.stringify(
49
- files.map((file) => {
50
- if (!fs.existsSync(file)) return [file, null]
51
- const stat = fs.statSync(file)
52
- return [file, stat.mtimeMs, stat.ctimeMs, stat.size]
53
- }),
21
+ function readConfig(root: string) {
22
+ const configPath = oneConfigPath(root)
23
+ const app = readOneNativeApp(root)
24
+ const scheme = app?.scheme
25
+ const urlSchemes = scheme === undefined ? [] : Array.isArray(scheme) ? scheme : [scheme]
26
+ if (
27
+ !urlSchemes.every(
28
+ (entry): entry is string =>
29
+ typeof entry === 'string' && /^[A-Za-z][A-Za-z0-9+.-]*$/.test(entry),
30
+ )
54
31
  )
55
- }
56
-
57
- async function readConfig(root: string): Promise<ConfigRead> {
58
- const cached = configs.get(root)
59
- if (cached && cached.stamp === configStamp(cached.watched)) return cached
60
- const reading = reads.get(root)
61
- if (reading) return reading
62
- const promise = (async () => {
63
- // resolve before launching: an app without One is not a configured One app.
64
- createRequire(path.join(root, 'package.json')).resolve('one/vite')
65
- const cache = path.join(root, 'node_modules/.cache/peach-widget-config')
66
- fs.mkdirSync(cache, { recursive: true })
67
- const directory = fs.mkdtempSync(path.join(cache, 'read-'))
68
- const script = path.join(directory, 'read.mjs')
69
- const result = path.join(directory, 'result.json')
70
- fs.writeFileSync(script, CONFIG_CHILD)
71
- try {
72
- await run(process.execPath, [script, result], {
73
- cwd: root,
74
- env: { ...process.env, [PEACH_FORKED_SCRIPT_ENV]: '1' },
75
- timeout: 30_000,
76
- maxBuffer: 1024 * 1024,
77
- })
78
- const value: unknown = JSON.parse(fs.readFileSync(result, 'utf8'))
79
- if (
80
- !isRecord(value) ||
81
- !Array.isArray(value.watched) ||
82
- !value.watched.every((file): file is string => typeof file === 'string')
83
- )
84
- throw new Error('One config loader returned invalid dependencies')
85
- if (
86
- !Array.isArray(value.urlSchemes) ||
87
- !value.urlSchemes.every(
88
- (scheme): scheme is string =>
89
- typeof scheme === 'string' && /^[A-Za-z][A-Za-z0-9+.-]*$/.test(scheme),
90
- )
91
- )
92
- throw new Error('One config loader returned invalid native.app.scheme')
93
- let widget: WidgetConfig | null = null
94
- if (value.widget !== null) {
95
- const entry = value.widget
96
- if (
97
- !isRecord(entry) ||
98
- typeof entry.appName !== 'string' ||
99
- !/^[A-Za-z][A-Za-z0-9_]*$/.test(entry.appName) ||
100
- typeof entry.bundleId !== 'string' ||
101
- !entry.bundleId ||
102
- typeof entry.suite !== 'string' ||
103
- !entry.suite ||
104
- typeof entry.kind !== 'string' ||
105
- !entry.kind ||
106
- typeof entry.displayName !== 'string' ||
107
- !entry.displayName ||
108
- typeof entry.description !== 'string' ||
109
- !entry.description
110
- )
111
- throw new Error('One config loader returned invalid native.app.ios.widgets')
112
- widget = {
113
- appName: entry.appName,
114
- bundleId: entry.bundleId,
115
- suite: entry.suite,
116
- kind: entry.kind,
117
- displayName: entry.displayName,
118
- description: entry.description,
119
- }
120
- }
121
- const watched = [
122
- ...new Set([
123
- path.join(root, 'package.json'),
124
- ...value.watched.map((file) => path.resolve(root, file)),
125
- ]),
126
- ]
127
- const loaded = {
128
- widget,
129
- urlSchemes: value.urlSchemes,
130
- watched,
131
- stamp: configStamp(watched),
132
- }
133
- configs.set(root, loaded)
134
- return loaded
135
- } finally {
136
- fs.rmSync(directory, { recursive: true, force: true })
32
+ throw new Error('One config has an invalid native.app.scheme')
33
+ const ios = isRecord(app?.ios) ? app.ios : null
34
+ const widgets = ios?.widgets
35
+ let widget: WidgetConfig | null = null
36
+ if (widgets !== undefined) {
37
+ if (
38
+ !isRecord(widgets) ||
39
+ typeof app?.name !== 'string' ||
40
+ !/^[A-Za-z][A-Za-z0-9_]*$/.test(app.name) ||
41
+ !nonEmpty(ios?.bundleId) ||
42
+ !nonEmpty(widgets.appGroup) ||
43
+ !nonEmpty(widgets.kind) ||
44
+ !nonEmpty(widgets.displayName) ||
45
+ !nonEmpty(widgets.description)
46
+ )
47
+ throw new Error('One config has an invalid native.app.ios.widgets')
48
+ widget = {
49
+ appName: app.name,
50
+ bundleId: ios.bundleId,
51
+ suite: widgets.appGroup,
52
+ kind: widgets.kind,
53
+ displayName: widgets.displayName,
54
+ description: widgets.description,
137
55
  }
138
- })()
139
- reads.set(root, promise)
140
- try {
141
- return await promise
142
- } finally {
143
- reads.delete(root)
56
+ }
57
+ return {
58
+ widget,
59
+ urlSchemes,
60
+ watched: [path.join(root, 'package.json'), ...(configPath ? [configPath] : [])],
144
61
  }
145
62
  }
146
63
 
@@ -161,7 +78,7 @@ function declaredFamilies(source: string): HomeWidgetFamily[] {
161
78
 
162
79
  export async function readOneWidgetSources(appRoot: string) {
163
80
  const root = fs.realpathSync(appRoot)
164
- const config = await readConfig(root)
81
+ const config = readConfig(root)
165
82
  if (!config.widget) return null
166
83
  const widget = config.widget
167
84
  const sourceFiles = {
@@ -209,9 +126,11 @@ export async function readOneWidgetSources(appRoot: string) {
209
126
  }
210
127
  }
211
128
 
129
+ // `packageUrl` is where the Peach host compiles the generated widget package
212
130
  export async function configuredOneWidget(
213
131
  appRoot: string,
214
132
  bundleUrl: string,
133
+ packageUrl: string,
215
134
  ): Promise<ConfiguredOneWidget | null> {
216
135
  const source = await readOneWidgetSources(appRoot)
217
136
  if (!source) return null
@@ -222,7 +141,7 @@ export async function configuredOneWidget(
222
141
  .update(JSON.stringify([source.root, source.widget.bundleId]))
223
142
  .digest('hex'),
224
143
  bundleUrl,
225
- packageUrl: new URL(`${SWIFT_PACKAGE_PATH}OneWidgets`, bundleUrl).href,
144
+ packageUrl,
226
145
  urlSchemes: source.urlSchemes,
227
146
  }
228
147
  }