@weapp-container/react-native 0.0.0-stage → 0.1.0-preview.7.1-oidc.0
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.
- package/LICENSE +201 -0
- package/README.en.md +233 -0
- package/README.md +230 -2
- package/WeappContainerReactNative.podspec +23 -0
- package/android/build.gradle +37 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/sonofmagic/weapp/container/reactnative/WeappContainerModule.kt +256 -0
- package/android/src/main/java/com/sonofmagic/weapp/container/reactnative/WeappContainerPackage.kt +16 -0
- package/android/src/main/java/com/sonofmagic/weapp/container/reactnative/WeappContainerViewManager.kt +83 -0
- package/ios/WCRNComponentView.h +3 -0
- package/ios/WCRNComponentView.mm +47 -0
- package/ios/WCRNInstance.swift +350 -0
- package/ios/WCRNModule.h +3 -0
- package/ios/WCRNModule.mm +73 -0
- package/lib/index.d.ts +188 -0
- package/lib/index.js +362 -0
- package/lib/specs/NativeWeappContainer.d.ts +14 -0
- package/lib/specs/NativeWeappContainer.js +2 -0
- package/lib/specs/WeappContainerNativeComponent.d.ts +11 -0
- package/lib/specs/WeappContainerNativeComponent.js +2 -0
- package/package.json +52 -4
- package/react-native.config.js +1 -0
- package/sdk-artifact.json +74 -0
- package/src/index.tsx +295 -0
- package/src/specs/NativeWeappContainer.ts +10 -0
- package/src/specs/WeappContainerNativeComponent.ts +8 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
package com.sonofmagic.weapp.container.reactnative
|
|
2
|
+
|
|
3
|
+
import android.widget.FrameLayout
|
|
4
|
+
import com.facebook.react.bridge.Arguments
|
|
5
|
+
import com.facebook.react.uimanager.*
|
|
6
|
+
import com.facebook.react.uimanager.annotations.ReactProp
|
|
7
|
+
import com.facebook.react.uimanager.events.Event
|
|
8
|
+
import com.facebook.react.viewmanagers.WeappContainerNativeViewManagerDelegate
|
|
9
|
+
import com.facebook.react.viewmanagers.WeappContainerNativeViewManagerInterface
|
|
10
|
+
import com.sonofmagic.weapp.container.sdk.WeappContainerView
|
|
11
|
+
|
|
12
|
+
class ContainerSurface(val reactContext: ThemedReactContext) : FrameLayout(reactContext) {
|
|
13
|
+
private val nativeView = WeappContainerView(reactContext)
|
|
14
|
+
private var sessionId = ""
|
|
15
|
+
private var entry: ContainerRegistry.Entry? = null
|
|
16
|
+
private var waiting: java.util.concurrent.CompletableFuture<Unit>? = null
|
|
17
|
+
init { addView(nativeView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) }
|
|
18
|
+
fun setSession(value: String?) {
|
|
19
|
+
val next = value ?: ""
|
|
20
|
+
if (sessionId == next) return
|
|
21
|
+
sessionId = next
|
|
22
|
+
bind()
|
|
23
|
+
}
|
|
24
|
+
private fun report(error: Throwable) {
|
|
25
|
+
val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id)
|
|
26
|
+
dispatcher?.dispatchEvent(SurfaceErrorEvent(UIManagerHelper.getSurfaceId(reactContext), id, error.message ?: "Surface binding failed"))
|
|
27
|
+
}
|
|
28
|
+
private fun retire() {
|
|
29
|
+
val previous = entry ?: return
|
|
30
|
+
if (previous.surface?.get() !== this) { entry = null; return }
|
|
31
|
+
if (previous.retirement != null) return
|
|
32
|
+
val result = nativeView.unbindAsync()
|
|
33
|
+
previous.retirement = result
|
|
34
|
+
result.whenComplete { _, error -> reactContext.runOnUiQueueThread {
|
|
35
|
+
if (previous.retirement === result) {
|
|
36
|
+
if (error == null) { previous.surface = null; if (entry === previous) entry = null }
|
|
37
|
+
previous.retirement = null
|
|
38
|
+
}
|
|
39
|
+
if (error != null) report(error)
|
|
40
|
+
} }
|
|
41
|
+
}
|
|
42
|
+
private fun bind() {
|
|
43
|
+
try {
|
|
44
|
+
val target = if (isAttachedToWindow) sessionId else ""
|
|
45
|
+
val next = if (target.isEmpty()) null else ContainerRegistry.sessions[target]
|
|
46
|
+
if (entry != null && entry !== next) retire()
|
|
47
|
+
if (target.isEmpty()) { retire(); return }
|
|
48
|
+
require(next != null && next.owner.owns(reactContext.reactApplicationContext)) { "Unknown session for this React instance" }
|
|
49
|
+
val previousSurface = next.surface?.get()
|
|
50
|
+
if (next.retirement == null && previousSurface != null && previousSurface !== this && !previousSurface.isAttachedToWindow) previousSurface.retire()
|
|
51
|
+
val pending = entry?.retirement ?: next.retirement
|
|
52
|
+
if (pending != null) {
|
|
53
|
+
if (waiting === pending) return
|
|
54
|
+
waiting = pending
|
|
55
|
+
pending.whenComplete { _, error -> reactContext.runOnUiQueueThread {
|
|
56
|
+
if (waiting === pending) { waiting = null; if (error == null) bind() else report(error) }
|
|
57
|
+
} }
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
require(next.surface?.get() == null || next.surface?.get() === this) { "A session can be mounted in only one native view" }
|
|
61
|
+
nativeView.bind(next.session)
|
|
62
|
+
next.surface = java.lang.ref.WeakReference(this); entry = next
|
|
63
|
+
} catch (error: Throwable) { report(error) }
|
|
64
|
+
}
|
|
65
|
+
fun detach() { sessionId = ""; retire() }
|
|
66
|
+
override fun onAttachedToWindow() { super.onAttachedToWindow(); bind() }
|
|
67
|
+
override fun onDetachedFromWindow() { retire(); super.onDetachedFromWindow() }
|
|
68
|
+
}
|
|
69
|
+
private class SurfaceErrorEvent(surfaceId: Int, viewId: Int, private val message: String) : Event<SurfaceErrorEvent>(surfaceId, viewId) {
|
|
70
|
+
override fun getEventName() = "topSurfaceError"
|
|
71
|
+
override fun getEventData() = Arguments.createMap().apply { putString("code", "ERR_SURFACE"); putString("message", message) }
|
|
72
|
+
override fun canCoalesce() = false
|
|
73
|
+
}
|
|
74
|
+
class WeappContainerViewManager : SimpleViewManager<ContainerSurface>(), WeappContainerNativeViewManagerInterface<ContainerSurface> {
|
|
75
|
+
private val delegate = WeappContainerNativeViewManagerDelegate(this)
|
|
76
|
+
override fun getDelegate(): ViewManagerDelegate<ContainerSurface> = delegate
|
|
77
|
+
override fun getName() = "WeappContainerNativeView"
|
|
78
|
+
override fun createViewInstance(reactContext: ThemedReactContext) = ContainerSurface(reactContext)
|
|
79
|
+
@ReactProp(name = "sessionId")
|
|
80
|
+
override fun setSessionId(view: ContainerSurface, value: String?) { view.setSession(value) }
|
|
81
|
+
override fun onDropViewInstance(view: ContainerSurface) { view.detach(); super.onDropViewInstance(view) }
|
|
82
|
+
override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> = mutableMapOf("topSurfaceError" to mapOf("registrationName" to "onSurfaceError"))
|
|
83
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#import "WCRNComponentView.h"
|
|
2
|
+
#import <AVFoundation/AVFoundation.h>
|
|
3
|
+
#import <CoreBluetooth/CoreBluetooth.h>
|
|
4
|
+
#import <CoreLocation/CoreLocation.h>
|
|
5
|
+
#import <Contacts/Contacts.h>
|
|
6
|
+
#import <ContactsUI/ContactsUI.h>
|
|
7
|
+
#import <EventKit/EventKit.h>
|
|
8
|
+
#import <EventKitUI/EventKitUI.h>
|
|
9
|
+
#import <PhotosUI/PhotosUI.h>
|
|
10
|
+
#import <Vision/Vision.h>
|
|
11
|
+
#import <VisionKit/VisionKit.h>
|
|
12
|
+
#import "WeappContainerReactNative-Swift.h"
|
|
13
|
+
#import <react/renderer/components/WeappContainerSpec/ComponentDescriptors.h>
|
|
14
|
+
#import <react/renderer/components/WeappContainerSpec/EventEmitters.h>
|
|
15
|
+
#import <react/renderer/components/WeappContainerSpec/Props.h>
|
|
16
|
+
#import <react/renderer/components/WeappContainerSpec/RCTComponentViewHelpers.h>
|
|
17
|
+
using namespace facebook::react;
|
|
18
|
+
@implementation WCRNComponentView {
|
|
19
|
+
WCRNSurface *_surface;
|
|
20
|
+
}
|
|
21
|
+
+ (ComponentDescriptorProvider)componentDescriptorProvider { return concreteComponentDescriptorProvider<WeappContainerNativeViewComponentDescriptor>(); }
|
|
22
|
+
- (instancetype)initWithFrame:(CGRect)frame {
|
|
23
|
+
if (self = [super initWithFrame:frame]) {
|
|
24
|
+
_props = std::make_shared<const WeappContainerNativeViewProps>();
|
|
25
|
+
_surface = [[WCRNSurface alloc] initWithFrame:self.bounds];
|
|
26
|
+
self.contentView = _surface;
|
|
27
|
+
__weak WCRNComponentView *weakSelf = self;
|
|
28
|
+
_surface.onError = ^(NSString *code, NSString *message) {
|
|
29
|
+
WCRNComponentView *owner = weakSelf;
|
|
30
|
+
if (owner && owner->_eventEmitter) {
|
|
31
|
+
auto emitter = std::static_pointer_cast<const WeappContainerNativeViewEventEmitter>(owner->_eventEmitter);
|
|
32
|
+
emitter->onSurfaceError({std::string(code.UTF8String), std::string(message.UTF8String)});
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
return self;
|
|
37
|
+
}
|
|
38
|
+
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps {
|
|
39
|
+
const auto &next = *std::static_pointer_cast<const WeappContainerNativeViewProps>(props);
|
|
40
|
+
// Fabric keeps previous props when recycling, while prepareForRecycle clears
|
|
41
|
+
// our native owner. The same session must still bind on a recycled view.
|
|
42
|
+
[_surface setSessionId:[NSString stringWithUTF8String:next.sessionId.c_str()]];
|
|
43
|
+
[super updateProps:props oldProps:oldProps];
|
|
44
|
+
}
|
|
45
|
+
- (void)prepareForRecycle { [_surface setSessionId:@""]; [super prepareForRecycle]; }
|
|
46
|
+
@end
|
|
47
|
+
Class<RCTComponentViewProtocol> WeappContainerNativeViewCls(void) { return WCRNComponentView.class; }
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import WeappContainer
|
|
2
|
+
import Foundation
|
|
3
|
+
import UIKit
|
|
4
|
+
|
|
5
|
+
@MainActor
|
|
6
|
+
private enum WCRNRegistry {
|
|
7
|
+
@MainActor final class Entry {
|
|
8
|
+
let owner: UUID
|
|
9
|
+
let session: WeappContainerSession
|
|
10
|
+
let event: (String, WeappJSON) -> Void
|
|
11
|
+
let storageKey: String?
|
|
12
|
+
var closeTask: Task<Void, Error>?
|
|
13
|
+
weak var surface: WCRNSurface?
|
|
14
|
+
var view: WeappContainerView?
|
|
15
|
+
var retirement: Task<Void, Error>?
|
|
16
|
+
var accountCleanup: (operationId:String,continuation:CheckedContinuation<Void,Error>)?
|
|
17
|
+
var deviceServices:WeappNativeDeviceServices?
|
|
18
|
+
init(owner: UUID, session: WeappContainerSession, event: @escaping (String, WeappJSON) -> Void) {
|
|
19
|
+
self.owner = owner; self.session = session; self.event = event
|
|
20
|
+
if case .persistent(let key, _) = session.configuration.storage { storageKey = key } else { storageKey = nil }
|
|
21
|
+
}
|
|
22
|
+
func close(id: String, attempts: Int = 1) -> Task<Void, Error> {
|
|
23
|
+
if let closeTask { return closeTask }
|
|
24
|
+
if let pending=accountCleanup { event("accountCleanupCancelled",.object(["operationId":.string(pending.operationId)])) }
|
|
25
|
+
let task = Task { @MainActor [self] in
|
|
26
|
+
defer { closeTask = nil }
|
|
27
|
+
for attempt in 1...attempts {
|
|
28
|
+
do {
|
|
29
|
+
try await session.close()
|
|
30
|
+
try await deviceServices?.close()
|
|
31
|
+
WCRNRegistry.sessions.removeValue(forKey: id)
|
|
32
|
+
if let storageKey { WCRNRegistry.closingStorage[storageKey]?.removeValue(forKey: id) }
|
|
33
|
+
return
|
|
34
|
+
} catch {
|
|
35
|
+
if attempt == attempts { throw error }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
closeTask = task
|
|
40
|
+
if let storageKey { WCRNRegistry.closingStorage[storageKey, default: [:]][id] = task }
|
|
41
|
+
return task
|
|
42
|
+
}
|
|
43
|
+
// Publish the handoff before scheduling async GPU drain. A new Fabric
|
|
44
|
+
// instance can then await the exact predecessor, without retry timers.
|
|
45
|
+
func detach(from owner: WCRNSurface) -> Task<Void, Error>? {
|
|
46
|
+
guard surface === owner, let retiringView = view else { return nil }
|
|
47
|
+
if let retirement { return retirement }
|
|
48
|
+
let task = Task { @MainActor [self] in
|
|
49
|
+
defer { retirement = nil }
|
|
50
|
+
try await retiringView.detach()
|
|
51
|
+
retiringView.removeFromSuperview()
|
|
52
|
+
view = nil; surface = nil
|
|
53
|
+
}
|
|
54
|
+
retirement = task
|
|
55
|
+
return task
|
|
56
|
+
}
|
|
57
|
+
func attach(to owner: WCRNSurface, isCurrent: () -> Bool) async throws -> WeappContainerView? {
|
|
58
|
+
if retirement == nil, let previous = surface, previous !== owner, previous.window == nil { _ = detach(from: previous) }
|
|
59
|
+
if let retirement { try await retirement.value }
|
|
60
|
+
guard isCurrent() else { return nil }
|
|
61
|
+
guard surface == nil || surface === owner else { throw WeappContainerError(code: "ERR_VIEW_IN_USE", message: "A session can be mounted in only one native view") }
|
|
62
|
+
if let view { return view }
|
|
63
|
+
let created = try WeappContainerView(session: session)
|
|
64
|
+
let report = event
|
|
65
|
+
created.onPresented = { revision in report("presented", .object(["revision": .number(Double(revision)), "backend": .string("skia-gpu-metal")])) }
|
|
66
|
+
surface = owner; view = created
|
|
67
|
+
return created
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
static var sessions: [String: Entry] = [:]
|
|
71
|
+
// A replaced React runtime may create a new module before the old GPU and
|
|
72
|
+
// storage owners finish closing. Wait only for known closing writers.
|
|
73
|
+
static var closingStorage: [String: [String: Task<Void, Error>]] = [:]
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
@MainActor
|
|
77
|
+
@objc(WCRNInstance)
|
|
78
|
+
public final class WCRNInstance: NSObject {
|
|
79
|
+
@objc public weak var devicePresenter:UIViewController?
|
|
80
|
+
private let owner = UUID()
|
|
81
|
+
private var active = true
|
|
82
|
+
private var retainedCalls = Set<String>()
|
|
83
|
+
private var calls: [String: (session: String, continuation: CheckedContinuation<WeappJSON, Error>)] = [:]
|
|
84
|
+
@objc public var onEvent: ((String, String, String) -> Void)?
|
|
85
|
+
private func json(_ text: String) throws -> WeappJSON { try JSONDecoder().decode(WeappJSON.self, from: Data(text.utf8)) }
|
|
86
|
+
private func encode(_ value: WeappJSON) throws -> String { String(decoding: try JSONEncoder().encode(value), as: UTF8.self) }
|
|
87
|
+
private func bridge(_ failure: Error) -> NSError {
|
|
88
|
+
if let failure = failure as? WeappContainerError { return NSError(domain: "WeappContainer", code: 1, userInfo: [NSLocalizedDescriptionKey: failure.message, "weappCode": failure.code]) }
|
|
89
|
+
return failure as NSError
|
|
90
|
+
}
|
|
91
|
+
private func error(_ code: String, _ message: String) -> WeappContainerError { .init(code: code, message: message) }
|
|
92
|
+
private func emit(_ id: String, _ type: String, _ value: WeappJSON) {
|
|
93
|
+
guard active else { return }
|
|
94
|
+
do { onEvent?(id, type, try encode(value)) } catch { NSLog("WeappContainer event encoding failed: %@", String(describing: error)) }
|
|
95
|
+
}
|
|
96
|
+
private func lookup(_ id: String) throws -> WeappContainerSession {
|
|
97
|
+
guard active, let entry = WCRNRegistry.sessions[id], entry.owner == owner else { throw error("ERR_SESSION", "Session does not belong to this React instance") }
|
|
98
|
+
return entry.session
|
|
99
|
+
}
|
|
100
|
+
@objc public func create(_ configuration: String, completion: @escaping (String?, NSError?) -> Void) {
|
|
101
|
+
Task { @MainActor [self] in
|
|
102
|
+
do {
|
|
103
|
+
guard active else { throw error("ERR_INVALIDATED", "React instance was invalidated") }
|
|
104
|
+
let storage = try json(configuration)["storage"]
|
|
105
|
+
let config: WeappContainerConfiguration
|
|
106
|
+
if storage["memoryOnly"].bool == true { config = .init(storage: .memoryOnly) }
|
|
107
|
+
else if let key = storage["key"].string, !key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { config = .init(storageKey: key) }
|
|
108
|
+
else { throw error("ERR_CONFIGURATION", "Select memoryOnly or a stable storage key") }
|
|
109
|
+
if case .persistent(let key, _) = config.storage {
|
|
110
|
+
for pending in Array((WCRNRegistry.closingStorage[key] ?? [:]).values) { try await pending.value }
|
|
111
|
+
}
|
|
112
|
+
guard active else { return }
|
|
113
|
+
let id = UUID().uuidString
|
|
114
|
+
let session = WeappContainerSession(configuration: config)
|
|
115
|
+
session.onEvent = { [weak self] event in
|
|
116
|
+
switch event {
|
|
117
|
+
case .ready(let value): self?.emit(id, "ready", value)
|
|
118
|
+
case .navigation(let value): self?.emit(id, "navigation", value)
|
|
119
|
+
case .chrome(let value): self?.emit(id, "chrome", value)
|
|
120
|
+
case .message(let value): self?.emit(id, "message", value)
|
|
121
|
+
case .raw(let value): self?.emit(id, value["type"].string ?? "runtime", value)
|
|
122
|
+
case .error(let error): self?.emit(id, "error", .object(["code": .string(error.code), "message": .string(error.message)]))
|
|
123
|
+
case .closed(let error): self?.emit(id, "closed", .object(["ok": .bool(error == nil), "error": error.map { .object(["code": .string($0.code), "message": .string($0.message)]) } ?? .null]))
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
let entry=WCRNRegistry.Entry(owner: owner, session: session, event: { [weak self] type, value in self?.emit(id, type, value) })
|
|
127
|
+
WCRNRegistry.sessions[id]=entry
|
|
128
|
+
session.onAccountCleanup = { [weak self,weak entry] operationId in
|
|
129
|
+
guard let self,let entry else { throw CancellationError() }
|
|
130
|
+
guard entry.accountCleanup == nil else { throw self.error("ERR_ACCOUNT_CLEANUP","Previous cleanup transport has not ended") }
|
|
131
|
+
try await withTaskCancellationHandler(operation: {
|
|
132
|
+
try Task.checkCancellation()
|
|
133
|
+
try await withCheckedThrowingContinuation { (continuation:CheckedContinuation<Void,Error>) in
|
|
134
|
+
entry.accountCleanup=(operationId,continuation)
|
|
135
|
+
self.emit(id,"accountCleanupRequired",.object(["operationId":.string(operationId)]))
|
|
136
|
+
}
|
|
137
|
+
}, onCancel: {
|
|
138
|
+
Task { @MainActor [weak self,weak entry] in
|
|
139
|
+
guard let entry,entry.accountCleanup?.operationId==operationId else { return }
|
|
140
|
+
self?.emit(id,"accountCleanupCancelled",.object(["operationId":.string(operationId)]))
|
|
141
|
+
}
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
completion(id, nil)
|
|
145
|
+
} catch { if active { completion(nil, bridge(error)) } }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
@objc public func invoke(_ id: String, operation: String, payload: String, completion: @escaping (String?, NSError?) -> Void) {
|
|
149
|
+
Task { @MainActor [self] in
|
|
150
|
+
do {
|
|
151
|
+
let value = try json(payload)
|
|
152
|
+
// Invalidation can race the real terminal of a JS cleanup.
|
|
153
|
+
// Only this owner's outstanding receipt may retire afterward.
|
|
154
|
+
let session: WeappContainerSession
|
|
155
|
+
if operation == "completeAccountCleanup" {
|
|
156
|
+
guard let entry=WCRNRegistry.sessions[id],entry.owner==owner else { throw error("ERR_SESSION","Session does not belong to this React instance") }
|
|
157
|
+
session=entry.session
|
|
158
|
+
} else { session=try lookup(id) }
|
|
159
|
+
var result = WeappJSON.null
|
|
160
|
+
switch operation {
|
|
161
|
+
case "installNativeDeviceApis":
|
|
162
|
+
guard let entry=WCRNRegistry.sessions[id],entry.deviceServices==nil else { throw error("ERR_DEVICE_ADAPTER","Native devices already installed") }
|
|
163
|
+
guard let presenter=devicePresenter else { throw error("ERR_DEVICE_ADAPTER","A React presenter is required") }
|
|
164
|
+
func origins(_ key:String)->[String] { if case .array(let values)=value[key] { return values.compactMap(\.string) }; return [] }
|
|
165
|
+
let wifiConfiguration: WeappWifiConfiguration?
|
|
166
|
+
if value["wifiConfiguration"] == .null { wifiConfiguration = nil }
|
|
167
|
+
else {
|
|
168
|
+
guard case .object = value["wifiConfiguration"],
|
|
169
|
+
let connect = value["wifiConfiguration"]["connectToNetworks"].bool,
|
|
170
|
+
let read = value["wifiConfiguration"]["readCurrentNetwork"].bool else {
|
|
171
|
+
throw error("ERR_DEVICE_ADAPTER", "wifiConfiguration requires connectToNetworks and readCurrentNetwork booleans")
|
|
172
|
+
}
|
|
173
|
+
wifiConfiguration = .init(connectToNetworks: connect, readCurrentNetwork: read)
|
|
174
|
+
}
|
|
175
|
+
let nfcConfiguration: WeappNfcConfiguration?
|
|
176
|
+
if value["nfcConfiguration"] == .null { nfcConfiguration = nil }
|
|
177
|
+
else {
|
|
178
|
+
guard case .object(let flags) = value["nfcConfiguration"] else { throw error("ERR_DEVICE_ADAPTER", "nfcConfiguration must be an object") }
|
|
179
|
+
func flag(_ key: String, _ fallback: Bool = false) throws -> Bool {
|
|
180
|
+
guard let raw = flags[key] else { return fallback }
|
|
181
|
+
guard let boolean = raw.bool else { throw WeappContainerError(code: "ERR_DEVICE_ADAPTER", message: "nfcConfiguration.\(key) must be a boolean") }; return boolean
|
|
182
|
+
}
|
|
183
|
+
nfcConfiguration = try .init(ndef: flag("ndef", true), isoDep: flag("isoDep"), mifareUltralight: flag("mifareUltralight"), nfcF: flag("nfcF"), nfcV: flag("nfcV"))
|
|
184
|
+
}
|
|
185
|
+
let driver=try WeappNativeDeviceServices(presenter:presenter,
|
|
186
|
+
networkOrigins:origins("allowedNetworkOrigins"),
|
|
187
|
+
allowLoopbackForDevelopment:value["allowLoopbackForDevelopment"].bool == true,
|
|
188
|
+
enableBluetooth:value["bluetooth"].bool != false,
|
|
189
|
+
allowedMediaOrigins:origins("allowedMediaOrigins"),
|
|
190
|
+
recordingAudioSession:value["dedicatedAudioSession"].bool == true ? WeappExclusiveRecordingAudioSession() : nil,
|
|
191
|
+
enableNfc:value["nfc"].bool == true,
|
|
192
|
+
wifiConfiguration:wifiConfiguration, nfcConfiguration:nfcConfiguration)
|
|
193
|
+
entry.deviceServices=driver
|
|
194
|
+
try driver.install(in:session)
|
|
195
|
+
case "completeAccountCleanup":
|
|
196
|
+
guard let entry=WCRNRegistry.sessions[id],let pending=entry.accountCleanup,
|
|
197
|
+
pending.operationId==value["operationId"].string else { throw error("ERR_ACCOUNT_CLEANUP","Account cleanup belongs to another operation") }
|
|
198
|
+
entry.accountCleanup=nil
|
|
199
|
+
if !active || value["retired"].bool == true { pending.continuation.resume(throwing:CancellationError()) }
|
|
200
|
+
else if let message=value["error"]["message"].string { pending.continuation.resume(throwing:error("ERR_ACCOUNT_CLEANUP",message)) }
|
|
201
|
+
else { pending.continuation.resume() }
|
|
202
|
+
case "registerHostMethod":
|
|
203
|
+
guard let name = value["name"].string else { throw error("ERR_ARGUMENT", "Missing host method name") }
|
|
204
|
+
try session.registerHostMethod(name) { [weak self] payload in
|
|
205
|
+
guard let self else { throw CancellationError() }
|
|
206
|
+
return try await self.hostCall(id, method: name, payload: payload)
|
|
207
|
+
}
|
|
208
|
+
case "registerApiHandler":
|
|
209
|
+
guard let name = value["name"].string else { throw error("ERR_ARGUMENT", "Missing API name") }
|
|
210
|
+
try session.registerApiHandler(name) { [weak self] call in
|
|
211
|
+
guard let self else { throw CancellationError() }
|
|
212
|
+
return try await self.hostCall(id, method:name, payload:call.payload, context:call.context, deadlineNs:call.deadlineNs, cancelToken:call.cancelToken, cancellation:call.cancellation, retained:call.keepsResourceAlive)
|
|
213
|
+
}
|
|
214
|
+
case "hostComponents", "authorizeInstalledPack", "migrateLegacyStorage", "deleteAccountData", "retryAccountCleanup", "configureHostServices", "hostApiEvent", "hostComponentFrame", "hostComponentEvent", "authorizePhoneButton", "prepareAccountHostServiceSnapshots", "updateHostServiceSnapshots", "switchAccount", "queryAccountSwitch", "updateAccountSwitchLaunch", "acknowledgeAccountCleanup", "retryAccountSwitch", "cancelAccountSwitch", "hostApiResource", "createHostBinary", "readHostBinary", "retainHostBinary", "releaseHostBinary":
|
|
215
|
+
guard case .object(let fields) = value else { throw error("ERR_ARGUMENT", "Expected object") }
|
|
216
|
+
result = try session.hostServicesCommand(operation,fields)
|
|
217
|
+
case "load":
|
|
218
|
+
let url: URL
|
|
219
|
+
if let directory = value["directory"].string, directory.hasPrefix("/") { url = URL(fileURLWithPath: directory, isDirectory: true) }
|
|
220
|
+
else if let asset = value["asset"].string, !asset.isEmpty, !asset.hasPrefix("/"), !asset.split(separator: "/").contains(where: { $0 == ".." || $0 == "." }), let root = Bundle.main.resourceURL { url = root.appendingPathComponent(asset, isDirectory: true) }
|
|
221
|
+
else { throw error("ERR_ARGUMENT", "Expected absolute directory or relative bundle asset") }
|
|
222
|
+
guard case .object(let options) = value["options"] else { throw error("ERR_ARGUMENT", "options must be an object") }
|
|
223
|
+
try await session.load(packURL: url, route: value["route"].string, options: options)
|
|
224
|
+
case "sendMessage": try session.sendMessage(value["message"])
|
|
225
|
+
case "navigate":
|
|
226
|
+
guard let route = value["route"].string, case .object(let query) = value["query"] else { throw error("ERR_ARGUMENT", "Expected route and query") }
|
|
227
|
+
try session.navigate(route: route, query: query, replace: value["replace"].bool ?? false)
|
|
228
|
+
case "back": try session.back()
|
|
229
|
+
case "state": result = try session.state()
|
|
230
|
+
case "capabilities": result = try session.capabilities()
|
|
231
|
+
case "setForeground":
|
|
232
|
+
guard let visible = value["visible"].bool else { throw error("ERR_ARGUMENT", "visible must be a boolean") }
|
|
233
|
+
try session.setForeground(visible)
|
|
234
|
+
case "flushStorage": try await session.flushStorage()
|
|
235
|
+
case "close":
|
|
236
|
+
guard let entry = WCRNRegistry.sessions[id] else { throw error("ERR_SESSION", "Unknown session") }
|
|
237
|
+
try await entry.close(id: id).value
|
|
238
|
+
default: throw error("ERR_OPERATION", "Unsupported adapter operation: \(operation)")
|
|
239
|
+
}
|
|
240
|
+
if active || operation == "completeAccountCleanup" { completion(try encode(result), nil) }
|
|
241
|
+
} catch { if active { completion(nil, bridge(error)) } }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
private func hostCall(_ session: String, method: String, payload: WeappJSON, context: WeappJSON = .null, deadlineNs:String? = nil, cancelToken:String? = nil, cancellation:WeappHostApiCancellation? = nil, retained:Bool = false) async throws -> WeappJSON {
|
|
245
|
+
let id = UUID().uuidString
|
|
246
|
+
if retained {
|
|
247
|
+
retainedCalls.insert(id)
|
|
248
|
+
cancellation?.onCancel { [weak self] in
|
|
249
|
+
guard let self, self.retainedCalls.remove(id) != nil else { return }
|
|
250
|
+
if self.calls[id] != nil { self.cancelCall(id) }
|
|
251
|
+
else { self.emit(session,"hostCallCancelled",.object(["callId":.string(id)])) }
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return try await withTaskCancellationHandler {
|
|
255
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
256
|
+
guard active, !Task.isCancelled, cancellation?.isCancelled != true else { continuation.resume(throwing: CancellationError()); return }
|
|
257
|
+
calls[id] = (session, continuation)
|
|
258
|
+
emit(session, "hostCall", .object(["callId": .string(id), "method": .string(method), "payload": payload, "context":context, "deadlineNs":deadlineNs.map(WeappJSON.string) ?? .null, "cancelToken":cancelToken.map(WeappJSON.string) ?? .null, "retainUntilCancelled":.bool(retained)]))
|
|
259
|
+
}
|
|
260
|
+
} onCancel: { Task { @MainActor [weak self] in self?.cancelCall(id) } }
|
|
261
|
+
}
|
|
262
|
+
private func cancelCall(_ id: String) {
|
|
263
|
+
guard let call = calls.removeValue(forKey: id) else { return }
|
|
264
|
+
call.continuation.resume(throwing: CancellationError())
|
|
265
|
+
emit(call.session, "hostCallCancelled", .object(["callId": .string(id)]))
|
|
266
|
+
}
|
|
267
|
+
@objc public func completeHostCall(_ session: String, callId: String, response: String, completion: @escaping (String?, NSError?) -> Void) {
|
|
268
|
+
do {
|
|
269
|
+
_ = try lookup(session)
|
|
270
|
+
// Cancellation can win while JS is posting its completed result.
|
|
271
|
+
guard let call = calls[callId] else { completion(nil, nil); return }
|
|
272
|
+
guard call.session == session else { throw error("ERR_SESSION", "Host call belongs to another session") }
|
|
273
|
+
let value = try json(response)
|
|
274
|
+
if case .object(let failure) = value["error"] {
|
|
275
|
+
guard let codeText = failure["code"]?.string, let code = WeappHostError.Code(rawValue: codeText), let message = failure["message"]?.string else { throw error("ERR_ARGUMENT", "Invalid host error") }
|
|
276
|
+
let details: [String:WeappJSON]
|
|
277
|
+
if case .object(let fields) = failure["details"] ?? .object([:]) { details=fields } else { throw error("ERR_ARGUMENT","Invalid error details") }
|
|
278
|
+
calls.removeValue(forKey:callId); retainedCalls.remove(callId)
|
|
279
|
+
call.continuation.resume(throwing: WeappHostError(code: code, message: message, retryable: failure["retryable"]?.bool ?? false, details:details))
|
|
280
|
+
} else {
|
|
281
|
+
calls.removeValue(forKey: callId)
|
|
282
|
+
call.continuation.resume(returning: value["result"])
|
|
283
|
+
}
|
|
284
|
+
completion(nil, nil)
|
|
285
|
+
} catch { completion(nil, bridge(error)) }
|
|
286
|
+
}
|
|
287
|
+
@objc public func invalidate() {
|
|
288
|
+
guard active else { return }
|
|
289
|
+
active = false; onEvent = nil; retainedCalls.removeAll()
|
|
290
|
+
for id in Array(calls.keys) { cancelCall(id) }
|
|
291
|
+
let owned = WCRNRegistry.sessions.filter { $0.value.owner == owner }
|
|
292
|
+
// Register all closing writers synchronously before yielding to a new
|
|
293
|
+
// React instance, so its create can await persistence and GPU drain.
|
|
294
|
+
for (id, entry) in owned {
|
|
295
|
+
let closing = entry.close(id: id, attempts: 3)
|
|
296
|
+
Task { @MainActor in
|
|
297
|
+
do { try await closing.value }
|
|
298
|
+
catch { NSLog("WeappContainer invalidation retains failed owner %@: %@", id, String(describing: error)) }
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
@MainActor
|
|
305
|
+
@objc(WCRNSurface)
|
|
306
|
+
public final class WCRNSurface: UIView {
|
|
307
|
+
private var requested = ""
|
|
308
|
+
private var attached = ""
|
|
309
|
+
private var generation: UInt64 = 0
|
|
310
|
+
private var nativeView: WeappContainerView?
|
|
311
|
+
private var entry: WCRNRegistry.Entry?
|
|
312
|
+
private var transition: Task<Void, Never>?
|
|
313
|
+
private var target: String { window == nil ? "" : requested }
|
|
314
|
+
@objc public var onError: ((String, String) -> Void)?
|
|
315
|
+
@objc public func setSessionId(_ id: String) { guard requested != id else { return }; requested = id; generation &+= 1; reconcile() }
|
|
316
|
+
public override func didMoveToWindow() { super.didMoveToWindow(); generation &+= 1; reconcile() }
|
|
317
|
+
public override func layoutSubviews() { super.layoutSubviews(); nativeView?.frame = bounds }
|
|
318
|
+
private func reconcile() {
|
|
319
|
+
// Window detachment must publish retirement synchronously, before a
|
|
320
|
+
// replacement Fabric view receives its props on this same main turn.
|
|
321
|
+
if attached != target { _ = entry?.detach(from: self) }
|
|
322
|
+
guard transition == nil else { return }
|
|
323
|
+
transition = Task { @MainActor [self] in
|
|
324
|
+
defer { transition = nil }
|
|
325
|
+
while true {
|
|
326
|
+
do {
|
|
327
|
+
if let current = entry {
|
|
328
|
+
// Retirement may finish before this task gets its main
|
|
329
|
+
// turn, including when Fabric reuses this same UIView.
|
|
330
|
+
// A matching ID alone does not mean we still own a view.
|
|
331
|
+
if attached == target && current.retirement == nil && current.surface === self && current.view === nativeView { break }
|
|
332
|
+
if let retirement = current.detach(from: self) { try await retirement.value }
|
|
333
|
+
nativeView = nil; entry = nil; attached = ""
|
|
334
|
+
}
|
|
335
|
+
let next = target
|
|
336
|
+
if next.isEmpty { break }
|
|
337
|
+
guard let nextEntry = WCRNRegistry.sessions[next] else { throw WeappContainerError(code: "ERR_SESSION", message: "Unknown React Native session") }
|
|
338
|
+
let revision = generation
|
|
339
|
+
guard let view = try await nextEntry.attach(to: self, isCurrent: { self.generation == revision && self.target == next }) else { continue }
|
|
340
|
+
view.frame = bounds; view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
|
341
|
+
nativeView = view; entry = nextEntry; attached = next; addSubview(view)
|
|
342
|
+
} catch {
|
|
343
|
+
let failure = error as? WeappContainerError
|
|
344
|
+
onError?(failure?.code ?? "ERR_SURFACE", failure?.message ?? String(describing: error))
|
|
345
|
+
break
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
package/ios/WCRNModule.h
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#import "WCRNModule.h"
|
|
2
|
+
#import <AVFoundation/AVFoundation.h>
|
|
3
|
+
#import <CoreBluetooth/CoreBluetooth.h>
|
|
4
|
+
#import <CoreLocation/CoreLocation.h>
|
|
5
|
+
#import <Contacts/Contacts.h>
|
|
6
|
+
#import <ContactsUI/ContactsUI.h>
|
|
7
|
+
#import <EventKit/EventKit.h>
|
|
8
|
+
#import <EventKitUI/EventKitUI.h>
|
|
9
|
+
#import <PhotosUI/PhotosUI.h>
|
|
10
|
+
#import <Vision/Vision.h>
|
|
11
|
+
#import <VisionKit/VisionKit.h>
|
|
12
|
+
#import "WeappContainerReactNative-Swift.h"
|
|
13
|
+
#import <React/RCTInvalidating.h>
|
|
14
|
+
#import <React/RCTUtils.h>
|
|
15
|
+
#include <atomic>
|
|
16
|
+
|
|
17
|
+
@interface WCRNModule () <RCTInvalidating>
|
|
18
|
+
@end
|
|
19
|
+
@implementation WCRNModule {
|
|
20
|
+
WCRNInstance *_instance;
|
|
21
|
+
std::atomic_bool _invalidated;
|
|
22
|
+
}
|
|
23
|
+
RCT_EXPORT_MODULE(WeappContainer)
|
|
24
|
+
- (instancetype)init { if (self = [super init]) _invalidated.store(false); return self; }
|
|
25
|
+
+ (BOOL)requiresMainQueueSetup { return NO; }
|
|
26
|
+
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {
|
|
27
|
+
return std::make_shared<facebook::react::NativeWeappContainerSpecJSI>(params);
|
|
28
|
+
}
|
|
29
|
+
- (WCRNInstance *)instance {
|
|
30
|
+
NSAssert([NSThread isMainThread], @"Native sessions belong to the main actor");
|
|
31
|
+
if (!_instance && !_invalidated) {
|
|
32
|
+
_instance = [WCRNInstance new];
|
|
33
|
+
__weak WCRNModule *weakSelf = self;
|
|
34
|
+
_instance.onEvent = ^(NSString *sessionId, NSString *type, NSString *payload) {
|
|
35
|
+
WCRNModule *owner = weakSelf;
|
|
36
|
+
if (owner && !owner->_invalidated) [owner emitOnEvent:@{@"sessionId":sessionId, @"type":type, @"payload":payload}];
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return _instance;
|
|
40
|
+
}
|
|
41
|
+
- (void)create:(NSString *)configuration resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
42
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
43
|
+
if (self->_invalidated) return;
|
|
44
|
+
[[self instance] create:configuration completion:^(NSString *value, NSError *error) {
|
|
45
|
+
if (self->_invalidated) return;
|
|
46
|
+
if (error) reject(error.userInfo[@"weappCode"] ?: @"ERR_CREATE", error.localizedDescription, error); else resolve(value);
|
|
47
|
+
}];
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
- (void)invoke:(NSString *)sessionId operation:(NSString *)operation payload:(NSString *)payload resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
51
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
52
|
+
if (self->_invalidated) return;
|
|
53
|
+
[self instance].devicePresenter=RCTPresentedViewController();
|
|
54
|
+
[[self instance] invoke:sessionId operation:operation payload:payload completion:^(NSString *value, NSError *error) {
|
|
55
|
+
if (self->_invalidated) return;
|
|
56
|
+
if (error) reject(error.userInfo[@"weappCode"] ?: @"ERR_OPERATION", error.localizedDescription, error); else resolve(value);
|
|
57
|
+
}];
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
- (void)completeHostCall:(NSString *)sessionId callId:(NSString *)callId response:(NSString *)response resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
61
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
62
|
+
if (self->_invalidated) return;
|
|
63
|
+
[[self instance] completeHostCall:sessionId callId:callId response:response completion:^(NSString *value, NSError *error) {
|
|
64
|
+
if (self->_invalidated) return;
|
|
65
|
+
if (error) reject(error.userInfo[@"weappCode"] ?: @"ERR_HOST_CALL", error.localizedDescription, error); else resolve(nil);
|
|
66
|
+
}];
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
- (void)invalidate {
|
|
70
|
+
if (_invalidated.exchange(true)) return;
|
|
71
|
+
dispatch_async(dispatch_get_main_queue(), ^{ [self->_instance invalidate]; self->_instance = nil; });
|
|
72
|
+
}
|
|
73
|
+
@end
|