@weapp-container/react-native 0.0.0-stage → 0.1.0-preview.7.1

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/README.md CHANGED
@@ -1,3 +1,231 @@
1
- # Temporary Holding Version
1
+ # Weapp Container React Native SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **简体中文** · [English](README.en.md)
4
+
5
+ <a id="public-distribution-candidate-preview7"></a>
6
+ ## 公开发行候选:preview.7
7
+
8
+ 当前 SDK 源码是 `0.1.0-preview.7.1` 候选,核心运行库 `.7.1` 已发布;React Native `.7.1` npm 包、Android Maven 依赖、iOS Pod 和对应原生发行物尚未发布。使用安装命令前先核对[发布状态](https://github.com/weapp-container/weapp-container/blob/main/docs/public-sdk-release.md),不要混用不同版本的包装层与运行库。源码公开、包发布、编译通过和设备验收分别记录。
9
+
10
+ `.7.1` 安装入口在 npm、Maven Central 与 CocoaPods 对应版本公开并完成匿名消费验证后可用。历史私有归档及其锁文件保持原样。
11
+
12
+ 版本 `0.1.0-preview.7.1`;React Native 0.88 新架构,Android API 26+ / Java 17,iOS 16+。安装公开预览:
13
+
14
+ ```sh
15
+ npm install @weapp-container/react-native@0.1.0-preview.7.1
16
+ ```
17
+
18
+ Android 从 Maven Central 获取 `io.github.weapp-container:weapp-container-android:0.1.0-preview.7.1`。iOS Podfile 添加:
19
+
20
+ ```ruby
21
+ source 'https://github.com/weapp-container/Specs.git'
22
+ source 'https://cdn.cocoapods.org/'
23
+ ```
24
+
25
+ 随后在 iOS 工程运行 `pod install`。桥接包依赖同版本 `WeappContainer` Pod,不重复捆绑运行库。普通安装无需 Node 准备命令、Rust 或兄弟 SDK checkout。
26
+
27
+ <a id="reviewed-source-build-checkout"></a>
28
+ ### 已复核的源码构建版本
29
+
30
+ ```sh
31
+ git clone https://github.com/weapp-container/sdk-react-native.git sdk-react-native-source
32
+ cd sdk-react-native-source
33
+ git checkout 7565c32125b8e4a76ec4e17213f773ef6fc64e93
34
+ ```
35
+
36
+
37
+
38
+ [开发文档](https://container.weapp.dev/docs/) · [源码构建](https://github.com/weapp-container/weapp-container/blob/main/docs/sdk-source-build.md) · [API 与协议](https://github.com/weapp-container/sdk-contract/blob/main/README.md)
39
+
40
+ 在 React Native 应用中嵌入原生小程序容器,支持 Android 与 iOS,使用 Fabric 组件和 TurboModule。通过 TypeScript Controller 加载 pack、导航、收发消息和管理会话。
41
+
42
+ 包名:`@weapp-container/react-native`;已复核源码示例版本:`0.1.0-preview.7.1`;原生 ABI:`1`。本仓库提供 Apache-2.0 许可的接入层,运行库从公开核心源码构建,或使用另行核验的配套归档。
43
+
44
+ > 当前源码与默认公开锁均使用 preview.7.1。准备工具默认读取 `runtime-artifacts.0.1.0-preview.7.1.lock.json`;`runtime-artifacts.lock.json` 仅保留历史 preview.5.3 输入。自定义本地归档仍须通过 `--manifest` 指定同版本审核锁。npm 包是否发布以注册源与发行记录为准。
45
+
46
+ <a id="start-from-current-source"></a>
47
+ ## 从当前源码开始
48
+
49
+ 首次接入优先使用公开的核心仓库及其固定 SDK 提交,不需要历史归档的下载 token:
50
+
51
+ ```sh
52
+ git clone --recurse-submodules https://github.com/weapp-container/weapp-container.git
53
+ cd weapp-container
54
+ corepack enable
55
+ pnpm install --frozen-lockfile
56
+ node sdk/contract/fixtures/make-acceptance-pack.mjs --out artifacts/hello-pack
57
+ ```
58
+
59
+ 随后按[源码构建说明](https://github.com/weapp-container/weapp-container/blob/main/docs/sdk-source-build.md)准备目标平台的运行库和 notices,再用本仓库的构建工具生成接入包。平台工具链仍是必要依赖;源码公开不表示公共包仓库已有可下载的二进制。已有原生小程序或框架构建产物可以由独立 portable pack 工具打包,不要求 weapp-vite。
60
+
61
+ 下面保留独立 SDK 的安装、视图与生命周期说明。涉及 `prepare-runtime` / `prepare-native` 的命令属于显式归档路径,必须使用核验过的配套 manifest;历史默认锁可能无法下载,详见文末说明。
62
+
63
+ <a id="requirements"></a>
64
+ ## 环境要求
65
+
66
+ | 项目 | 版本 |
67
+ | --- | --- |
68
+ | Node.js / Python | Node.js 24+、Python 3 |
69
+ | React Native / React | React Native 0.88.0(新架构)、React 19.3.0 |
70
+ | TypeScript | 5.9.3 |
71
+ | Android | API 26+;arm64-v8a、x86_64;Android SDK、JDK、Gradle 工具链 |
72
+ | iOS | iOS 16+;arm64 真机、arm64/x86_64 模拟器;macOS、Xcode、CocoaPods |
73
+
74
+ <a id="1-install-the-sdk"></a>
75
+ ## 1. 安装 SDK
76
+
77
+ 如果已获得带原生依赖的 SDK 分发包,在你的 React Native 应用中安装本地归档:
78
+
79
+ ```sh
80
+ npm install /absolute/packages/weapp-container-react-native-0.1.0-preview.7.1.tgz
81
+ cd ios
82
+ pod install
83
+ ```
84
+
85
+ 该归档包含原生 SDK 和对应 notices,使用它不需要核心源码或 Rust 工具链。Android 应用只启用 `arm64-v8a,x86_64`,iOS deployment target 设为 `16.0` 或更高。
86
+
87
+ 如果需要从本仓库生成分发包,请按文末的“从源码生成分发包”操作。
88
+
89
+ <a id="2-create-a-session-and-register-host-methods"></a>
90
+ ## 2. 创建会话与注册宿主方法
91
+
92
+ 由页面或路由管理 Controller,保留同一个实例,不要在 React render 中重复创建。首次加载 pack 前注册方法和事件:
93
+
94
+ ```tsx
95
+ import {
96
+ WeappContainerController,
97
+ WeappContainerView,
98
+ } from '@weapp-container/react-native';
99
+
100
+ const controller = await WeappContainerController.create({
101
+ storage: {key: 'account-42:catalog'},
102
+ });
103
+ await controller.registerHostMethod('host.echo', async (payload, {signal}) => {
104
+ if (signal.aborted) throw new Error('Host call cancelled');
105
+ return {value: payload};
106
+ });
107
+ const unsubscribe = controller.subscribe(event => {
108
+ if (event.type === 'message') console.log(event.payload);
109
+ if (event.type === 'error') console.error(event.payload);
110
+ });
111
+ ```
112
+
113
+ 使用稳定的应用/账号标识作为存储 key。只需要内存状态时,改为 `storage: {memoryOnly: true}`。
114
+
115
+ <a id="3-mount-the-view-and-load-a-pack"></a>
116
+ ## 3. 挂载 View 并加载 pack
117
+
118
+ 在组件中渲染具有正数宽高的区域,传入上面创建的 Controller:
119
+
120
+ ```tsx
121
+ <WeappContainerView
122
+ controller={controller}
123
+ style={{height: 480, width: '100%'}}
124
+ onSurfaceError={error => console.error(error.code, error.message)}
125
+ />
126
+ ```
127
+
128
+ 加载随应用打包的 pack:
129
+
130
+ ```tsx
131
+ await controller.load({asset: 'catalog-pack'});
132
+ ```
133
+
134
+ `asset` 相对于 Android 的 `assets/` 或 iOS 主资源 bundle。Android 可放在 `android/app/src/main/assets/catalog-pack/`;iOS 将整个 `catalog-pack` 目录作为资源文件夹加入应用 target,保留目录结构。
135
+
136
+ 也可以加载已生成、已校验并解包到应用私有目录的 pack:
137
+
138
+ ```tsx
139
+ await controller.load({directory: '/verified/local/catalog-pack'});
140
+ await controller.navigate('pages/detail/index', {id: '42'});
141
+ await controller.sendMessage({type: 'refresh'});
142
+ await controller.back();
143
+ ```
144
+
145
+ pack 需要符合运行库格式,不能直接传入普通小程序源码目录。完整的 React 页面挂载与资源打包示例见 [example/App.tsx](example/App.tsx) 和[独立示例生成器](tools/create-consumer.mjs)。
146
+
147
+ <a id="session-lifecycle"></a>
148
+ ## 会话生命周期
149
+
150
+ Controller 与 View 分离,卸载 View 可以保留会话。页面隐藏时显式切换前后台,结束功能时等待关闭完成:
151
+
152
+ ```tsx
153
+ await controller.setForeground(false);
154
+ // When the page becomes visible again
155
+ await controller.setForeground(true);
156
+
157
+ // When the session will no longer be reused
158
+ unsubscribe();
159
+ await controller.flushStorage();
160
+ await controller.close();
161
+ ```
162
+
163
+ 在 React effect 中创建会话时,处理“组件已卸载但 create 尚未完成”的情况:新建成功后检查组件状态,已卸载则立即关闭。Effect cleanup 不能返回 Promise,应将异步关闭交给会话管理逻辑,并在下次创建前等待它完成。关闭失败时保留 Controller 供重试。完整实现可参考 [example/App.tsx](example/App.tsx)。
164
+
165
+ 宿主方法只接收和返回 JSON 可表示的值。异步操作应观察 `AbortSignal`,在取消后终止对应工作;可抛出导出的 `HostError`,返回 `permission_denied`、`unsupported` 等明确错误代码。
166
+
167
+ 需要登录、账号、网络或设备 API 时,在 `load()` 前调用 `configureHostServices`,再按需调用 `installNativeDeviceApis`。宿主负责网络 origin 白名单和系统权限,受限 Showcase 的编译时策略继续生效。配置、账号切换和完整类型见 [src/index.tsx](src/index.tsx) 与 [CONTRACT.md](CONTRACT.md)。
168
+
169
+ 标准微信支付可使用 `controller.installWxRequestPayment(handler)` 注册。SDK 会校验 `timeStamp`、`nonceStr`、`package`、`signType` 和 `paySign`,handler 应调用宿主配置的官方支付 SDK,并在终结回调与服务端验单完成后返回;成功结果固定为 `requestPayment:ok`,取消或渠道错误应抛出 `HostError`。SDK 不接受 guest 自带商户密钥,也不会把 UI 已完成当作订单已支付。
170
+
171
+ <a id="build-a-distribution-from-source"></a>
172
+ ## 从源码生成分发包
173
+
174
+ ```sh
175
+ git clone https://github.com/weapp-container/sdk-react-native.git
176
+ cd sdk-react-native
177
+ git checkout 7565c32125b8e4a76ec4e17213f773ef6fc64e93
178
+ npm install --ignore-scripts
179
+ npm run typecheck
180
+ node tools/prepare-native.mjs --platform android --arch universal \
181
+ --manifest /absolute/reviewed-preview6-lock.json --artifact-dir /absolute/archives
182
+ node tools/prepare-native.mjs --platform ios --arch universal \
183
+ --manifest /absolute/reviewed-preview6-lock.json --artifact-dir /absolute/archives
184
+ node tools/package.mjs --out /absolute/new-sdk-packages \
185
+ --manifest /absolute/reviewed-preview6-lock.json --artifact-dir /absolute/archives
186
+ ```
187
+
188
+ 以上示例使用已获授权的离线归档。在线下载时省略 `--artifact-dir`,通过环境变量 `WEAPP_CONTAINER_RUNTIME_TOKEN` 提供私有运行库仓库的只读授权。不要提交凭据或归档。
189
+
190
+ 准备工具校验精确版本、ABI、架构、大小和 SHA-256,将原生依赖放入忽略提交的 `native/` 目录。打包要求独立、已提交且通过源码清单校验的仓库,同时验证 Android/iOS 原生依赖,执行 TypeScript 构建、RN codegen 和 `npm pack`,输出 `.tgz` 与 `build.json`。需要额外校验 lock 文件本身时,追加 `--manifest-sha256` 和独立确认的 SHA-256。
191
+
192
+ 从生成的归档创建包含测试 pack 的独立应用:
193
+
194
+ ```sh
195
+ node tools/create-consumer.mjs \
196
+ --package /absolute/new-sdk-packages/weapp-container-react-native-0.1.0-preview.7.1.tgz \
197
+ --out /absolute/new-rn-consumer
198
+ ```
199
+
200
+ 该命令使用固定的 React Native 模板,安装 SDK 并准备原生工程;实际构建和设备运行另行执行。见 [example/README.md](example/README.md)。
201
+
202
+ <a id="troubleshooting"></a>
203
+ ## 常见问题
204
+
205
+ | 现象 | 检查项 |
206
+ | --- | --- |
207
+ | 默认准备命令拒绝版本 | 确认使用当前 preview.7.1 公开锁;自定义 manifest 必须与包装层和归档一致 |
208
+ | 找不到 AAR / XCFramework | 先准备同版本原生 SDK;单独安装源码不会附带运行库 |
209
+ | Android 链接或安装失败 | API 26+,仅启用 arm64-v8a、x86_64 |
210
+ | 原生组件不可用 | 使用新架构,完成原生依赖准备、CocoaPods 安装和应用重新构建 |
211
+ | 关闭后仍有异步回调 | 取消宿主任务并等待原生清理完成,不复用已关闭的 Controller |
212
+
213
+ <a id="documentation-and-licensing"></a>
214
+ ## 更多资料与许可
215
+
216
+ - [公开 API](src/index.tsx) · [协议与能力协商](CONTRACT.md)
217
+ - [完整示例](example/App.tsx) · [示例运行说明](example/README.md)
218
+ - [公共类型和 C ABI](https://github.com/weapp-container/sdk-contract/blob/main/README.md)
219
+
220
+ 接入层源码使用 [Apache-2.0](LICENSE)。运行库与第三方组件遵循分发归档中的 `RUNTIME-LICENSE` 和 notices;源码开源不授予私有运行库下载权或额外的商用权利。
221
+
222
+ <a id="historical-archives-and-migration"></a>
223
+ ## 历史归档与迁移
224
+
225
+ 运行库发行工具已迁入 [核心仓库](https://github.com/weapp-container/weapp-container/tree/main/tools/runtime-artifacts)。新清单使用核心仓库的精确版本 Release;用 `--manifest` 显式选取。更新后的下载器把旧锁中的 `runtime-artifacts` 标识定向到私有的 `weapp-container/runtime-artifacts-private-archive`,仅允许九个冻结版本,保留原版本、哈希及随附许可,回执记录实际存储库。旧版下载器需升级;同名新仓库只保留停更工具源码。无跨仓库回退,私有档案仍需读取权限,源码许可不代表历史发行物公开可用。
226
+
227
+ 核心运行时与 SDK 自有源码采用 Apache-2.0,可按[主仓库源码构建说明](https://github.com/weapp-container/weapp-container/blob/main/docs/sdk-source-build.md)构建当前运行库。现有预编译归档保留原许可、访问要求及精确版本和哈希锁;本次源码更新不发布替代二进制。
228
+
229
+ ## 发布构建
230
+
231
+ 维护者通过 `tools/package-public.mjs` 使用已验证的 Android/iOS 发行清单构建公开候选。历史离线工具用于复核旧分发,详见[公开发行流程](PUBLIC-RELEASE.md)。
@@ -0,0 +1,23 @@
1
+ require "json"
2
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
3
+ Pod::Spec.new do |s|
4
+ s.name = "WeappContainerReactNative"
5
+ s.version = package["version"]
6
+ s.summary = package["description"]
7
+ s.homepage = "https://github.com/weapp-container/sdk-react-native"
8
+ s.license = { :type => "Apache-2.0", :file => "LICENSE" }
9
+ s.authors = { "weapp-container" => "https://github.com/weapp-container/sdk-react-native" }
10
+ s.source = { :git => "https://github.com/weapp-container/sdk-react-native.git", :tag => "v#{s.version}" }
11
+ s.platform = :ios, "16.0"
12
+ s.swift_version = "5.9"
13
+ s.source_files = "ios/**/*.{h,m,mm,swift}"
14
+ s.dependency "WeappContainer", package["version"]
15
+ s.private_header_files = "ios/WCRNModule.h", "ios/WCRNComponentView.h"
16
+ # The generated Swift Objective-C interface references delegate protocols
17
+ # from every installed native device adapter. Keep these imports explicit so
18
+ # WCRNModule.mm can consume the generated header in a clean CocoaPods target.
19
+ s.frameworks = "Metal", "MetalKit", "QuartzCore", "UIKit", "CoreGraphics", "CoreText", "CoreFoundation", "SystemConfiguration", "Security", "AVFoundation", "CoreBluetooth", "CoreLocation", "CoreMotion", "Network", "AudioToolbox", "Contacts", "ContactsUI", "EventKit", "EventKitUI", "VisionKit", "Vision", "PhotosUI", "CoreNFC", "LocalAuthentication"
20
+ s.libraries = "c++", "z", "iconv"
21
+ s.pod_target_xcconfig = { "DEFINES_MODULE" => "YES", "SWIFT_OBJC_INTERFACE_HEADER_NAME" => "WeappContainerReactNative-Swift.h", "CLANG_CXX_LANGUAGE_STANDARD" => "c++20" }
22
+ install_modules_dependencies(s)
23
+ end
@@ -0,0 +1,37 @@
1
+ buildscript {
2
+ repositories { google(); mavenCentral() }
3
+ dependencies { classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${rootProject.ext.has('kotlinVersion') ? rootProject.ext.kotlinVersion : '2.2.0'}") }
4
+ }
5
+ apply plugin: "com.android.library"
6
+ apply plugin: "org.jetbrains.kotlin.android"
7
+ apply plugin: "com.facebook.react"
8
+ def supportedArchitectures = ["arm64-v8a", "x86_64"]
9
+ def requestedArchitectures = (findProperty("reactNativeArchitectures") ?: "arm64-v8a,x86_64").split(",").collect { it.trim() }
10
+ if (requestedArchitectures.any { !supportedArchitectures.contains(it) }) {
11
+ throw new GradleException("WeappContainer supports arm64-v8a,x86_64; set reactNativeArchitectures=arm64-v8a,x86_64 in gradle.properties")
12
+ }
13
+ react {
14
+ jsRootDir = file("../src")
15
+ libraryName = "WeappContainerSpec"
16
+ codegenJavaPackageName = "com.sonofmagic.weapp.container.reactnative"
17
+ }
18
+ android {
19
+ namespace "com.sonofmagic.weapp.container.reactnative"
20
+ compileSdk rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 37
21
+ defaultConfig { minSdk 26; ndk { abiFilters "arm64-v8a", "x86_64" } }
22
+ compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
23
+ kotlinOptions { jvmTarget = '17' }
24
+ }
25
+ // Maven Central is the default installation source. A local repository is an explicit build-test override.
26
+ def sdkMavenOverride = project.findProperty('weappSdkMavenDir')
27
+ rootProject.allprojects {
28
+ repositories {
29
+ if (sdkMavenOverride) { maven { url = uri(sdkMavenOverride); content { includeGroup 'io.github.weapp-container' } } }
30
+ google()
31
+ mavenCentral()
32
+ }
33
+ }
34
+ dependencies {
35
+ implementation "com.facebook.react:react-android"
36
+ implementation 'io.github.weapp-container:weapp-container-android:0.1.0-preview.7.1'
37
+ }
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,256 @@
1
+ package com.sonofmagic.weapp.container.reactnative
2
+
3
+ import com.facebook.react.bridge.*
4
+ import com.facebook.react.module.annotations.ReactModule
5
+ import com.facebook.react.modules.core.PermissionAwareActivity
6
+ import com.facebook.react.modules.core.PermissionListener
7
+ import com.sonofmagic.weapp.container.sdk.*
8
+ import org.json.JSONObject
9
+ import org.json.JSONArray
10
+ import java.io.File
11
+ import java.util.UUID
12
+ import java.util.concurrent.CompletableFuture
13
+
14
+ internal object ContainerRegistry {
15
+ class Entry(val owner: WeappContainerModule, val session: WeappContainerSession, var requestedForeground: Boolean = true) {
16
+ var surface: java.lang.ref.WeakReference<ContainerSurface>? = null
17
+ var retirement: CompletableFuture<Unit>? = null
18
+ var accountCleanup: Pair<String,CompletableFuture<Unit>>? = null
19
+ var deviceServices:AndroidNativeDeviceServices?=null
20
+ private var closing: CompletableFuture<Unit>? = null
21
+ fun close(id: String, attempts: Int = 1): CompletableFuture<Unit> {
22
+ closing?.let { return it }
23
+ accountCleanup?.let { owner.emitCleanupCancellation(id, it.first) }
24
+ val result = CompletableFuture<Unit>()
25
+ closing = result
26
+ session.storageKey?.let { closingStorage.getOrPut(it) { mutableMapOf() }[id] = result }
27
+ fun attempt(remaining: Int) {
28
+ session.closeAsync().whenComplete { _, error ->
29
+ if (error != null && remaining > 1) { attempt(remaining - 1); return@whenComplete }
30
+ closing = null
31
+ try {
32
+ if(error!=null) throw error
33
+ deviceServices?.close()
34
+ sessions.remove(id)
35
+ session.storageKey?.let { closingStorage[it]?.remove(id) }
36
+ result.complete(Unit)
37
+ } catch(failure:Throwable) { result.completeExceptionally(failure) }
38
+ }
39
+ }
40
+ attempt(attempts)
41
+ return result
42
+ }
43
+ }
44
+ val sessions = mutableMapOf<String, Entry>() // Android main thread only.
45
+ val closingStorage = mutableMapOf<String, MutableMap<String, CompletableFuture<Unit>>>()
46
+ }
47
+
48
+ @ReactModule(name = WeappContainerModule.NAME)
49
+ class WeappContainerModule(context: ReactApplicationContext) : NativeWeappContainerSpec(context), LifecycleEventListener {
50
+ companion object { const val NAME = "WeappContainer" }
51
+ @Volatile private var active = true
52
+ private var hostForeground = context.lifecycleState == com.facebook.react.common.LifecycleState.RESUMED
53
+ private val invalidated = java.util.concurrent.atomic.AtomicBoolean(false)
54
+ private data class Pending(val sessionId: String, val reply: HostReply, val retained:Boolean=false)
55
+ private val calls = mutableMapOf<String, Pending>()
56
+ private var nextPermission=39000
57
+ private val permissionBroker=AndroidPermissionBroker { permissions,call,completion ->
58
+ val activity=reactApplicationContext.currentActivity as? PermissionAwareActivity
59
+ if(activity==null || call.isCancelled) completion(false)
60
+ else {
61
+ val id=nextPermission++; if(nextPermission>=65000) nextPermission=39000
62
+ activity.requestPermissions(permissions,id,PermissionListener { requestCode,_,_ ->
63
+ if(requestCode!=id) false else {
64
+ completion(!call.isCancelled && permissions.all { reactApplicationContext.currentActivity?.checkSelfPermission(it)==android.content.pm.PackageManager.PERMISSION_GRANTED }); true
65
+ }
66
+ })
67
+ }
68
+ }
69
+ init { context.addLifecycleEventListener(this) }
70
+ override fun getName() = NAME
71
+ internal fun owns(context: ReactContext) = active && context === reactApplicationContext
72
+ private fun emit(id: String, type: String, payload: Any?) {
73
+ if (!active || !reactApplicationContext.hasActiveReactInstance()) return
74
+ emitOnEvent(Arguments.createMap().apply { putString("sessionId", id); putString("type", type); putString("payload", JSONArray().put(payload ?: JSONObject.NULL).toString().drop(1).dropLast(1)) })
75
+ }
76
+ private fun lookup(id: String): WeappContainerSession {
77
+ check(active) { "React instance was invalidated" }
78
+ val entry = ContainerRegistry.sessions[id]
79
+ require(entry?.owner === this) { "Session does not belong to this React instance" }
80
+ return checkNotNull(entry).session
81
+ }
82
+ private fun reject(promise: Promise, error: Throwable) {
83
+ if (active) promise.reject((error as? ContainerException)?.code ?: "ERR_REACT_NATIVE", error.message, error)
84
+ }
85
+ private fun <T> complete(future: CompletableFuture<T>, promise: Promise, map: (T) -> Any? = { "null" }) {
86
+ future.whenComplete { value, error ->
87
+ if (active) { if (error != null) reject(promise, error) else promise.resolve(map(value)) }
88
+ }
89
+ }
90
+ override fun create(configuration: String, promise: Promise) = reactApplicationContext.runOnUiQueueThread {
91
+ try {
92
+ check(active)
93
+ val storage = JSONObject(configuration).getJSONObject("storage")
94
+ val key = if (storage.optBoolean("memoryOnly")) null else storage.getString("key").also { require(it.isNotBlank()) }
95
+ val pending = key?.let { ContainerRegistry.closingStorage[it]?.values?.toTypedArray() } ?: emptyArray()
96
+ CompletableFuture.allOf(*pending).whenComplete { _, error -> reactApplicationContext.runOnUiQueueThread {
97
+ if (!active) return@runOnUiQueueThread
98
+ if (error != null) { reject(promise, error); return@runOnUiQueueThread }
99
+ try {
100
+ val id = UUID.randomUUID().toString()
101
+ val session = WeappContainerSession(reactApplicationContext, key)
102
+ session.eventListener = ContainerEventListener { event ->
103
+ val type = event.getString("type")
104
+ val value = when (type) {
105
+ "message" -> event.opt("message")
106
+ "ready" -> event.opt("state")
107
+ "error" -> event.opt("error")
108
+ "closed" -> JSONObject().put("ok", event.optBoolean("ok", true)).put("error", event.opt("error") ?: JSONObject.NULL)
109
+ else -> event
110
+ }
111
+ emit(id, type, value)
112
+ }
113
+ val entry=ContainerRegistry.Entry(this,session)
114
+ ContainerRegistry.sessions[id] = entry
115
+ session.accountCleanupHandler = { operationId ->
116
+ val pending=CompletableFuture<Unit>()
117
+ check(entry.accountCleanup==null) { "Previous account cleanup transport has not ended" }
118
+ entry.accountCleanup=operationId to pending
119
+ emit(id,"accountCleanupRequired",JSONObject().put("operationId",operationId))
120
+ pending
121
+ }
122
+ session.setForeground(hostForeground)
123
+ if (active) promise.resolve(id)
124
+ } catch (failure: Throwable) { reject(promise, failure) }
125
+ } }
126
+
127
+ } catch (error: Throwable) { reject(promise, error) }
128
+ }
129
+ override fun invoke(sessionId: String, operation: String, payload: String, promise: Promise) = reactApplicationContext.runOnUiQueueThread {
130
+ try {
131
+ val value = JSONObject(payload)
132
+ // A real terminal may race React invalidation. Only the exact
133
+ // outstanding cleanup receipt can retire this module's old owner.
134
+ val session = if (operation == "completeAccountCleanup") {
135
+ val entry = ContainerRegistry.sessions[sessionId]
136
+ require(entry?.owner === this) { "Session does not belong to this React instance" }
137
+ checkNotNull(entry).session
138
+ } else lookup(sessionId)
139
+ when (operation) {
140
+ "installNativeDeviceApis" -> {
141
+ val entry=checkNotNull(ContainerRegistry.sessions[sessionId])
142
+ check(entry.deviceServices==null) { "Native devices already installed" }
143
+ val activity=checkNotNull(reactApplicationContext.currentActivity) { "A foreground React Activity is required" }
144
+ val rawOrigins=value.optJSONArray("allowedNetworkOrigins") ?: JSONArray()
145
+ val origins=(0 until rawOrigins.length()).map { rawOrigins.getString(it) }.toSet()
146
+ val driver=AndroidNativeDeviceServices(activity,networkOrigins=origins,
147
+ allowLoopbackForDevelopment=value.optBoolean("allowLoopbackForDevelopment",false),
148
+ enableBluetooth=value.optBoolean("bluetooth",true),permissions=permissionBroker,
149
+ enableNfc=value.optBoolean("nfc",false),
150
+ enableWifi=value.optBoolean("enableWifi",false))
151
+ entry.deviceServices=driver
152
+ complete(driver.install(session),promise)
153
+ }
154
+ "completeAccountCleanup" -> {
155
+ val entry=checkNotNull(ContainerRegistry.sessions[sessionId])
156
+ val pending=entry.accountCleanup
157
+ require(pending?.first==value.getString("operationId")) { "Account cleanup belongs to another operation" }
158
+ entry.accountCleanup=null
159
+ val error=value.optJSONObject("error")
160
+ if(!active || value.optBoolean("retired")) pending!!.second.completeExceptionally(ContainerException("ERR_CANCELLED","Retired account cleanup ended"))
161
+ else if(error!=null) pending!!.second.completeExceptionally(ContainerException("ERR_ACCOUNT_CLEANUP",error.optString("message","Account cleanup failed")))
162
+ else pending!!.second.complete(Unit)
163
+ promise.resolve("null")
164
+ }
165
+ "registerHostMethod", "registerApiHandler" -> {
166
+ val name = value.getString("name")
167
+ val handler = HostMethod { call, reply ->
168
+ val id = UUID.randomUUID().toString()
169
+ if (!active) { reply.reject(HostErrorCode.CANCELLED, "React instance was invalidated"); return@HostMethod }
170
+ calls[id] = Pending(sessionId, reply, call.keepsResourceAlive)
171
+ call.onCancel = {
172
+ if (calls.remove(id) != null) emit(sessionId, "hostCallCancelled", JSONObject().put("callId", id))
173
+ }
174
+ if (!call.isCancelled) emit(sessionId, "hostCall", JSONObject().put("callId", id).put("method", name).put("payload", call.payload ?: JSONObject.NULL).put("context", call.context ?: JSONObject.NULL).put("deadlineNs",call.deadlineNsDecimal ?: JSONObject.NULL).put("cancelToken",call.cancelToken ?: JSONObject.NULL).put("retainUntilCancelled",call.keepsResourceAlive))
175
+ }
176
+ complete(if (operation == "registerApiHandler") session.registerApiHandler(name,handler) else session.registerHostMethod(name,handler), promise)
177
+ }
178
+ "load" -> {
179
+ val source = if (value.has("asset")) PackSource.Asset(value.getString("asset")) else PackSource.Directory(File(value.getString("directory")).also { require(it.isAbsolute) })
180
+ complete(session.load(source, LoadOptions(value.optString("route").takeIf { value.has("route") }, value.getJSONObject("options"))), promise)
181
+ }
182
+ "sendMessage" -> complete(session.sendMessage(value.opt("message")), promise)
183
+ "navigate" -> complete(session.navigate(value.getString("route"), value.getJSONObject("query"), value.optBoolean("replace")), promise)
184
+ "back" -> complete(session.back(), promise)
185
+ "state" -> complete(session.state(), promise) { it.toString() }
186
+ "capabilities" -> complete(session.capabilities(), promise) { it.toString() }
187
+ "setForeground" -> {
188
+ val entry = checkNotNull(ContainerRegistry.sessions[sessionId])
189
+ entry.requestedForeground = value.getBoolean("visible")
190
+ complete(session.setForeground(entry.requestedForeground && hostForeground), promise)
191
+ }
192
+ "flushStorage" -> complete(session.flushStorage(), promise)
193
+ "close" -> complete(checkNotNull(ContainerRegistry.sessions[sessionId]).close(sessionId), promise)
194
+ "hostComponents", "authorizeInstalledPack", "migrateLegacyStorage", "deleteAccountData", "retryAccountCleanup", "configureHostServices", "hostApiEvent", "hostComponentFrame", "hostComponentEvent", "authorizePhoneButton", "prepareAccountHostServiceSnapshots", "updateHostServiceSnapshots", "switchAccount", "queryAccountSwitch", "updateAccountSwitchLaunch", "acknowledgeAccountCleanup", "retryAccountSwitch", "cancelAccountSwitch", "hostApiResource", "createHostBinary", "readHostBinary", "retainHostBinary", "releaseHostBinary" -> complete(session.hostServicesCommand(operation,value),promise) { JSONArray().put(it ?: JSONObject.NULL).toString().drop(1).dropLast(1) }
195
+ else -> throw IllegalArgumentException("Unsupported adapter operation: $operation")
196
+ }
197
+ } catch (error: Throwable) { reject(promise, error) }
198
+ }
199
+ internal fun emitCleanupCancellation(id: String, operationId: String) {
200
+ emit(id,"accountCleanupCancelled",JSONObject().put("operationId",operationId))
201
+ }
202
+ override fun completeHostCall(sessionId: String, callId: String, response: String, promise: Promise) = reactApplicationContext.runOnUiQueueThread {
203
+ try {
204
+ lookup(sessionId)
205
+ val call = calls[callId]
206
+ if (call != null) {
207
+ require(call.sessionId == sessionId)
208
+ val value = JSONObject(response)
209
+ val error = value.optJSONObject("error")
210
+ if (error != null) {
211
+ val code = when (error.getString("code")) {
212
+ "invalid_request" -> HostErrorCode.INVALID_REQUEST
213
+ "permission_denied" -> HostErrorCode.PERMISSION_DENIED
214
+ "timeout" -> HostErrorCode.TIMEOUT
215
+ "cancelled" -> HostErrorCode.CANCELLED
216
+ "unsupported" -> HostErrorCode.UNSUPPORTED
217
+ else -> throw IllegalArgumentException("Invalid host error code")
218
+ }
219
+ call.reply.reject(code, error.getString("message"), error.optBoolean("retryable"), error.optJSONObject("details") ?: JSONObject())
220
+ } else call.reply.resolve(value.opt("result"))
221
+ if(error != null || !call.retained) calls.remove(callId)
222
+ }
223
+ if (active) promise.resolve(null)
224
+ } catch (error: Throwable) { reject(promise, error) }
225
+ }
226
+ private fun foreground(visible: Boolean) = reactApplicationContext.runOnUiQueueThread {
227
+ hostForeground = visible
228
+ ContainerRegistry.sessions.filterValues { it.owner === this }.forEach { (id, entry) ->
229
+ entry.session.setForeground(visible && entry.requestedForeground).whenComplete { _, error -> if (error != null) emit(id, "error", JSONObject().put("code", "ERR_LIFECYCLE").put("message", error.message)) }
230
+ }
231
+ }
232
+ override fun onHostResume() {
233
+ ContainerRegistry.sessions.values.filter { it.owner===this }.forEach { entry -> entry.deviceServices?.rebindActivity(reactApplicationContext.currentActivity) }
234
+ foreground(true)
235
+ }
236
+ override fun onHostPause() { foreground(false) }
237
+ override fun onHostDestroy() {
238
+ ContainerRegistry.sessions.values.filter { it.owner===this }.forEach { entry -> entry.deviceServices?.rebindActivity(null) }
239
+ foreground(false)
240
+ }
241
+ override fun invalidate() {
242
+ if (!invalidated.compareAndSet(false, true)) return
243
+ active = false
244
+ super.invalidate()
245
+ reactApplicationContext.runOnUiQueueThread {
246
+ reactApplicationContext.removeLifecycleEventListener(this)
247
+ calls.values.forEach { it.reply.reject(HostErrorCode.CANCELLED, "React instance was invalidated") }; calls.clear()
248
+ ContainerRegistry.sessions.filterValues { it.owner === this }.forEach { (id, entry) ->
249
+ entry.session.eventListener = null
250
+ entry.close(id, 3).whenComplete { _, error ->
251
+ if (error != null) android.util.Log.e(NAME, "React invalidation retains failed native owner: $id", error)
252
+ }
253
+ }
254
+ }
255
+ }
256
+ }
@@ -0,0 +1,16 @@
1
+ package com.sonofmagic.weapp.container.reactnative
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+ import com.facebook.react.uimanager.ViewManager
9
+
10
+ class WeappContainerPackage : BaseReactPackage() {
11
+ override fun getModule(name: String, context: ReactApplicationContext): NativeModule? = if (name == WeappContainerModule.NAME) WeappContainerModule(context) else null
12
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
13
+ mapOf(WeappContainerModule.NAME to ReactModuleInfo(WeappContainerModule.NAME, WeappContainerModule::class.java.name, false, false, false, true))
14
+ }
15
+ override fun createViewManagers(context: ReactApplicationContext): List<ViewManager<*, *>> = listOf(WeappContainerViewManager())
16
+ }