@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,74 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": 1,
|
|
3
|
+
"sourceCommit": "1b6a4379089a033947e6e97be8e2796eca2d7799",
|
|
4
|
+
"sourceDirty": false,
|
|
5
|
+
"nativeDependencies": {
|
|
6
|
+
"ios": {
|
|
7
|
+
"schemaVersion": 1,
|
|
8
|
+
"repository": "weapp-container/sdk-ios",
|
|
9
|
+
"sdkVersion": "0.1.0-preview.7.1",
|
|
10
|
+
"tag": "v0.1.0-preview.7.1",
|
|
11
|
+
"sourceCommit": "c15a30cd0a16335c80552c10fbde42b4c6e2fc5c",
|
|
12
|
+
"sourceDirty": false,
|
|
13
|
+
"assets": [
|
|
14
|
+
{
|
|
15
|
+
"component": "swiftpm-native",
|
|
16
|
+
"fileName": "WeappContainerNative-0.1.0-preview.7.1.xcframework.zip",
|
|
17
|
+
"size": 71891415,
|
|
18
|
+
"sha256": "e078d84930dd75723c9d61835c4d53adf0034deba2636c11bc66e718f6b47910"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"component": "cocoapods-sdk",
|
|
22
|
+
"fileName": "WeappContainer-0.1.0-preview.7.1.zip",
|
|
23
|
+
"size": 74802568,
|
|
24
|
+
"sha256": "2675a4da84570ca6e38eb7ba400faa72fbe23b5fdef6f03ec85bb9a778a01ce7"
|
|
25
|
+
}
|
|
26
|
+
],
|
|
27
|
+
"packagingSourceCommit": "cd34d1e5a274e870a36d5dc240b47b09e9ba7950"
|
|
28
|
+
},
|
|
29
|
+
"android": {
|
|
30
|
+
"schemaVersion": 1,
|
|
31
|
+
"repository": "weapp-container/sdk-android",
|
|
32
|
+
"sdkVersion": "0.1.0-preview.7.1",
|
|
33
|
+
"tag": "v0.1.0-preview.7.1",
|
|
34
|
+
"sourceCommit": "d0b2d014b2aa4a6c3313a7ca630ae3b1a9cb30df",
|
|
35
|
+
"sourceDirty": false,
|
|
36
|
+
"assets": [
|
|
37
|
+
{
|
|
38
|
+
"component": "maven-central",
|
|
39
|
+
"coordinate": "io.github.weapp-container:weapp-container-android:0.1.0-preview.7.1",
|
|
40
|
+
"fileName": "weapp-container-android-0.1.0-preview.7.1-central.zip",
|
|
41
|
+
"size": 23252558,
|
|
42
|
+
"sha256": "5baf4e26b09aab44760416b244e7abcbc9fbd8bcc3f1ba034b24b9a1cff5f382"
|
|
43
|
+
}
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"files": {
|
|
48
|
+
"android/build.gradle": "2be791e30d96aee0d561e773828e7f00e2516a039f360090d78f43672d93c048",
|
|
49
|
+
"android/src/main/AndroidManifest.xml": "343d5be1ac17cdd45d1a2f2ddc616c509290e655869125a9422a96d88aa66066",
|
|
50
|
+
"android/src/main/java/com/sonofmagic/weapp/container/reactnative/WeappContainerModule.kt": "0d9dc6287233517546355d659b64cdf41bc1e46fc37c9a93c8056c038e58008d",
|
|
51
|
+
"android/src/main/java/com/sonofmagic/weapp/container/reactnative/WeappContainerPackage.kt": "1926bbccb29a1cb6babf8ff266ff09037dc0ccc675799d05e0523a76e9b0969f",
|
|
52
|
+
"android/src/main/java/com/sonofmagic/weapp/container/reactnative/WeappContainerViewManager.kt": "f281aa6d4fb8665c0cb1e301d01a25116b29c503b9c75f80a3b87068a65d3dd3",
|
|
53
|
+
"ios/WCRNComponentView.h": "47c5a7714c912744b8885d7fe8acb6f1f6dd04233b378ffd30f34036265a962b",
|
|
54
|
+
"ios/WCRNComponentView.mm": "92f2aeaf37dc7e55273443abb099c643d601f5b9187e175cefad331e9d48aefd",
|
|
55
|
+
"ios/WCRNInstance.swift": "0f42f6074008449c822d1500571cd8283789efc575c2f450fbdebb33fffab8a1",
|
|
56
|
+
"ios/WCRNModule.h": "d56dbf86e1aeeb1395c254eb06d3bf1ccce4ec2fcdfe400fac67f4827ff1dcdb",
|
|
57
|
+
"ios/WCRNModule.mm": "98b6a0c70ce746f7ef47a37df2715f3089969852dccae140e2299db6fcc3c85d",
|
|
58
|
+
"lib/index.d.ts": "0c14b7f4c1c147a0dc64fe7806cf2237c0aa4fd3c01a5e9acecb691540b8b360",
|
|
59
|
+
"lib/index.js": "84f614912cbeffecd2eaf3c7bc20addeeab09cecc3f50812ad9dc0ed9a4fe7fe",
|
|
60
|
+
"lib/specs/NativeWeappContainer.d.ts": "9457d91796f72cdd413573affa2377d4899c942829d210f98eb47a03e5c5b8a1",
|
|
61
|
+
"lib/specs/NativeWeappContainer.js": "b50593c75735bd3cda3485162f6801f0f3113308f9a1dd3c4885ac78bad6c42a",
|
|
62
|
+
"lib/specs/WeappContainerNativeComponent.d.ts": "81fd59ef184cd9db907530e2a53c2a19169e420bd239fd286947192d820742f5",
|
|
63
|
+
"lib/specs/WeappContainerNativeComponent.js": "0bd137393ead6206f0c16fb3968429f2f3f1157e15e65ef5c668fa717e946d8c",
|
|
64
|
+
"LICENSE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2",
|
|
65
|
+
"package.json": "fdbb0116fedf859cd8bc9f6af059d16353e54cca88c3bb49ea781a46f62d2ace",
|
|
66
|
+
"react-native.config.js": "b781e240c12b2ecbd0f6ae1bbe64138e113da030a0595e95a6e92d3911b870e0",
|
|
67
|
+
"README.en.md": "469e70a1b7f188867accece2655105b59de312cbeac5c5ac87db8d7e4b0f51a5",
|
|
68
|
+
"README.md": "77d8c1b07bf64205e792d3c7a21f305891aa3cff0005dcddc7277f0207ce7ae9",
|
|
69
|
+
"src/index.tsx": "520a4c2fe3db1d7659f4d52b9f5584bcfa42ad83a3312a34d4468bdec692c34e",
|
|
70
|
+
"src/specs/NativeWeappContainer.ts": "e979e6afb3120f06b3451ee38842383b48e53f7d83fa662f11744eb8bb1dc1a7",
|
|
71
|
+
"src/specs/WeappContainerNativeComponent.ts": "cdfef5677c3a4d34cd10afbfe28c831eb010e8aac1e22489d6f8833e1f376f96",
|
|
72
|
+
"WeappContainerReactNative.podspec": "dd522048d824d5ea487a18d0acca2339875c6cd9714c02a130c463a6a118d6ee"
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/index.tsx
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import type {ViewProps} from 'react-native';
|
|
3
|
+
import Native from './specs/NativeWeappContainer';
|
|
4
|
+
import Surface from './specs/WeappContainerNativeComponent';
|
|
5
|
+
|
|
6
|
+
export type JSONValue = null | boolean | number | string | JSONValue[] | {[key: string]: JSONValue};
|
|
7
|
+
export type JSONObject = {[key: string]: JSONValue};
|
|
8
|
+
export type TrustedApplication = {hostAppId:string;tenantId:string;publisherId:string;appId:string;environment:'develop'|'trial'|'release';version:string;packRoot:string};
|
|
9
|
+
export type HostAccount = {principalId:string|null;epoch:string};
|
|
10
|
+
export type HostServicesConfiguration = {application:TrustedApplication;account:HostAccount;apis?:string[];syncValues?:JSONObject};
|
|
11
|
+
export type NativeDeviceApiOptions = {
|
|
12
|
+
bluetooth?:boolean; allowedNetworkOrigins?:string[]; allowLoopbackForDevelopment?:boolean;
|
|
13
|
+
allowedMediaOrigins?:string[]; dedicatedAudioSession?:boolean; nfc?:boolean; enableWifi?:boolean;
|
|
14
|
+
wifiConfiguration?:{connectToNetworks:boolean;readCurrentNetwork:boolean};
|
|
15
|
+
nfcConfiguration?:{ndef?:boolean;isoDep?:boolean;mifareUltralight?:boolean;nfcF?:boolean;nfcV?:boolean};
|
|
16
|
+
};
|
|
17
|
+
export type HostSnapshotContext = {application:TrustedApplication;account:HostAccount;sessionId:string};
|
|
18
|
+
export type HostApiCallContext = HostSnapshotContext & {callId:string;api:string;deadlineNs:string|null;cancelToken:string|null;componentTarget?:{pageId:string;nodeId:string;ownerScopeId:string|null}};
|
|
19
|
+
export type Configuration = {storage: {key: string} | {memoryOnly: true};hostServices?:HostServicesConfiguration};
|
|
20
|
+
/** Asset paths are relative to Android assets or the iOS main resource bundle. */
|
|
21
|
+
export type PackSource = {directory: string} | {asset: string};
|
|
22
|
+
export type HostErrorCode = 'invalid_request' | 'permission_denied' | 'timeout' | 'cancelled' | 'unsupported';
|
|
23
|
+
export class HostError extends Error {
|
|
24
|
+
constructor(public readonly code: HostErrorCode, message: string, public readonly retryable = false, public readonly details:JSONObject={}) { super(message); }
|
|
25
|
+
}
|
|
26
|
+
export type HostHandler = (payload: JSONValue, context: {signal: AbortSignal;callId:string;method:string;deadlineNs?:string;cancelToken?:string;apiContext?:HostApiCallContext}) => JSONValue | Promise<JSONValue>;
|
|
27
|
+
export type WxRequestPaymentOptions = {
|
|
28
|
+
timeStamp: string;
|
|
29
|
+
nonceStr: string;
|
|
30
|
+
package: string;
|
|
31
|
+
signType: 'MD5' | 'HMAC-SHA256' | 'RSA';
|
|
32
|
+
paySign: string;
|
|
33
|
+
};
|
|
34
|
+
export type WxRequestPaymentHandler = (
|
|
35
|
+
options: WxRequestPaymentOptions,
|
|
36
|
+
context: Parameters<HostHandler>[1],
|
|
37
|
+
) => void | Promise<void>;
|
|
38
|
+
export type AccountCleanupHandler = (context: {operationId:string;signal:AbortSignal}) => void | Promise<void>;
|
|
39
|
+
export type ContainerEvent = {type: 'accountCleanupRequired' | 'ready' | 'navigation' | 'message' | 'error' | 'closed' | 'presented' | 'accountSwitch' | 'hostApiEvent'; payload: JSONValue};
|
|
40
|
+
|
|
41
|
+
function encode(value: JSONValue): string {
|
|
42
|
+
const ancestors = new Set<object>();
|
|
43
|
+
const check = (item: JSONValue): void => {
|
|
44
|
+
if (item === null || typeof item === 'string' || typeof item === 'boolean') return;
|
|
45
|
+
if (typeof item === 'number' && Number.isFinite(item)) return;
|
|
46
|
+
if (typeof item !== 'object' || ancestors.has(item)) throw new TypeError('Expected finite, acyclic JSON data');
|
|
47
|
+
if (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) throw new TypeError('Expected plain JSON data');
|
|
48
|
+
ancestors.add(item);
|
|
49
|
+
for (const child of Object.values(item)) check(child);
|
|
50
|
+
ancestors.delete(item);
|
|
51
|
+
};
|
|
52
|
+
check(value);
|
|
53
|
+
return JSON.stringify(value);
|
|
54
|
+
}
|
|
55
|
+
const owners = new Map<string, WeappContainerController>();
|
|
56
|
+
const lifecycle = globalThis as typeof globalThis & {__weappContainerCleanup?: Promise<void>};
|
|
57
|
+
let disposed = false;
|
|
58
|
+
let subscription: {remove(): void} | undefined;
|
|
59
|
+
|
|
60
|
+
/** Session owner. Keep it outside render; detach and close are separate operations. */
|
|
61
|
+
export class WeappContainerController {
|
|
62
|
+
private handlers = new Map<string, HostHandler>();
|
|
63
|
+
private apiHandlers = new Map<string, HostHandler>();
|
|
64
|
+
private calls = new Map<string, AbortController>();
|
|
65
|
+
private listeners = new Set<(event: ContainerEvent) => void>();
|
|
66
|
+
private cleanupHandlers = new Set<AccountCleanupHandler>();
|
|
67
|
+
private cleanup?: {operationId:string;abort:AbortController};
|
|
68
|
+
private cleanupTasks = new Set<Promise<void>>();
|
|
69
|
+
private cleanupTail: Promise<void> = Promise.resolve();
|
|
70
|
+
private closing?: Promise<void>;
|
|
71
|
+
private closeRequested = false;
|
|
72
|
+
private closed = false;
|
|
73
|
+
private constructor(public readonly sessionId: string) {}
|
|
74
|
+
static async create(configuration: Configuration): Promise<WeappContainerController> {
|
|
75
|
+
await lifecycle.__weappContainerCleanup;
|
|
76
|
+
if (disposed) throw new Error('React Native module was disposed');
|
|
77
|
+
if (!configuration?.storage || (!('memoryOnly' in configuration.storage) && !configuration.storage.key?.trim())) throw new TypeError('Select memoryOnly or a stable nonblank storage key');
|
|
78
|
+
subscription ??= Native.onEvent(event => owners.get(event.sessionId)?.receive(event.type, event.payload));
|
|
79
|
+
const id = await Native.create(encode(configuration as unknown as JSONValue));
|
|
80
|
+
if (disposed) { await Native.invoke(id, 'close', '{}'); throw new Error('React Native module was disposed during create'); }
|
|
81
|
+
const controller = new WeappContainerController(id);
|
|
82
|
+
owners.set(id, controller);
|
|
83
|
+
if(configuration.hostServices) {
|
|
84
|
+
try { await controller.configureHostServices(configuration.hostServices); }
|
|
85
|
+
catch(error) { await controller.close(); throw error; }
|
|
86
|
+
}
|
|
87
|
+
return controller;
|
|
88
|
+
}
|
|
89
|
+
private async command(operation: string, payload: JSONValue = {}): Promise<JSONValue> {
|
|
90
|
+
if (this.closed || this.closeRequested) throw new Error('Container is closing or closed');
|
|
91
|
+
return JSON.parse(await Native.invoke(this.sessionId, operation, encode(payload))) as JSONValue;
|
|
92
|
+
}
|
|
93
|
+
async registerHostMethod(name: string, handler: HostHandler): Promise<void> {
|
|
94
|
+
if (!name.trim() || name.startsWith('wx.') || this.handlers.has(name)) throw new TypeError('Host method must be unique and must not use the wx. namespace');
|
|
95
|
+
this.handlers.set(name, handler);
|
|
96
|
+
try { await this.command('registerHostMethod', {name}); } catch (error) { this.handlers.delete(name); throw error; }
|
|
97
|
+
}
|
|
98
|
+
async configureHostServices(configuration:HostServicesConfiguration):Promise<void> { await this.command('configureHostServices', configuration as unknown as JSONValue); }
|
|
99
|
+
async registerApiHandler(name:string,handler:HostHandler):Promise<void> {
|
|
100
|
+
if(this.apiHandlers.has(name)) throw new TypeError('API handler is already registered');
|
|
101
|
+
this.apiHandlers.set(name,handler);
|
|
102
|
+
try { await this.command('registerApiHandler',{name}); } catch(error) { this.apiHandlers.delete(name); throw error; }
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Install the standard mini-program JSAPI payment boundary.
|
|
106
|
+
* The handler must call the configured official payment SDK and resolve only
|
|
107
|
+
* after its terminal callback; backend order confirmation remains the host's
|
|
108
|
+
* responsibility.
|
|
109
|
+
*/
|
|
110
|
+
async installWxRequestPayment(handler: WxRequestPaymentHandler): Promise<void> {
|
|
111
|
+
await this.registerApiHandler('wx.requestPayment', async (payload, context) => {
|
|
112
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
113
|
+
throw new HostError('invalid_request', 'wx.requestPayment options are required');
|
|
114
|
+
}
|
|
115
|
+
const value = payload as Record<string, unknown>;
|
|
116
|
+
const fields = ['timeStamp', 'nonceStr', 'package', 'signType', 'paySign'] as const;
|
|
117
|
+
for (const field of fields) {
|
|
118
|
+
if (typeof value[field] !== 'string' || value[field].trim().length === 0) {
|
|
119
|
+
throw new HostError('invalid_request', `wx.requestPayment requires non-empty ${field}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (!['MD5', 'HMAC-SHA256', 'RSA'].includes(value.signType as string)) {
|
|
123
|
+
throw new HostError('invalid_request', 'wx.requestPayment signType must be MD5, HMAC-SHA256, or RSA');
|
|
124
|
+
}
|
|
125
|
+
await handler({
|
|
126
|
+
timeStamp: value.timeStamp as string,
|
|
127
|
+
nonceStr: value.nonceStr as string,
|
|
128
|
+
package: value.package as string,
|
|
129
|
+
signType: value.signType as WxRequestPaymentOptions['signType'],
|
|
130
|
+
paySign: value.paySign as string,
|
|
131
|
+
}, context);
|
|
132
|
+
return {errMsg: 'requestPayment:ok'};
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/** Await custom resources before a new account owner can start. */
|
|
136
|
+
registerAccountCleanupHandler(handler:AccountCleanupHandler):()=>void {
|
|
137
|
+
if(this.closed || this.closeRequested) throw new Error('Container is closing or closed');
|
|
138
|
+
this.cleanupHandlers.add(handler); return ()=>this.cleanupHandlers.delete(handler);
|
|
139
|
+
}
|
|
140
|
+
async installNativeDeviceApis(options:NativeDeviceApiOptions={}):Promise<void> {
|
|
141
|
+
await this.command('installNativeDeviceApis',{
|
|
142
|
+
bluetooth:options.bluetooth??true,
|
|
143
|
+
allowedNetworkOrigins:[...(options.allowedNetworkOrigins??[])],
|
|
144
|
+
allowLoopbackForDevelopment:options.allowLoopbackForDevelopment??false,
|
|
145
|
+
allowedMediaOrigins:[...(options.allowedMediaOrigins??[])],
|
|
146
|
+
dedicatedAudioSession:options.dedicatedAudioSession??false,
|
|
147
|
+
nfc:options.nfc??false,
|
|
148
|
+
enableWifi:options.enableWifi??false,
|
|
149
|
+
...(options.wifiConfiguration === undefined ? {} : {wifiConfiguration:{...options.wifiConfiguration}}),
|
|
150
|
+
...(options.nfcConfiguration === undefined ? {} : {nfcConfiguration:{...options.nfcConfiguration}}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
async retryAccountCleanup():Promise<void> { await this.command('retryAccountCleanup'); }
|
|
154
|
+
hostComponents():Promise<JSONValue> { return this.command('hostComponents'); }
|
|
155
|
+
async authorizeInstalledPack(application:TrustedApplication):Promise<void> { await this.command('authorizeInstalledPack',application as unknown as JSONValue); }
|
|
156
|
+
async migrateLegacyStorage(sourceKey:string):Promise<void> { await this.command('migrateLegacyStorage',{sourceKey}); }
|
|
157
|
+
deleteAccountData(principalId:string):Promise<JSONValue> { return this.command('deleteAccountData',{principalId}); }
|
|
158
|
+
async emitHostApiEvent(event:JSONObject):Promise<void> { await this.command('hostApiEvent',event); }
|
|
159
|
+
submitHostComponentFrame(frame:JSONObject):Promise<JSONValue> { return this.command('hostComponentFrame',frame); }
|
|
160
|
+
async emitHostComponentEvent(event:JSONObject):Promise<void> { await this.command('hostComponentEvent',event); }
|
|
161
|
+
async authorizePhoneButton(nodeId:string):Promise<void> { await this.command('authorizePhoneButton',{nodeId}); }
|
|
162
|
+
async prepareAccountHostServiceSnapshots(operationId:string,values:JSONObject):Promise<void> { await this.command('prepareAccountHostServiceSnapshots',{operationId,values}); }
|
|
163
|
+
/** Async producers must capture this native owner before starting their work. */
|
|
164
|
+
async updateHostServiceSnapshots(values:JSONObject,context?:HostSnapshotContext):Promise<void> { await this.command('updateHostServiceSnapshots',{values,...(context===undefined?{}:{context:context as unknown as JSONValue})}); }
|
|
165
|
+
switchAccount(account:HostAccount,launches:JSONObject={}):Promise<JSONValue> { return this.command('switchAccount',{account:account as unknown as JSONValue,launches}); }
|
|
166
|
+
queryAccountSwitch(operationId?:string):Promise<JSONValue> { return this.command('queryAccountSwitch',operationId?{operationId}:{}); }
|
|
167
|
+
async updateAccountSwitchLaunch(options:JSONObject):Promise<void> { await this.command('updateAccountSwitchLaunch',{options}); }
|
|
168
|
+
async retryAccountSwitch(options:JSONObject={}):Promise<void> { await this.command('retryAccountSwitch',{options}); }
|
|
169
|
+
async cancelAccountSwitch(operationId:string):Promise<void> { await this.command('cancelAccountSwitch',{operationId}); }
|
|
170
|
+
createHostBinary(bytes:Uint8Array):Promise<JSONValue> { return this.command('createHostBinary',{bytes:Array.from(bytes)}); }
|
|
171
|
+
readHostBinary(id:string,offset:number,length:number):Promise<JSONValue> { return this.command('readHostBinary',{id,offset,length}); }
|
|
172
|
+
/** Read only the asset bound to an exact live API context; requires apiResourceChunks 1.0. */
|
|
173
|
+
readHostApiResource(context:HostApiCallContext,offset:number,length:number):Promise<JSONValue> { return this.command('hostApiResource',{context:context as unknown as JSONValue,offset,length}); }
|
|
174
|
+
async retainHostBinary(id:string):Promise<void> { await this.command('retainHostBinary',{id}); }
|
|
175
|
+
async releaseHostBinary(id:string):Promise<void> { await this.command('releaseHostBinary',{id}); }
|
|
176
|
+
async load(source: PackSource, options: {route?: string; options?: JSONObject} = {}): Promise<void> {
|
|
177
|
+
await this.command('load', {...source, ...(options.route === undefined ? {} : {route: options.route}), options: options.options ?? {}});
|
|
178
|
+
}
|
|
179
|
+
async sendMessage(message: JSONValue): Promise<void> { await this.command('sendMessage', {message}); }
|
|
180
|
+
async navigate(route: string, query: JSONObject = {}, replace = false): Promise<void> { await this.command('navigate', {route, query, replace}); }
|
|
181
|
+
async back(): Promise<void> { await this.command('back'); }
|
|
182
|
+
async setForeground(visible: boolean): Promise<void> { await this.command('setForeground', {visible}); }
|
|
183
|
+
async flushStorage(): Promise<void> { await this.command('flushStorage'); }
|
|
184
|
+
state(): Promise<JSONValue> { return this.command('state'); }
|
|
185
|
+
capabilities(): Promise<JSONValue> { return this.command('capabilities'); }
|
|
186
|
+
subscribe(listener: (event: ContainerEvent) => void): () => void {
|
|
187
|
+
if (this.closed) throw new Error('Container is closed');
|
|
188
|
+
this.listeners.add(listener);
|
|
189
|
+
return () => this.listeners.delete(listener);
|
|
190
|
+
}
|
|
191
|
+
close(): Promise<void> {
|
|
192
|
+
if (this.closed) return Promise.resolve();
|
|
193
|
+
if (this.closing) return this.closing;
|
|
194
|
+
this.closeRequested = true;
|
|
195
|
+
for (const call of this.calls.values()) call.abort();
|
|
196
|
+
this.calls.clear();
|
|
197
|
+
this.cleanup?.abort.abort(); this.cleanup=undefined;
|
|
198
|
+
this.closing = (async () => {
|
|
199
|
+
// Superseded account cleanup must finish before resources are retired again.
|
|
200
|
+
await Promise.allSettled([...this.cleanupTasks]);
|
|
201
|
+
const abort = new AbortController();
|
|
202
|
+
const results = await Promise.allSettled([...this.cleanupHandlers].map(handler =>
|
|
203
|
+
Promise.resolve().then(() => handler({operationId:`close:${this.sessionId}`,signal:abort.signal}))));
|
|
204
|
+
const failures = results.filter((result):result is PromiseRejectedResult => result.status==='rejected');
|
|
205
|
+
if(failures.length) throw new AggregateError(failures.map(result=>result.reason),'Container resource cleanup failed');
|
|
206
|
+
await Native.invoke(this.sessionId, 'close', '{}');
|
|
207
|
+
this.closed = true; owners.delete(this.sessionId); this.listeners.clear(); this.handlers.clear(); this.apiHandlers.clear(); this.cleanupHandlers.clear();
|
|
208
|
+
})().catch(error => { this.closing = undefined; throw error; });
|
|
209
|
+
return this.closing;
|
|
210
|
+
}
|
|
211
|
+
private receive(type: string, payloadJSON: string): void {
|
|
212
|
+
const payload = JSON.parse(payloadJSON) as JSONObject;
|
|
213
|
+
if(type==='accountSwitch' && (payload.receipt as JSONObject | undefined)?.phase==='revoking') { this.cleanup?.abort.abort(); for(const call of this.calls.values()) call.abort(); this.calls.clear(); }
|
|
214
|
+
if(type==='accountCleanupRequired') {
|
|
215
|
+
if(this.closed) return;
|
|
216
|
+
const task=this.cleanupAccount(String(payload.operationId)); this.cleanupTasks.add(task);
|
|
217
|
+
void task.finally(()=>this.cleanupTasks.delete(task)); return;
|
|
218
|
+
}
|
|
219
|
+
if(type==='accountCleanupCancelled') {
|
|
220
|
+
if(this.cleanup?.operationId===String(payload.operationId)) this.cleanup.abort.abort();
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (type === 'hostCallCancelled') {
|
|
224
|
+
const id = String(payload.callId); this.calls.get(id)?.abort(); this.calls.delete(id); return;
|
|
225
|
+
}
|
|
226
|
+
if (type === 'hostCall') { void this.dispatchHostCall(payload); return; }
|
|
227
|
+
for (const listener of this.listeners) {
|
|
228
|
+
try { listener({type: type as ContainerEvent['type'], payload}); }
|
|
229
|
+
catch (error) { console.error('WeappContainer event listener failed', error); }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
private cleanupAccount(operationId:string):Promise<void> {
|
|
233
|
+
this.cleanup?.abort.abort();
|
|
234
|
+
const current={operationId,abort:new AbortController()}; this.cleanup=current;
|
|
235
|
+
const run=async():Promise<void>=>{
|
|
236
|
+
let response:JSONObject={operationId};
|
|
237
|
+
const retired=()=>this.cleanup!==current || current.abort.signal.aborted || this.closed || this.closeRequested;
|
|
238
|
+
try { if(!retired()) {
|
|
239
|
+
const results=await Promise.allSettled([...this.cleanupHandlers].map(handler=>Promise.resolve().then(()=>handler({operationId,signal:current.abort.signal}))));
|
|
240
|
+
const failures=results.filter((result):result is PromiseRejectedResult=>result.status==='rejected');
|
|
241
|
+
if(failures.length) throw new AggregateError(failures.map(result=>result.reason),'Account resource cleanup failed');
|
|
242
|
+
} } catch(error) { response.error={code:'ERR_ACCOUNT_CLEANUP',message:error instanceof Error?error.message:String(error)}; }
|
|
243
|
+
if(retired()) response={operationId,retired:true};
|
|
244
|
+
// Even a revoked/closing owner must finish its exact transport waiter.
|
|
245
|
+
// Native treats retired as cancellation and never as permission to start.
|
|
246
|
+
try { await Native.invoke(this.sessionId,'completeAccountCleanup',encode(response)); }
|
|
247
|
+
catch(error) { if(!this.closed && !this.closing) console.error('WeappContainer account cleanup reply failed',error); }
|
|
248
|
+
finally { if(this.cleanup===current) this.cleanup=undefined; }
|
|
249
|
+
};
|
|
250
|
+
// Cancellation gates the old operation immediately, but only its actual
|
|
251
|
+
// handler terminals release devices/files for the next account or close.
|
|
252
|
+
const task=this.cleanupTail.then(run,run);
|
|
253
|
+
this.cleanupTail=task.then(()=>{},()=>{});
|
|
254
|
+
return task;
|
|
255
|
+
}
|
|
256
|
+
private async dispatchHostCall(payload: JSONObject): Promise<void> {
|
|
257
|
+
const id = String(payload.callId);
|
|
258
|
+
if (this.closeRequested || this.closed) {
|
|
259
|
+
try { await Native.completeHostCall(this.sessionId, id, encode({error: {code: 'cancelled', message: 'Container is closing', retryable: false}})); } catch { /* Native close may already have cancelled this call. */ }
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const abort = new AbortController(); this.calls.set(id, abort);
|
|
263
|
+
let response: JSONValue;
|
|
264
|
+
try {
|
|
265
|
+
const handler = this.apiHandlers.get(String(payload.method)) ?? this.handlers.get(String(payload.method));
|
|
266
|
+
if (!handler) throw new HostError('unsupported', 'Host method is not registered');
|
|
267
|
+
const result = await handler(payload.payload ?? null, {signal: abort.signal,callId:id,method:String(payload.method),...(payload.deadlineNs==null?{}:{deadlineNs:String(payload.deadlineNs)}),...(payload.cancelToken==null?{}:{cancelToken:String(payload.cancelToken)}),...(payload.context?{apiContext:payload.context as unknown as HostApiCallContext}:{})});
|
|
268
|
+
encode(result); response = {result};
|
|
269
|
+
} catch (error) {
|
|
270
|
+
response = {error: {code: error instanceof HostError ? error.code : 'invalid_request', message: error instanceof Error ? error.message : String(error), retryable: error instanceof HostError && error.retryable,details:error instanceof HostError?error.details:{}}};
|
|
271
|
+
}
|
|
272
|
+
if (this.calls.get(id) !== abort || abort.signal.aborted) return;
|
|
273
|
+
if(!(payload.retainUntilCancelled===true && response!==null && typeof response==='object' && 'result' in response)) this.calls.delete(id);
|
|
274
|
+
try { await Native.completeHostCall(this.sessionId, id, encode(response)); }
|
|
275
|
+
catch (error) { if (!this.closing && !this.closed) console.error('WeappContainer host reply failed', error); }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
export type WeappContainerViewProps = ViewProps & {controller: WeappContainerController; onSurfaceError?: (error: {code: string; message: string}) => void};
|
|
279
|
+
export function WeappContainerView({controller, onSurfaceError, ...props}: WeappContainerViewProps): React.JSX.Element {
|
|
280
|
+
return <Surface {...props} sessionId={controller.sessionId} onSurfaceError={onSurfaceError ? event => onSurfaceError(event.nativeEvent) : undefined} />;
|
|
281
|
+
}
|
|
282
|
+
/** Await before replacing an entire React surface or account. Failed close remains retryable. */
|
|
283
|
+
export async function closeAllContainers(): Promise<void> {
|
|
284
|
+
const results = await Promise.allSettled([...owners.values()].map(owner => owner.close()));
|
|
285
|
+
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
|
|
286
|
+
if (failures.length) throw new AggregateError(failures.map(result => result.reason), 'Container cleanup failed');
|
|
287
|
+
}
|
|
288
|
+
declare const module: {hot?: {dispose(callback: () => void): void}};
|
|
289
|
+
if (typeof module !== 'undefined' && module.hot) module.hot.dispose(() => {
|
|
290
|
+
disposed = true;
|
|
291
|
+
const cleanup = closeAllContainers().finally(() => { subscription?.remove(); subscription = undefined; });
|
|
292
|
+
lifecycle.__weappContainerCleanup = cleanup;
|
|
293
|
+
// Retain the rejection for the next create, and avoid an unhandled promise rejection meanwhile.
|
|
294
|
+
void cleanup.catch(error => console.error('WeappContainer Fast Refresh cleanup failed', error));
|
|
295
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type {TurboModule, CodegenTypes} from 'react-native';
|
|
2
|
+
import {TurboModuleRegistry} from 'react-native';
|
|
3
|
+
export type NativeEvent = Readonly<{sessionId: string; type: string; payload: string}>;
|
|
4
|
+
export interface Spec extends TurboModule {
|
|
5
|
+
create(configuration: string): Promise<string>;
|
|
6
|
+
invoke(sessionId: string, operation: string, payload: string): Promise<string>;
|
|
7
|
+
completeHostCall(sessionId: string, callId: string, response: string): Promise<void>;
|
|
8
|
+
readonly onEvent: CodegenTypes.EventEmitter<NativeEvent>;
|
|
9
|
+
}
|
|
10
|
+
export default TurboModuleRegistry.getEnforcing<Spec>('WeappContainer');
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type {ViewProps, HostComponent, CodegenTypes} from 'react-native';
|
|
2
|
+
import {codegenNativeComponent} from 'react-native';
|
|
3
|
+
type SurfaceError = Readonly<{code: string; message: string}>;
|
|
4
|
+
export interface NativeProps extends ViewProps {
|
|
5
|
+
sessionId: string;
|
|
6
|
+
onSurfaceError?: CodegenTypes.DirectEventHandler<SurfaceError>;
|
|
7
|
+
}
|
|
8
|
+
export default codegenNativeComponent<NativeProps>('WeappContainerNativeView') as HostComponent<NativeProps>;
|