peachsim 0.1.2000 → 0.1.2002

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 (112) hide show
  1. package/cli/commands/control.ts +1 -0
  2. package/cli/commands/package.ts +2 -0
  3. package/cli/commands/shell-url.ts +4 -0
  4. package/dist-lib/agent-daemon-client.cjs +1 -1
  5. package/dist-lib/agent-events.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +1 -1
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +1 -1
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +1 -1
  16. package/dist-lib/bundle-channel.cjs +22481 -21950
  17. package/dist-lib/capture-contract.cjs +1 -1
  18. package/dist-lib/capture-contract.mjs +1 -1
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +1 -1
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +1 -1
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +1 -1
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/config.mjs +1 -1
  27. package/dist-lib/detox/index.cjs +8 -2
  28. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  29. package/dist-lib/expo-swift-bundle.cjs +2872 -2838
  30. package/dist-lib/expo-swift-metadata.cjs +1 -1
  31. package/dist-lib/expo-swift-metadata.mjs +1 -1
  32. package/dist-lib/home-paths.cjs +1 -1
  33. package/dist-lib/host/bridge-host.cjs +4195 -3717
  34. package/dist-lib/host/fetch-proxy-handler.cjs +2 -2
  35. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  36. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  37. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  38. package/dist-lib/host/websocket-proxy.cjs +1 -1
  39. package/dist-lib/index.cjs +3 -3
  40. package/dist-lib/jump-to-source-babel.cjs +1 -1
  41. package/dist-lib/jump-to-source-native.cjs +1 -1
  42. package/dist-lib/kotlin-host.cjs +1 -1
  43. package/dist-lib/menu.cjs +1 -1
  44. package/dist-lib/menu.mjs +1 -1
  45. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  47. package/dist-lib/metro-production-bundle.cjs +1 -1
  48. package/dist-lib/metro-production-bundle.mjs +1 -1
  49. package/dist-lib/metro.cjs +3 -3
  50. package/dist-lib/native-app-identity-project.cjs +2 -2
  51. package/dist-lib/native-app-identity-project.mjs +2 -2
  52. package/dist-lib/native-app-identity.cjs +2 -3
  53. package/dist-lib/native-app-identity.mjs +2 -3
  54. package/dist-lib/native-firebase-metadata.cjs +1 -1
  55. package/dist-lib/native-firebase-metadata.mjs +1 -1
  56. package/dist-lib/pdfium-raster.cjs +1 -1
  57. package/dist-lib/pdfium-raster.mjs +1 -1
  58. package/dist-lib/plist.cjs +1 -1
  59. package/dist-lib/plist.mjs +1 -1
  60. package/dist-lib/profiles.cjs +1 -1
  61. package/dist-lib/public-brand.cjs +1 -1
  62. package/dist-lib/public-origins-lib-esm.json +24 -24
  63. package/dist-lib/public-origins-lib.json +108 -94
  64. package/dist-lib/react-native-host-modules.cjs +1 -1
  65. package/dist-lib/react-native-host-modules.mjs +1 -1
  66. package/dist-lib/reap-browser.cjs +1 -1
  67. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  68. package/dist-lib/sdk.cjs +1 -1
  69. package/dist-lib/sdk.mjs +1 -1
  70. package/dist-lib/skills.cjs +4860 -4340
  71. package/dist-lib/swift-compile.cjs +13 -33
  72. package/dist-lib/swift-compile.mjs +13 -33
  73. package/dist-lib/swift-package.cjs +1 -1
  74. package/dist-lib/swift-package.mjs +1 -1
  75. package/dist-lib/swift-submit.cjs +1 -1
  76. package/dist-lib/swift-submit.mjs +1 -1
  77. package/dist-lib/swift-toolchain.cjs +1 -1
  78. package/dist-lib/swift.cjs +1 -1
  79. package/dist-lib/vite-swift.cjs +14 -34
  80. package/dist-lib/vite.cjs +2 -2
  81. package/dist-lib/worklet-executable.cjs +1 -1
  82. package/dist-lib/worklet-executable.mjs +1 -1
  83. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +0 -6
  84. package/dist-types/packages/peach-engine/src/render-worker/metro-bundle-metadata.d.ts +2 -0
  85. package/dist-types/packages/peach-engine/src/settings/duo-fold-bus.d.ts +1 -0
  86. package/package.json +1 -1
  87. package/runtime-companion.json +1 -1
  88. package/sdk/ios/System/Library/Frameworks/QuartzCore.framework/Modules/module.modulemap +1 -0
  89. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIActivityViewController.h +1 -1
  90. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UICalendarViewDecoration.h +1 -1
  91. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UICollectionViewFlowLayout.h +1 -1
  92. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UICollectionViewLayout.h +2 -2
  93. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIDiffableDataSource.h +2 -2
  94. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes +0 -1
  95. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIPasteboard.h +4 -4
  96. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIPrintInteractionController.h +2 -7
  97. package/sdk/ios/System/Library/Frameworks/UIKitText.framework/Headers/UIKitText.apinotes +46 -0
  98. package/sdk/ios/System/Library/Frameworks/UIKitTypes.framework/Headers/UIKitTypes.h +13 -5
  99. package/src/expo-native-workspace.ts +7 -2
  100. package/src/expo-swift-ready.ts +8 -0
  101. package/src/host/bridge-host.ts +6 -0
  102. package/src/native-app-identity.ts +1 -2
  103. package/src/native-bundles.ts +15 -0
  104. package/src/nitro-adapter.lock.json +275 -275
  105. package/src/nitro-superset.lock.json +4 -4
  106. package/src/one-sdk/source.ts +341 -0
  107. package/src/one-sdk-bundle.ts +109 -0
  108. package/src/one-sdk-preparation.ts +59 -0
  109. package/src/oneSdkContract.ts +77 -0
  110. package/src/swift-compile.ts +22 -33
  111. package/src/swift-distribution.lock.json +12 -11
  112. package/src/turbo-runtime.lock.json +22 -22
@@ -0,0 +1,341 @@
1
+ export const oneSDKModule = String.raw`import SwiftUI
2
+
3
+ // the public surface of One's device module (packages/one/ios/OneSwiftPackage.swift
4
+ // in ~/one), which One's pod implicitly imports into every source of a swift
5
+ // package. the declarations live in the SwiftUI module, which Peach's own
6
+ // entry points need; these aliases name the same types, so a file that
7
+ // imports SwiftUI as well sees no ambiguity.
8
+ public typealias JSON = SwiftUI.JSON
9
+ public typealias PeachPackage = SwiftUI.PeachPackage
10
+ public typealias PeachModule = SwiftUI.PeachModule
11
+
12
+ public protocol OneNativeCompositionParent: AnyObject {
13
+ var compositionActive: Bool { get }
14
+ func refreshRow(for child: UIView)
15
+ }
16
+
17
+ extension OneNativeCompositionParent {
18
+ public func refreshRow(for child: UIView) {}
19
+ }
20
+
21
+ public protocol OneNativeComposable: UIView {
22
+ func compositionContent() -> AnyView
23
+ func composeInto(_ parent: any OneNativeCompositionParent)
24
+ func decompose()
25
+ func propagateActive(_ active: Bool)
26
+ }
27
+
28
+ extension OneNativeComposable {
29
+ public func propagateActive(_ active: Bool) {}
30
+ }
31
+ `
32
+
33
+ export const oneSDKApp = String.raw`import SwiftUI
34
+ @_spi(Peach) import UIKit
35
+ import One
36
+ import OneSDKBindings
37
+
38
+ private struct UIKitHost: UIViewRepresentable {
39
+ let props: JSON
40
+ func makeUIView(context: Context) -> OneNativeUIKitHostView { OneNativeUIKitHostView() }
41
+ func updateUIView(_ view: OneNativeUIKitHostView, context: Context) {
42
+ view.configure(viewId: props["viewId"]?.doubleValue ?? 0)
43
+ view.configureAccessibility(props["accessibilityLabel"]?.stringValue ?? "",
44
+ hint: props["accessibilityHint"]?.stringValue ?? "",
45
+ value: props["accessibilityValue"]?.stringValue ?? "",
46
+ identifier: props["testID"]?.stringValue ?? "")
47
+ }
48
+ static func dismantleUIView(_ view: OneNativeUIKitHostView, coordinator: Coordinator) { view.reset() }
49
+ }
50
+
51
+ @main
52
+ struct SDKGuest: PeachPackage {
53
+ func view(props: JSON) -> some View { UIKitHost(props: props) }
54
+ }
55
+ `
56
+
57
+ export const oneSDKTransport = String.raw`import Foundation
58
+ import CoreFoundation
59
+ import CoreGraphics
60
+ import ObjectiveC
61
+ @_spi(Peach) import UIKit
62
+ import One
63
+
64
+ private final class SDKChannel {
65
+ let token: Int
66
+ init(_ token: Int) { self.token = token }
67
+ deinit { _PeachNativeStub.call("PeachOneSDK", "release", [token]) }
68
+ func send(_ method: String, _ fields: [String: Any]) -> Any? {
69
+ _PeachNativeStub.call("PeachOneSDK", method, [token, fields])
70
+ }
71
+ }
72
+
73
+ private enum SDKTransport {
74
+ nonisolated(unsafe) static var handles: [Int: OneSDKHandleBox] = [:]
75
+ nonisolated(unsafe) static var nextHandle = 0
76
+ nonisolated(unsafe) static var subscriptions: [Int: () -> Void] = [:]
77
+ nonisolated(unsafe) static var contents: [Int: (view: OneNativeContentView, source: Int, item: Int)] = [:]
78
+ nonisolated(unsafe) static var reply: UnsafeMutableRawPointer?
79
+
80
+ static func typeName(_ type: Any.Type) -> String {
81
+ let name = String(reflecting: type)
82
+ let owner = name.split(separator: ".", maxSplits: 1).first.map(String.init) ?? ""
83
+ if ["UIKitCore", "UIKitText", "UIKitEnums", "Foundation"].contains(owner), let object = type as? AnyClass {
84
+ let runtimeName = String(cString: class_getName(object))
85
+ if !runtimeName.hasPrefix("_Tt") { return runtimeName }
86
+ }
87
+ if ["UIKitCore", "UIKitText", "UIKitEnums"].contains(owner) {
88
+ return "UIKit" + name.dropFirst(owner.count)
89
+ }
90
+ return name
91
+ }
92
+
93
+ static func metadata(_ box: OneSDKHandleBox) -> [String: Any] {
94
+ nextHandle += 1
95
+ handles[nextHandle] = box
96
+ var names: [String] = []
97
+ if let type = type(of: box.value) as? AnyClass {
98
+ var at: AnyClass? = class_getSuperclass(type)
99
+ while let current = at, current != NSObject.self {
100
+ names.append(typeName(current))
101
+ at = class_getSuperclass(current)
102
+ }
103
+ }
104
+ var result: [String: Any] = ["id": nextHandle, "typeName": typeName(type(of: box.value)), "identity": box.identity, "superclasses": names]
105
+ if box.value is OneSDKCallable { result["callable"] = true }
106
+ return result
107
+ }
108
+
109
+ static func envelope(_ data: [String: Any], _ existing: [OneSDKHandleBox] = []) -> [String: Any] {
110
+ var outputHandles = existing.map(metadata)
111
+ var buffers: [String] = []
112
+ var nonfinite: [[String: Any]] = []
113
+ func pack(_ value: Any, _ path: [String]) -> Any {
114
+ if value is NSNull { return NSNull() }
115
+ if let box = value as? OneSDKHandleBox {
116
+ let index = outputHandles.count
117
+ outputHandles.append(metadata(box))
118
+ return ["$h": index]
119
+ }
120
+ if let data = value as? Data {
121
+ let index = buffers.count
122
+ buffers.append(data.base64EncodedString())
123
+ return ["$b": index]
124
+ }
125
+ if let date = value as? Date { return pack(["$date": date.timeIntervalSince1970 * 1000], path) }
126
+ if let rect = value as? CGRect { return pack(["x": rect.origin.x, "y": rect.origin.y, "width": rect.width, "height": rect.height], path) }
127
+ if let point = value as? CGPoint { return pack(["x": point.x, "y": point.y], path) }
128
+ if let size = value as? CGSize { return pack(["width": size.width, "height": size.height], path) }
129
+ if let number = value as? NSNumber {
130
+ if !number.doubleValue.isFinite {
131
+ nonfinite.append(["path": path, "value": number.doubleValue.isNaN ? "NaN" : number.doubleValue > 0 ? "Infinity" : "-Infinity"])
132
+ return NSNull()
133
+ }
134
+ return number
135
+ }
136
+ if let string = value as? String { return string }
137
+ if let array = value as? [Any] { return array.enumerated().map { pack($0.element, path + [String($0.offset)]) } }
138
+ if let dictionary = value as? [String: Any] {
139
+ var result: [String: Any] = [:]
140
+ for (key, value) in dictionary { result[key] = pack(value, path + [key]) }
141
+ return result
142
+ }
143
+ preconditionFailure("invalid sdk wire value: \(type(of: value))")
144
+ }
145
+ let packed = pack(data, [])
146
+ return ["data": packed, "handles": outputHandles, "buffers": buffers, "nonfinite": nonfinite]
147
+ }
148
+
149
+ static func failure(_ error: Error, _ context: String? = nil) -> [String: Any] {
150
+ let native = error as NSError
151
+ let message = context.map { "E_SDK: \($0): \(native.localizedDescription)" } ?? native.localizedDescription
152
+ return envelope(["$error": ["message": message, "code": "E_SDK", "domain": native.domain, "nativeCode": Double(native.code)]])
153
+ }
154
+
155
+ static func boxes(_ values: Any?) throws -> [OneSDKHandleBox] {
156
+ guard let ids = values as? [Int] else { throw OneSDKError.unsupported("invalid sdk transport handles") }
157
+ return try ids.map { id in
158
+ guard let box = handles[id] else { throw OneSDKError.unsupported("released sdk handle \(id)") }
159
+ return box
160
+ }
161
+ }
162
+
163
+ static func input(_ value: [String: Any]) throws -> OneSDKCallbackReply {
164
+ guard var data = value["data"] as? [String: Any], let encoded = value["buffers"] as? [String], let nonfinite = value["nonfinite"] as? [[String: Any]] else {
165
+ throw OneSDKError.unsupported("invalid sdk transport envelope")
166
+ }
167
+ func restore(_ value: Any, _ path: ArraySlice<String>, _ number: Double) -> Any {
168
+ guard let key = path.first else { return number }
169
+ if var array = value as? [Any], let index = Int(key), array.indices.contains(index) {
170
+ array[index] = restore(array[index], path.dropFirst(), number)
171
+ return array
172
+ }
173
+ if var dictionary = value as? [String: Any], let child = dictionary[key] {
174
+ dictionary[key] = restore(child, path.dropFirst(), number)
175
+ return dictionary
176
+ }
177
+ return value
178
+ }
179
+ for item in nonfinite {
180
+ guard let path = item["path"] as? [String], let name = item["value"] as? String,
181
+ let number = ["NaN": Double.nan, "Infinity": Double.infinity, "-Infinity": -Double.infinity][name],
182
+ let restored = restore(data, path[...], number) as? [String: Any] else {
183
+ throw OneSDKError.unsupported("invalid sdk nonfinite number")
184
+ }
185
+ data = restored
186
+ }
187
+ let buffers = try encoded.map { text in
188
+ guard let bytes = Data(base64Encoded: text) else { throw OneSDKError.unsupported("invalid sdk buffer") }
189
+ return bytes
190
+ }
191
+ return OneSDKCallbackReply(data: data, handles: try boxes(value["handles"]), buffers: buffers)
192
+ }
193
+
194
+ static func call(_ value: [String: Any], _ channel: SDKChannel?, _ sync: Bool) throws -> OneSDKCall {
195
+ let input = try input(value)
196
+ let dispatch: OneSDKDispatch? = channel.map { channel in
197
+ { index, data, handles in _ = channel.send("dispatch", ["index": index, "result": envelope(data, handles)]) }
198
+ }
199
+ let syncDispatch: OneSDKSyncDispatch? = sync ? channel.map { channel in
200
+ { index, data, handles in
201
+ do {
202
+ guard let reply = channel.send("dispatchSync", ["index": index, "result": envelope(data, handles)]) as? [String: Any] else {
203
+ throw OneSDKError.callback("invalid synchronous callback reply")
204
+ }
205
+ return try self.input(reply)
206
+ } catch { return OneSDKCallbackReply(data: ["error": error.localizedDescription, "args": []], handles: []) }
207
+ }
208
+ } : nil
209
+ return try OneSDKCall(data: input.data, handles: input.handles, buffers: input.buffers, syncDispatch: syncDispatch, dispatch: dispatch)
210
+ }
211
+
212
+ @MainActor static func run(_ request: [String: Any]) throws -> [String: Any] {
213
+ guard let operation = request["operation"] as? String else { throw OneSDKError.unsupported("missing sdk operation") }
214
+ if operation == "content" {
215
+ guard let id = request["contentId"] as? Int, let source = request["sourceId"] as? Int,
216
+ let item = request["item"] as? Int, let height = request["height"] as? Double,
217
+ let estimate = request["estimatedHeight"] as? Double, let host = request["host"] as? String else {
218
+ throw OneSDKError.unsupported("invalid UIKit content props")
219
+ }
220
+ let view = OneNativeContentRegistry.view(forId: id)
221
+ view._peachReactContentHost = host
222
+ view.fixedHeight = height
223
+ view.estimatedHeight = estimate
224
+ if let previous = contents[id], previous.source != source || previous.item != item {
225
+ if previous.source > 0 { OneNativeCellSources.unregister(view, sourceId: previous.source, item: previous.item) }
226
+ }
227
+ if source > 0 { OneNativeCellSources.register(view, sourceId: source, item: item) }
228
+ contents[id] = (view, source, item)
229
+ return [:]
230
+ }
231
+ if operation == "measureContent" {
232
+ guard let id = request["contentId"] as? Int, let height = request["height"] as? Double else {
233
+ throw OneSDKError.unsupported("invalid UIKit content measurement")
234
+ }
235
+ contents[id]?.view.setMeasuredHeight(height)
236
+ return [:]
237
+ }
238
+ if operation == "unmountContent" {
239
+ guard let id = request["contentId"] as? Int else { throw OneSDKError.unsupported("invalid UIKit content id") }
240
+ if let content = contents.removeValue(forKey: id) {
241
+ content.view._peachReactContentHost = nil
242
+ content.view.retire()
243
+ if content.source > 0 { OneNativeCellSources.unregister(content.view, sourceId: content.source, item: content.item) }
244
+ }
245
+ OneNativeContentRegistry.unmount(id)
246
+ return [:]
247
+ }
248
+ if operation == "release" {
249
+ guard let ids = request["handles"] as? [Int] else { throw OneSDKError.unsupported("invalid sdk release") }
250
+ for id in ids { handles.removeValue(forKey: id) }
251
+ return [:]
252
+ }
253
+ guard let token = request["token"] as? Int else { throw OneSDKError.unsupported("missing sdk call token") }
254
+ if operation == "cancel" { subscriptions.removeValue(forKey: token)?(); return [:] }
255
+ let channel = SDKChannel(token)
256
+ if operation == "subscribe" {
257
+ do {
258
+ guard let id = request["handle"] as? Int, let box = handles[id] else { throw OneSDKError.unsupported("expected a handle from the sdk bindings") }
259
+ let subscription = try box.subscribe({ value in
260
+ let call = OneSDKCall(receiver: nil, argCount: 0)
261
+ _ = channel.send("event", envelope(["value": call.out(value)], call.handlesOut))
262
+ }, { _ = channel.send("event", failure($0)) })
263
+ subscriptions[token] = { subscription.cancel(); withExtendedLifetime(channel) {} }
264
+ } catch { _ = channel.send("event", failure(error)) }
265
+ return [:]
266
+ }
267
+ guard let module = request["module"] as? String, let number = request["id"] as? NSNumber else { throw OneSDKError.unsupported("missing sdk table or symbol") }
268
+ let id = number.int64Value
269
+ let context = "\(module) #\(id)"
270
+ do {
271
+ let call = try call(request, request["callbacks"] as? Bool == true ? channel : nil, operation == "callSync")
272
+ if operation == "callFunction" {
273
+ guard let handle = request["handle"] as? Int, let function = handles[handle]?.value as? OneSDKCallable else { throw OneSDKError.unsupported("expected a callable sdk handle") }
274
+ Task { @MainActor in
275
+ let result: [String: Any]
276
+ do { let value = try await function.call(call); call.retainImplementations([]); result = envelope(["value": value], call.handlesOut) }
277
+ catch { result = failure(error) }
278
+ _ = channel.send("complete", result)
279
+ }
280
+ return [:]
281
+ }
282
+ let table = try OneSDKTables.table(module)
283
+ if operation == "observe" {
284
+ let lifetime = OneSDKSubscription()
285
+ DispatchQueue.main.async {
286
+ lifetime.deliver {
287
+ do {
288
+ let observation = try table.observe(id, call, { value in
289
+ let output = OneSDKCall(receiver: nil, argCount: 0)
290
+ _ = channel.send("event", envelope(["value": output.out(value)], output.handlesOut))
291
+ })
292
+ lifetime.install { observation.cancel() }
293
+ } catch { _ = channel.send("event", failure(error)) }
294
+ }
295
+ }
296
+ subscriptions[token] = { lifetime.cancel(); withExtendedLifetime(channel) {} }
297
+ return [:]
298
+ }
299
+ if operation == "callAsync" {
300
+ Task { @MainActor in
301
+ let result: [String: Any]
302
+ do { let value = try await table.async(id, call); call.retainImplementations(table.argumentNames(id)); result = envelope(["value": value], call.handlesOut) }
303
+ catch { result = failure(error, context) }
304
+ _ = channel.send("complete", result)
305
+ }
306
+ return [:]
307
+ }
308
+ guard operation == "call" || operation == "callSync" else { throw OneSDKError.unsupported("sdk operation \(operation)") }
309
+ defer { if operation == "callSync" { call.endSynchronousCallbacks() } }
310
+ let value = try table.sync(id, call)
311
+ call.retainImplementations(table.argumentNames(id))
312
+ return envelope(["value": value], call.handlesOut)
313
+ } catch {
314
+ let result = failure(error, context)
315
+ if operation == "callAsync" || operation == "callFunction" { _ = channel.send("complete", result); return [:] }
316
+ if operation == "observe" { _ = channel.send("event", result); return [:] }
317
+ return result
318
+ }
319
+ }
320
+ }
321
+
322
+ @_expose(wasm, "peach_one_sdk")
323
+ @_cdecl("peach_one_sdk")
324
+ @MainActor
325
+ public func peachOneSDK(_ pointer: UnsafePointer<UInt8>, _ length: Int32) -> UnsafeMutableRawPointer {
326
+ let result: [String: Any]
327
+ do {
328
+ guard let request = try JSONSerialization.jsonObject(with: Data(bytes: pointer, count: Int(length))) as? [String: Any] else {
329
+ throw OneSDKError.unsupported("invalid sdk transport request")
330
+ }
331
+ result = try SDKTransport.run(request)
332
+ } catch { result = SDKTransport.failure(error) }
333
+ let data = try! JSONSerialization.data(withJSONObject: result)
334
+ SDKTransport.reply?.deallocate()
335
+ let reply = UnsafeMutableRawPointer.allocate(byteCount: data.count + 4, alignment: 4)
336
+ reply.storeBytes(of: UInt32(data.count).littleEndian, as: UInt32.self)
337
+ data.copyBytes(to: reply.advanced(by: 4).assumingMemoryBound(to: UInt8.self), count: data.count)
338
+ SDKTransport.reply = reply
339
+ return reply
340
+ }
341
+ `
@@ -0,0 +1,109 @@
1
+ import { createHash } from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { prepareNativeAppRoot } from './expo-native-workspace'
5
+ import { compiledModuleAssets, compiledModuleRequestHandler } from './nitro-bundle'
6
+ import { selectOneSDK } from './one-sdk-preparation'
7
+ import { oneSDKApp, oneSDKModule, oneSDKTransport } from './one-sdk/source'
8
+ import { ONE_SDK_SOURCE_DIRECTORY, readOneSDKSourceManifest } from './oneSdkContract'
9
+ import { syncSwiftTree } from './swift-compile'
10
+ import { resolveSwiftModule } from './swift-distribution'
11
+ import { artifactFor, icuUrl, projectFor } from './swift-host'
12
+ import { swiftCacheDir } from './swift-toolchain'
13
+ import type { OneSDKCompilation } from './oneSdkContract'
14
+
15
+ export const ONE_SDK_ROUTE = '/__peach/one-sdk'
16
+ export async function compileOneSDKApp(
17
+ appRoot: string,
18
+ origin: string,
19
+ moduleRootOverride?: string,
20
+ ) {
21
+ const selected = await selectOneSDK(appRoot)
22
+ if (!selected) return null
23
+ const { one, frameworks } = selected
24
+ const preparedRoot = await prepareNativeAppRoot(appRoot)
25
+ const sourceRoot = path.join(preparedRoot, ONE_SDK_SOURCE_DIRECTORY)
26
+ const generated = readOneSDKSourceManifest(
27
+ JSON.parse(fs.readFileSync(path.join(sourceRoot, 'manifest.json'), 'utf8')),
28
+ )
29
+ const { generation } = JSON.parse(
30
+ fs.readFileSync(path.join(one, 'ios-bindings/manifest.json'), 'utf8'),
31
+ )
32
+ if (
33
+ generated.generation !== generation ||
34
+ JSON.stringify(generated.frameworks) !== JSON.stringify(frameworks)
35
+ )
36
+ throw new Error(
37
+ 'prepared One SDK sources differ from the installed facades or app imports',
38
+ )
39
+ const moduleRoot = moduleRootOverride ?? (await resolveSwiftModule()).root
40
+ const packagePath = path.join(
41
+ swiftCacheDir(),
42
+ 'peach-one-sdk-swift',
43
+ createHash('sha256').update(fs.realpathSync(appRoot)).digest('hex').slice(0, 16),
44
+ 'sdk',
45
+ )
46
+ const files = new Map<string, string>()
47
+ files.set(
48
+ 'Package.swift',
49
+ `// swift-tools-version: 6.2
50
+ import PackageDescription
51
+ let package = Package(name: "OneSDKGuest", targets: [
52
+ .target(name: "One", path: "Sources/One"),
53
+ .target(name: "OneSDKBindings", dependencies: ["One"], path: "Sources/OneSDKBindings", swiftSettings: [.unsafeFlags(["-suppress-warnings"])]),
54
+ .executableTarget(name: "App", dependencies: ["One", "OneSDKBindings"], path: "Sources/App")
55
+ ])
56
+ `,
57
+ )
58
+ files.set('Sources/One/One.swift', oneSDKModule)
59
+ for (const source of [
60
+ 'SDK/OneSDKRuntime.swift',
61
+ 'OneNativeUIKitHostView.swift',
62
+ 'OneNativeContent.swift',
63
+ 'OneNativeAccessibility.swift',
64
+ 'SDKViews/OneNativeViewsTable.swift',
65
+ ])
66
+ files.set(
67
+ `Sources/One/${path.basename(source)}`,
68
+ fs.readFileSync(path.join(one, 'ios', source), 'utf8'),
69
+ )
70
+ for (const name of generated.files)
71
+ files.set(
72
+ `Sources/OneSDKBindings/${name}`,
73
+ fs.readFileSync(path.join(sourceRoot, name), 'utf8'),
74
+ )
75
+ files.set('Sources/App/App.swift', oneSDKApp)
76
+ files.set('Sources/App/Transport.swift', oneSDKTransport)
77
+ fs.mkdirSync(packagePath, { recursive: true })
78
+ syncSwiftTree(
79
+ packagePath,
80
+ new Map([...files].map(([name, source]) => [path.join(packagePath, name), source])),
81
+ )
82
+ const project = projectFor(packagePath)
83
+ project.oneModule = false
84
+ const artifact = await artifactFor(project, 'Sources/App/App.swift', moduleRoot)
85
+ const metadata: OneSDKCompilation = {
86
+ url: `${origin}/__peach/swift/${artifact.hash}.wasm`,
87
+ hash: artifact.hash,
88
+ icuUrl: icuUrl(origin, artifact),
89
+ rootId: `one-sdk-${artifact.hash.slice(0, 16)}`,
90
+ bundleFiles: artifact.package.bundleFiles.files,
91
+ modules: frameworks.map((name) => `${name}_${generated.generation}`),
92
+ }
93
+ return { metadata, artifact }
94
+ }
95
+
96
+ export async function buildOneSDKBundle(appRoot: string) {
97
+ const compiled = await compileOneSDKApp(appRoot, '')
98
+ return (
99
+ compiled && {
100
+ metadata: compiled.metadata,
101
+ assets: await compiledModuleAssets(compiled.artifact),
102
+ }
103
+ )
104
+ }
105
+
106
+ export const handleOneSDKRequest = compiledModuleRequestHandler(
107
+ 'One SDK',
108
+ (root, origin) => compileOneSDKApp(root, origin),
109
+ )
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { ONE_SDK_SOURCE_DIRECTORY, type OneSDKSourceManifest } from './oneSdkContract'
6
+
7
+ interface SDKGenerator {
8
+ importedFrameworks(root: string): string[]
9
+ generateAppSdk(frameworks: string[]): Promise<{
10
+ files: Map<string, string>
11
+ generation: string
12
+ }>
13
+ }
14
+
15
+ export async function selectOneSDK(appRoot: string) {
16
+ const require = createRequire(path.join(appRoot, 'package.json'))
17
+ let onePackage: string
18
+ try {
19
+ onePackage = require.resolve('one/package.json')
20
+ } catch (error) {
21
+ if (error instanceof Error && 'code' in error && error.code === 'MODULE_NOT_FOUND')
22
+ return null
23
+ throw error
24
+ }
25
+ const one = path.dirname(onePackage)
26
+ const generator: SDKGenerator = await import(
27
+ pathToFileURL(path.join(one, 'dist/sdk/app.mjs')).href
28
+ )
29
+ const frameworks = generator
30
+ .importedFrameworks(appRoot)
31
+ .filter((name) => name === 'UIKit')
32
+ return frameworks.length ? { one, generator, frameworks } : null
33
+ }
34
+
35
+ export async function prepareOneSDKSources(appRoot: string) {
36
+ const selected = await selectOneSDK(appRoot)
37
+ if (!selected) return
38
+ if (process.platform !== 'darwin')
39
+ throw new Error(
40
+ 'One SDK source preparation requires a Mac; supply its prepared native workspace',
41
+ )
42
+ const generated = await selected.generator.generateAppSdk(selected.frameworks)
43
+ const { generation } = JSON.parse(
44
+ fs.readFileSync(path.join(selected.one, 'ios-bindings/manifest.json'), 'utf8'),
45
+ )
46
+ if (generated.generation !== generation)
47
+ throw new Error('One SDK source generation differs from the installed facades')
48
+ const directory = path.join(appRoot, ONE_SDK_SOURCE_DIRECTORY)
49
+ fs.rmSync(directory, { recursive: true, force: true })
50
+ fs.mkdirSync(directory, { recursive: true })
51
+ for (const [name, from] of generated.files)
52
+ fs.copyFileSync(from, path.join(directory, name))
53
+ const manifest: OneSDKSourceManifest = {
54
+ generation,
55
+ frameworks: selected.frameworks,
56
+ files: [...generated.files.keys()],
57
+ }
58
+ fs.writeFileSync(path.join(directory, 'manifest.json'), JSON.stringify(manifest))
59
+ }
@@ -0,0 +1,77 @@
1
+ import {
2
+ insertBundleMetadataFooter,
3
+ readBundleMetadataFooter,
4
+ } from './bundleGlobalFooter'
5
+ import { isRecord } from './is-record'
6
+ import {
7
+ isBase64Bytes,
8
+ isSwiftResourcePath,
9
+ type SwiftEntryOptions,
10
+ } from './swiftContract'
11
+
12
+ export interface OneSDKCompilation extends SwiftEntryOptions {
13
+ rootId: string
14
+ icuUrl: string
15
+ modules: string[]
16
+ bundleFiles: Record<string, string>
17
+ }
18
+
19
+ export function readOneSDKMetadata(value: unknown): OneSDKCompilation | null {
20
+ if (value == null) return null
21
+ if (!isRecord(value)) throw new Error('invalid One SDK compilation metadata')
22
+ const { url, hash, rootId, icuUrl, modules, bundleFiles } = value
23
+ if (
24
+ typeof url !== 'string' ||
25
+ typeof hash !== 'string' ||
26
+ typeof rootId !== 'string' ||
27
+ typeof icuUrl !== 'string' ||
28
+ !Array.isArray(modules) ||
29
+ !modules.every((name) => typeof name === 'string') ||
30
+ !isRecord(bundleFiles)
31
+ )
32
+ throw new Error('invalid One SDK compilation metadata')
33
+ const files = Object.fromEntries(
34
+ Object.entries(bundleFiles).map(([name, bytes]) => {
35
+ if (
36
+ !isSwiftResourcePath(name) ||
37
+ typeof bytes !== 'string' ||
38
+ !isBase64Bytes(bytes)
39
+ )
40
+ throw new Error('invalid One SDK bundle file')
41
+ return [name, bytes] satisfies [string, string]
42
+ }),
43
+ )
44
+ return { url, hash, rootId, icuUrl, modules, bundleFiles: files }
45
+ }
46
+
47
+ export const readOneSDKFooter = (source: string) =>
48
+ readOneSDKMetadata(readBundleMetadataFooter(source, 'oneSDK'))
49
+ export const insertOneSDKFooter = (source: string, metadata: OneSDKCompilation) =>
50
+ insertBundleMetadataFooter(source, 'oneSDK', metadata)
51
+
52
+ export const ONE_SDK_SOURCE_DIRECTORY = 'ios/PeachOneSDK'
53
+
54
+ export interface OneSDKSourceManifest {
55
+ generation: string
56
+ frameworks: string[]
57
+ files: string[]
58
+ }
59
+
60
+ export function readOneSDKSourceManifest(value: unknown): OneSDKSourceManifest {
61
+ if (!isRecord(value)) throw new Error('invalid prepared One SDK sources')
62
+ const { generation, frameworks, files } = value
63
+ if (
64
+ typeof generation !== 'string' ||
65
+ !/^[a-f0-9]{16}$/.test(generation) ||
66
+ !Array.isArray(frameworks) ||
67
+ !frameworks.every((name) => typeof name === 'string') ||
68
+ !Array.isArray(files) ||
69
+ !files.every(
70
+ (name) =>
71
+ typeof name === 'string' &&
72
+ /^OneSDK_[A-Za-z_][A-Za-z0-9_]*(?:\.types)?\.swift$/.test(name),
73
+ )
74
+ )
75
+ throw new Error('invalid prepared One SDK sources')
76
+ return { generation, frameworks, files }
77
+ }