@retion-miniapp/react-native 0.8.1 → 0.9.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/README.md +4 -3
- package/app.plugin.js +7 -2
- package/dist/index.d.mts +19 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.js +7 -7
- package/dist/index.mjs +7 -7
- package/docs/MINIAPP_README.md +331 -141
- package/docs/NATIVE_APIS.md +332 -0
- package/docs/SPEECH.md +2 -2
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -5,8 +5,9 @@ Package chạy mini app web trong app React Native: tải bundle, lưu cục b
|
|
|
5
5
|
## Đọc theo thứ tự
|
|
6
6
|
|
|
7
7
|
1. [Cài đặt, cấu hình và mở mini app](docs/MINIAPP_README.md).
|
|
8
|
-
2. [
|
|
9
|
-
3. [
|
|
8
|
+
2. [Tích hợp API native: Face ID / Touch ID và speech-to-text](docs/NATIVE_APIS.md).
|
|
9
|
+
3. [Nhận dạng giọng nói: quyền, hoạt động, API và quản lý phiên](docs/SPEECH.md).
|
|
10
|
+
4. [Face ID / Touch ID: quyền, API và kết quả native](docs/BIOMETRICS.md).
|
|
10
11
|
|
|
11
12
|
## Ai làm phần nào?
|
|
12
13
|
|
|
@@ -21,7 +22,7 @@ Cài package không sửa được binary đã cài trên thiết bị. Nếu bi
|
|
|
21
22
|
|
|
22
23
|
## Phiên bản và điều kiện tích hợp
|
|
23
24
|
|
|
24
|
-
Tài liệu hiện tại mô tả **Mini App React Native 0.8.
|
|
25
|
+
Tài liệu hiện tại mô tả **Mini App React Native 0.8.1 + Web SDK 0.8.0**. Package khai báo React ≥18, React Native ≥0.72, Expo ≥52 và WebView ≥13; đây là giới hạn khai báo, không phải cam kết mọi tổ hợp phiên bản native đã được kiểm tra. App React Native thuần cần tích hợp Expo Modules để dùng thư viện speech.
|
|
25
26
|
|
|
26
27
|
Package tự cài `react-native-biometrics@3.0.1` và `expo-speech-recognition@1.1.1`. Nếu app cũng dùng các thư viện này cho chức năng khác, đồng bộ phiên bản để tránh trùng module native. Với Expo 57, xem lưu ý bản vá của thư viện speech trong [hướng dẫn speech](docs/SPEECH.md).
|
|
27
28
|
|
package/app.plugin.js
CHANGED
|
@@ -7,6 +7,9 @@ module.exports = function withMiniApp(config, options = {}) {
|
|
|
7
7
|
config.modResults.NSFaceIDUsageDescription = options.faceIDPermission
|
|
8
8
|
|| config.modResults.NSFaceIDUsageDescription
|
|
9
9
|
|| 'Allow this app to use Face ID to verify your identity.';
|
|
10
|
+
config.modResults.NSLocationWhenInUseUsageDescription = options.locationPermission
|
|
11
|
+
|| config.modResults.NSLocationWhenInUseUsageDescription
|
|
12
|
+
|| 'Allow this app to access your location while you use it.';
|
|
10
13
|
return config;
|
|
11
14
|
});
|
|
12
15
|
config = withSpeechRecognition(config, {
|
|
@@ -17,8 +20,10 @@ module.exports = function withMiniApp(config, options = {}) {
|
|
|
17
20
|
return withAndroidManifest(config, config => {
|
|
18
21
|
const manifest = config.modResults.manifest;
|
|
19
22
|
const permissions = manifest['uses-permission'] || [];
|
|
20
|
-
|
|
21
|
-
permissions.
|
|
23
|
+
for (const name of ['android.permission.USE_BIOMETRIC', 'android.permission.ACCESS_COARSE_LOCATION', 'android.permission.ACCESS_FINE_LOCATION']) {
|
|
24
|
+
if (!permissions.some(item => item.$?.['android:name'] === name)) {
|
|
25
|
+
permissions.push({ $: { 'android:name': name } });
|
|
26
|
+
}
|
|
22
27
|
}
|
|
23
28
|
manifest['uses-permission'] = permissions;
|
|
24
29
|
return config;
|
package/dist/index.d.mts
CHANGED
|
@@ -551,4 +551,22 @@ interface SpeechOptions {
|
|
|
551
551
|
/** Đóng/ẩn mini app: huỷ, không lấy kết quả cuối. Giữ khoá đến native end để tránh event phiên cũ sang phiên mới. */
|
|
552
552
|
declare const releaseSpeechFor: (owner: string) => void;
|
|
553
553
|
|
|
554
|
-
|
|
554
|
+
interface LocationOptions {
|
|
555
|
+
enableHighAccuracy?: boolean;
|
|
556
|
+
timeout?: number;
|
|
557
|
+
maximumAge?: number;
|
|
558
|
+
}
|
|
559
|
+
interface LocationResult {
|
|
560
|
+
coords: {
|
|
561
|
+
latitude: number;
|
|
562
|
+
longitude: number;
|
|
563
|
+
accuracy: number;
|
|
564
|
+
altitude: number | null;
|
|
565
|
+
altitudeAccuracy: number | null;
|
|
566
|
+
heading: number | null;
|
|
567
|
+
speed: number | null;
|
|
568
|
+
};
|
|
569
|
+
timestamp: number;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
|
package/dist/index.d.ts
CHANGED
|
@@ -551,4 +551,22 @@ interface SpeechOptions {
|
|
|
551
551
|
/** Đóng/ẩn mini app: huỷ, không lấy kết quả cuối. Giữ khoá đến native end để tránh event phiên cũ sang phiên mới. */
|
|
552
552
|
declare const releaseSpeechFor: (owner: string) => void;
|
|
553
553
|
|
|
554
|
-
|
|
554
|
+
interface LocationOptions {
|
|
555
|
+
enableHighAccuracy?: boolean;
|
|
556
|
+
timeout?: number;
|
|
557
|
+
maximumAge?: number;
|
|
558
|
+
}
|
|
559
|
+
interface LocationResult {
|
|
560
|
+
coords: {
|
|
561
|
+
latitude: number;
|
|
562
|
+
longitude: number;
|
|
563
|
+
accuracy: number;
|
|
564
|
+
altitude: number | null;
|
|
565
|
+
altitudeAccuracy: number | null;
|
|
566
|
+
heading: number | null;
|
|
567
|
+
speed: number | null;
|
|
568
|
+
};
|
|
569
|
+
timestamp: number;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var hn=Object.create;var be=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var Mn=(e,t)=>{for(var n in t)be(e,n,{get:t[n],enumerable:!0})},lt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of An(t))!yn.call(e,o)&&o!==n&&be(e,o,{get:()=>t[o],enumerable:!(r=mn(t,o))||r.enumerable});return e};var fe=(e,t,n)=>(n=e!=null?hn(wn(e)):{},lt(t||!e||!e.__esModule?be(n,"default",{value:e,enumerable:!0}):n,e)),vn=e=>lt(be({},"__esModule",{value:!0}),e);var Vn={};Mn(Vn,{DefaultMiniAppSplash:()=>nt,MINIAPP_PLATFORM_URL:()=>_e,MiniAppHost:()=>ln,MiniAppHostError:()=>g,closeMiniApp:()=>pe,configureMiniApp:()=>dt,createMmkvStorage:()=>ht,createReactNativeBiometrics:()=>Ue,createRnfsFileSystem:()=>ft,ensureMiniApp:()=>Me,getLocalMiniApp:()=>x,getMiniAppCatalog:()=>sn,getMiniAppCatalogEntry:()=>le,getMiniAppStatuses:()=>Gt,getMiniAppUpdate:()=>et,installBundledMiniApp:()=>$t,onMiniAppEvent:()=>Yt,openMiniApp:()=>qt,pauseMiniApp:()=>en,pauseMiniAppDownloads:()=>nn,preloadMiniApp:()=>Ht,releaseSpeechFor:()=>z,restoreMiniApp:()=>Zt,resumeMiniApp:()=>tn,resumeMiniAppDownloads:()=>rn,sendEventToWeb:()=>Ut,syncMiniAppCatalog:()=>$e,uninstallMiniApp:()=>Xt,updateMiniApp:()=>on,useMiniAppDownload:()=>Ne,useMiniAppDownloadsPaused:()=>Kt});module.exports=vn(Vn);var _e="https://retion-miniapp-platform.vercel.app",se=null,ut=new Set,dt=e=>{se=e,ut.forEach(t=>t())},R=()=>{if(!se)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return se},gt=e=>{ut.add(e),se&&e()},$=(...e)=>{se!=null&&se.debug&&console.log("[miniapp]",...e)};var ft=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:o})=>{let{jobId:s,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:i})=>o==null?void 0:o(c,i)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(s)}}}),ht=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var f=fe(require("react")),b=require("react-native"),pn=fe(require("react-native-webview"));var he=require("react-native");var Ue=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),xe,Je=()=>(xe||(xe=import("react-native-biometrics").then(({default:e})=>Ue(new e({allowDeviceCredentials:!1}))).catch(e=>{throw xe=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),xe);var W=require("react-native");var mt=e=>{var n,r,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[s,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let i=t[s];if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||i<a||i>c))throw new g("INVALID_PARAMS",`${s} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},At=(e,t=()=>!0)=>new Promise((n,r)=>{let o=!1,s=(i,p)=>{o||(o=!0,clearTimeout(a),i?r(i):n(p))},a=setTimeout(()=>s(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>o?!1:t()?!0:(s(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let i;try{i=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(W.Platform.OS==="android"){let p=W.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,y=W.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await W.PermissionsAndroid.check(p);if(!c())return;let M=d||await W.PermissionsAndroid.check(y);if(!c())return;if(!d&&!M){let A=await W.PermissionsAndroid.requestMultiple([p,y]);if(!c())return;if(A[p]!==W.PermissionsAndroid.RESULTS.GRANTED&&A[y]!==W.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&i.getCurrentPosition(p=>{c()&&s(void 0,p)},p=>{var d;if(!c())return;let y=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[p.code])!=null?d:"LOCATION_ERROR";s(new g(y,p.message))},e)}})().catch(i=>s(i))});var wt=require("react-native");var G,qe=e=>{var t;if(G===e&&(G=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&wt.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},yt=async(e,t,n,r=()=>!0)=>{var s,a,c,i,p;if(G)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};G=o;try{let y;try{y=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=y.ExpoSpeechRecognitionModule;if(o.native=d,o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let M=await d.requestPermissionsAsync();if(o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!M.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(d.addListener("result",A=>{var w,C;G!==o||o.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(C=(w=A.results[0])==null?void 0:w.transcript)!=null?C:""})}),d.addListener("error",A=>{G===o&&!o.cancelled&&n("speech.error",{...A,code:A.error})}),d.addListener("end",()=>{G===o&&(qe(o),n("speech.end"))})),o.started=!0,d.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(i=t.addsPunctuation)!=null?i:!0,requiresOnDeviceRecognition:(p=t.requiresOnDeviceRecognition)!=null?p:!1,iosCategory:{category:y.AVAudioSessionCategory.playAndRecord,categoryOptions:[y.AVAudioSessionCategoryOptions.defaultToSpeaker,y.AVAudioSessionCategoryOptions.allowBluetooth],mode:y.AVAudioSessionMode.measurement}})}catch(y){throw qe(o),y}},Mt=e=>{let t=G;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},z=e=>{let t=G;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{qe(t)}};var Pe=1,g=class extends Error{constructor(n,r){super(r);this.code=n}},vt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Pe&&typeof t.method=="string"?t:null}catch{return null}},me=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,St=(e,t)=>me({id:e,result:t}),bt=(e,t)=>me({id:e,error:{code:t.code,message:t.message}}),_t=(e,t)=>me({event:e,data:t}),je=e=>me({event:"context",data:e});var xt=()=>`(function () {
|
|
2
2
|
var post = function (level, args) {
|
|
3
3
|
try {
|
|
4
4
|
var parts = [];
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
|
|
9
9
|
else { parts.push(String(a)); }
|
|
10
10
|
}
|
|
11
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
11
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Pe}, method: 'log', level: level, text: parts.join(' ') }));
|
|
12
12
|
} catch (e) {}
|
|
13
13
|
};
|
|
14
14
|
['log', 'info', 'warn', 'error'].forEach(function (level) {
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
|
|
20
20
|
// Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
|
|
21
21
|
post('info', ['[page] ' + location.pathname + location.hash]);
|
|
22
|
-
})(); true;`,
|
|
22
|
+
})(); true;`,Et=()=>`(function () {
|
|
23
23
|
function atTop(el) {
|
|
24
24
|
for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
|
|
25
25
|
if (n.scrollTop > 0) { return false; }
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
function report(at_top) {
|
|
31
31
|
if (at_top === last) { return; }
|
|
32
32
|
last = at_top;
|
|
33
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
33
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Pe}, method: 'touchAtTop', at_top: at_top }));
|
|
34
34
|
}
|
|
35
35
|
document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
|
|
36
36
|
// Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
|
|
@@ -38,8 +38,8 @@
|
|
|
38
38
|
var el = e.target === document ? document.documentElement : e.target;
|
|
39
39
|
if (el && el.scrollTop > 0) { report(false); }
|
|
40
40
|
}, { capture: true, passive: true });
|
|
41
|
-
})(); true;`,
|
|
42
|
-
${je(e)}`},
|
|
41
|
+
})(); true;`,Rt=e=>me({event:e}),Pt=(e,t)=>{let n=Tt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
|
|
42
|
+
${je(e)}`},Tt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Ot=(e,t={})=>{let n=Tt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Pe} };
|
|
43
43
|
window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
|
|
44
44
|
${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
|
|
45
|
-
true;`},Pt={partner:"partner_token",chatbox:"chatbox_token"},Tt=(e,t)=>{let n={...e};for(let r of Object.values(Pt))t.includes(r)||delete n[r];return n},Je=new Set,qe=async(e,t)=>{if(Je.has(e))throw new w("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Je.add(e);try{return await t()}finally{Je.delete(e)}},Mn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),xe=(e,t)=>{if(typeof e!="string"||!e)throw new w("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Ot=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:p,options:i,emit:u,isActive:M})=>{var m,C,T,N,l,k,le,X,Me;let h=i==null?void 0:i.handlers,v={app_id:a,instance_id:p,close:s},A=()=>new w("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"speech.start":{if(!u)throw A();let g={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new w("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");g.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new w("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);g[S]=t[S]}return mt(p,g,u,M)}case"speech.stop":return At(p);case"getBiometricAvailability":return((m=i==null?void 0:i.biometrics)!=null?m:await Ve()).getAvailability();case"authenticateBiometric":{let g=xe(t==null?void 0:t.reason,"reason").trim();if(!g||g.length>200)throw new w("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new w("INVALID_PARAMS","Invalid cancelButtonText");return qe(e,async()=>{var re;return((re=i==null?void 0:i.biometrics)!=null?re:await Ve()).authenticate({reason:g,cancelButtonText:S})})}case"requestPayment":{let g=h==null?void 0:h.requestPayment;if(!g)throw A();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new w("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let U={...t,amount:S,currency:xe(t==null?void 0:t.currency,"currency")};return qe(e,()=>g(U,v))}case"printImage":{let g=h==null?void 0:h.printImage;if(!g)throw A();let S=xe(t==null?void 0:t.image,"image");await qe(e,()=>g({image:S},v));return}case"openScreen":if(!(h!=null&&h.openScreen))throw A();await h.openScreen({screen:xe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},v);return;case"closeApp":s();return;case"openWebview":{let g=String((C=t==null?void 0:t.url)!=null?C:"");if(!/^https?:\/\//i.test(g))throw new w("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(g):ge.Linking.openURL(g));return}case"openLink":{let g=String((T=t==null?void 0:t.url)!=null?T:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(g)||/^(javascript|file|data|about|blob):/i.test(g))throw new w("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(g):ge.Linking.openURL(g))}catch(S){throw new w("NOT_SUPPORTED",String((l=(N=S==null?void 0:S.message)!=null?N:S)!=null?l:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(le=i==null?void 0:i.showToast)==null||le.call(i,String((k=t==null?void 0:t.message)!=null?k:""));return;case"haptic":{let g=Mn.has(t==null?void 0:t.type)?t.type:"selection";(X=i==null?void 0:i.haptic)==null||X.call(i,g);return}case"getSystemInfo":return{platform:ge.Platform.OS==="ios"?"ios":"android",appVersion:(Me=i==null?void 0:i.app_version)!=null?Me:"",theme:o?"dark":"light"};case"getAccessToken":{let g=n().access_token;if(!g)throw new w("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return g}case"getToken":{let g=t==null?void 0:t.type;if(g==="access"){let re=n().access_token;if(!re)throw new w("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(g!=="partner"&&g!=="chatbox")throw new w("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(g)}`);let S=Pt[g];if(!r().includes(S))throw new w("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let U=g==="partner"?n().partner_token:n().chatbox_token;if(!U)throw new w("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return U}case"getUserInfo":{let g=n().user;if(!g)throw new w("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return g}case"getPageInfo":{let g=n().page;if(!g)throw new w("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return g}case"sendMessage":case"insertText":throw new w("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new w("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var We=e=>`bundle:${e}`,ze=()=>`${R().file_system.document_dir}/miniapps`,Ke=ze,Ye=(e,t,n="index.html",r=!1,o=[])=>{let s=`${Ke()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},He=e=>{var t;R().storage.setString(We(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},yn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,x=e=>{let t=R().storage.getString(We(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return Ye(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>R().file_system.exists(e.entry_uri.replace("file://","")),Qe=async e=>{let t=x(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},kt=async(e,t)=>{let n=R().file_system,r=`${Ke()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},Dt=async e=>{var t;await((t=me[e])==null?void 0:t.catch(()=>{})),R().storage.setString(We(e),""),await R().file_system.remove(`${Ke()}/${e}`).catch(()=>{})},ae=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},me={},It=(e,t)=>{var s;let r=((s=me[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return me[e]=o,o.then(()=>{me[e]===o&&delete me[e]}),r},vn=(e,t)=>{var o,s;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let p=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(p)return p}return 0},Lt=({manifest:e,zip_path:t})=>It(e.app_id,async()=>{var s;let n=R().file_system,r=x(e.app_id);if(r&&vn(r.version,e.version)>=0&&await Q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=Ye(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),He(e),$("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),kt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Ge=(e,{base_url:t,onProgress:n}={})=>{let r=R().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(s)throw new ae},i=async()=>{var h;p();let u=x(e.app_id);if((u==null?void 0:u.version)===e.version&&await r.exists(u.dir))return He(e),x(e.app_id);p();let M=r.download({url:t?yn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(v,A)=>{var C;let m=A>0?A:(C=e.size)!=null?C:0;m>0&&(n==null||n(Math.min(1,v/m)))}});o=M;try{let{status:v}=await M.promise;if(p(),v!==200)throw new Error(`bundle ${v}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else $("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let A=Ye(e.app_id,e.version,e.entry,!!e.context_update,(h=e.permissions)!=null?h:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),He(e),kt(e.app_id,[e.version,u==null?void 0:u.version].filter(Boolean)),A}catch(v){throw s?new ae:v}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:It(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},he={},Sn=__DEV__?0:60*1e3,Ct={},Nt=(e,t)=>{var r,o;let n=x(e);return n&&Date.now()-((r=Ct[t])!=null?r:0)<Sn?Promise.resolve(n):((o=he[e])!=null||(he[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),p=await Ge(a,{base_url:t}).promise;return Ct[t]=Date.now(),p})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),x(e))).finally(()=>{he[e]=void 0})),he[e])};var Re=new Map,Bt=(e,t)=>(Re.set(e,t),()=>{Re.get(e)===t&&Re.delete(e)}),$t=(e,t)=>{let n=Re.get(e);return n?n(t):!1};var Pe=require("react"),Te=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},z=(e,t,n=Object.is)=>{let r=(0,Pe.useRef)(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let p=t(s),i=a&&n(a.value,p)?a.value:p;return r.current={state:s,selector:t,value:i},i};return(0,Pe.useSyncExternalStore)(e.subscribe,o)};var F=Te({active_key:null,instances:{}}),Ft=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var p;let a=(p=R().keep_alive)==null?void 0:p.max_webviews;F.setState(i=>{let u=t!=null?t:e.app_id,M={...i.instances,[u]:{key:u,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},h=Object.keys(M);return a&&a>0&&h.length>a&&h.filter(v=>v!==u).sort((v,A)=>M[v].last_used_at-M[A].last_used_at).slice(0,h.length-a).forEach(v=>{delete M[v]}),s?{active_key:u,instances:M}:{instances:M}})},Vt=e=>Ft(e,!0),Ut=e=>Ft(e,!1),ce=()=>F.setState({active_key:null}),Oe=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Jt="catalog",bn="paused_apps",_n="removed_apps",xn=10*1e3,En=2,Rn=3e3,Pn=()=>{var e;try{return JSON.parse((e=R().storage.getString(Jt))!=null?e:"{}")}catch{return{}}},_=Te({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),qt=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},De=new Set,jt=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let o=JSON.parse((r=R().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},j=jt(bn),ne=jt(_n);dt(()=>{j.load(),ne.load();let e=Pn(),t={};Object.keys(e).filter(n=>!ne.has(n)).forEach(n=>{let r=x(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:j.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var Ie=e=>z(_,t=>e?t.downloads[e]:void 0),Ht=()=>z(_,e=>e.pause_reasons.length>0),q=(...e)=>$("queue",...e),O=[],G={},y=null,Ce=new Set,se={},Xe=new Set,ee=e=>{Xe.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Wt=e=>(Xe.add(e),()=>{Xe.delete(e)}),zt=()=>_.getState().downloads,L=(e,t)=>{let n=!!x(e),r=_.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?ee({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&ee({type:"progress",app_id:e,progress:s.progress,version:s.version})},ke=(e,t)=>{var n;(n=se[e])==null||n.forEach(r=>r(t)),delete se[e]},Tn=()=>_.getState().pause_reasons.length>0,te=e=>{var p;if(y)return;let t=e?O.indexOf(e):Tn()?-1:O.findIndex(i=>!j.has(i));if(t<0||t>=O.length)return;let[n]=O.splice(t,1),r=_.getState().catalog[n];if(!r){ke(n,x(n)),te();return}let o=Date.now();G[n]=((p=G[n])!=null?p:0)+1,L(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Ge(r,{onProgress:i=>{let u=Math.floor(i*100);u!==s&&(s=u,L(n,{progress:u/100,version:r.version}))}});y={app_id:n,handle:a,forced:!!e},q("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{q("installed",n,r.version,`${Date.now()-o}ms`),L(n,{status:"installed",progress:1,version:r.version}),ke(n,i)}).catch(i=>{var M;if(i instanceof ae){if(Ce.has(n))return;q("paused",n),G[n]-=1,O.unshift(n),L(n,{status:j.has(n)?"paused":"queued",progress:0,version:r.version});return}let u=String((M=i==null?void 0:i.message)!=null?M:i);if(console.warn("[miniapp-queue] failed",n,u),G[n]<En){L(n,{status:"queued",progress:0,version:r.version,error:u}),setTimeout(()=>{var h;O.includes(n)||(y==null?void 0:y.app_id)===n||(O.push(n),te((h=se[n])!=null&&h.length?n:void 0))},Rn);return}L(n,{status:"failed",progress:0,version:r.version,error:u}),ke(n,x(n))}).finally(()=>{y=null;let i=O.find(u=>{var M;return(M=se[u])==null?void 0:M.length});te(i)})},Le=(e,{front:t=!1}={})=>{if((y==null?void 0:y.app_id)===e)return;let n=O.indexOf(e);if(n>=0){if(!t)return;O.splice(n,1)}t?O.unshift(e):O.push(e)},On=async e=>{let{host_id:t,client_token:n}=R(),r=new AbortController,o=setTimeout(()=>r.abort(),xn);try{let s=`${be}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(o)}},Ae=null,Ne=()=>(Ae!=null||(Ae=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(On)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(_.getState().catalog).filter(i=>!r[i]);R().storage.setString(Jt,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(o.map(i=>Kt(i,{by_user:!1}))),o.forEach(i=>ne.delete(i));let s=Object.keys(r).filter(i=>!ne.has(i)),a=[],p={};for(let i of s.map(u=>r[u])){if(await Qe(i)){L(i.app_id,{status:"installed",progress:1,version:i.version});continue}let u=x(i.app_id);if(qt(i.app_id)&&!De.has(i.app_id)&&u&&await Q(u)){L(i.app_id,{status:"installed",progress:1,version:u.version}),p[i.app_id]={app_id:i.app_id,current_version:u.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:p}),a.forEach(i=>{G[i.app_id]=0,L(i.app_id,{status:j.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Le(i.app_id)}),q("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),ee({type:"sync_complete",app_ids:s,removed:o}),Object.values(p).forEach(i=>ee({type:"update_available",...i})),te(),{ok:!0,app_ids:s,removed:o}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ee({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{Ae=null}})()),Ae),Kt=async(e,{by_user:t})=>{var o,s,a,p;if(t&&ne.add(e),Ce.has(e))return;Ce.add(e),j.delete(e);let n=O.indexOf(e);n>=0&&O.splice(n,1),(y==null?void 0:y.app_id)===e&&y.handle.cancel();let r=(p=(a=(o=_.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=x(e))==null?void 0:s.version)!=null?p:"";L(e,{status:"uninstalling",progress:0,version:r}),await Dt(e),Oe(e),_.setState(i=>{let u={...i.downloads};return delete u[e],{downloads:u}}),delete G[e],Ce.delete(e),ke(e,null),q("uninstalled",e,t?"(user)":"(not in list)"),ee({type:"uninstalled",app_id:e})},Yt=e=>Kt(e,{by_user:!0}),Qt=e=>{let t=pe(e);return t?(ne.delete(e),(y==null?void 0:y.app_id)===e||O.includes(e)||(G[e]=0,L(e,{status:j.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Le(e),te(),q("restore",e)),!0):!1},Gt=e=>{if(j.has(e))return;if(j.add(e),q("pause app",e),(y==null?void 0:y.app_id)===e&&!y.forced){y.handle.cancel();return}let t=_.getState().downloads[e];O.includes(e)&&t&&L(e,{status:"paused",progress:0,version:t.version})},Xt=e=>{if(!j.delete(e))return;q("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!O.includes(e)&&pe(e)&&(G[e]=0,Le(e)),O.includes(e)&&t&&L(e,{status:"queued",progress:0,version:t.version}),te()},Zt=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),q("pause",e),t.length===0&&ee({type:"pause_change",paused:!0,reasons:[e]}),y&&!y.forced&&y.handle.cancel())},en=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),q("resume",e),n.length===0&&ee({type:"pause_change",paused:!1,reasons:n}),te()},Ze=e=>_.getState().updates[e],tn=async e=>{var n,r;let t=Ze(e);De.add(e);try{let o=await we(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=pe(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(_.setState(a=>{var i;let p={...a.updates};return delete p[e],{updates:p,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),q("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{De.delete(e)}},nn=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!x(e.app_id),removed_by_user:ne.has(e.app_id)})),pe=e=>_.getState().catalog[e],we=async e=>{let t=pe(e);if(!t)return;if(j.delete(e),ne.delete(e),await Qe(t))return x(e);let n=x(e);if(qt(e)&&!De.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=se[e])!=null?s:se[e]=[]).push(o)});return(y==null?void 0:y.app_id)===e?y.forced=!0:(G[e]=0,Le(e,{front:!0}),y&&!y.forced?y.handle.cancel():te(e)),r};var E=require("react/jsx-runtime"),et=e=>(e!=null?e:"").replace(/\?[^#]*/,""),rn=0,Cn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},kn=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:p,opaque_background:i,allow_embedded_miniapps:u,onWebLoadEnd:M})=>{var st,at;let h=(0,d.useRef)(null),v=(0,d.useRef)(!1),A=z(F,c=>c.instances[e]),m=A==null?void 0:A.app.app_id,C=A==null?void 0:A.app.manifest_url,T=A==null?void 0:A.context,N=A==null?void 0:A.url_params,[l,k]=(0,d.useState)(()=>m?x(m):null),[le,X]=(0,d.useState)(!1),[Me,g]=(0,d.useState)(0),[S,U]=(0,d.useState)(0),[re,B]=(0,d.useState)(!1),H=(0,d.useRef)(null),nt=c=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,B(!0)},c)};(0,d.useEffect)(()=>()=>{H.current&&clearTimeout(H.current)},[]),(0,d.useEffect)(()=>{if(!m||!t&&l)return;let c=!0;return X(!1),(async()=>{let f=x(m),D=f?await Q(f):!1;if(!c||(k(D?J=>!J||J.version!==f.version||J.permissions.join(",")!==f.permissions.join(",")?f:J:null),__DEV__&&Date.now()-rn>1e4&&(rn=Date.now(),await Ne()),!c))return;let Z=await we(m),ie=Z!==void 0?Z:C?await Nt(m,C):x(m);if(c){if(!ie){X(!0);return}k(J=>J!=null?J:ie)}})(),()=>{c=!1}},[t,m,C,Me]),(0,d.useEffect)(()=>Bt(e,c=>h.current?(h.current.postMessage(c),!0):!1),[e]);let cn=z(_,c=>{let f=m?c.downloads[m]:void 0;return(f==null?void 0:f.status)==="installed"?f.version:void 0});(0,d.useEffect)(()=>{if(t||!m||!l)return;let c=x(m);if(!c||c.version===l.version)return;let f=!0;return Q(c).then(D=>{!f||!D||($(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),k(c))}),()=>{f=!1}},[t,m,cn,l==null?void 0:l.version]);let rt=z(_,c=>{var f;return m&&(f=c.apply_ticks[m])!=null?f:0});(0,d.useEffect)(()=>{if(!rt||!m)return;let c=x(m);if(!c||c.version===(l==null?void 0:l.version))return;let f=!0;return Q(c).then(D=>{!f||!D||($(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),B(!1),k(c))}),()=>{f=!1}},[rt]),(0,d.useEffect)(()=>{var D;let c=(D=R().keep_alive)==null?void 0:D.idle_close_ms;if(t||!c||c<=0)return;let f=setTimeout(()=>{Oe(e)},c);return()=>clearTimeout(f)},[t,e]),(0,d.useEffect)(()=>{o>0&&(X(!1),B(!1),U(c=>c+1),g(c=>c+1))},[o]);let it=(0,d.useRef)(t);(0,d.useEffect)(()=>{var c;it.current!==t&&(it.current=t,v.current&&((c=h.current)==null||c.injectJavaScript(_t(t?"resumed":"paused"))))},[t]);let ue=`${(st=l==null?void 0:l.version)!=null?st:"none"}:${(at=l==null?void 0:l.permissions.join(","))!=null?at:""}:${S}`,de=(0,d.useMemo)(()=>JSON.stringify([T!=null?T:{},N!=null?N:{}]),[T,N]),Be=(0,d.useMemo)(()=>{var c;return Tt(N!=null?N:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[de,l==null?void 0:l.permissions]),pn=(0,d.useMemo)(()=>Rt(T!=null?T:{},Be)+bt()+(R().debug?St():""),[Be]),ye=(0,d.useRef)(null),ot=(0,d.useRef)(null);(0,d.useEffect)(()=>{var f,D,Z;if(!l)return;if(ot.current!==ue){ot.current=ue,ye.current=de;return}if(ye.current===de)return;let c=((D=JSON.parse((f=ye.current)!=null?f:"[]")[0])!=null?D:{}).org_id;if(ye.current=de,c===(T==null?void 0:T.org_id)&&v.current){B(!1),nt(1500),(Z=h.current)==null||Z.injectJavaScript(xt(T!=null?T:{},Be));return}B(!1),U(ie=>ie+1)},[de,l,ue]),(0,d.useEffect)(()=>(t||W(e),()=>W(e)),[t,e,ue,o]),(0,d.useEffect)(()=>{let c=b.AppState.addEventListener("change",f=>{f==="background"&&W(e)});return()=>c.remove()},[e]);let ln=(0,d.useCallback)(async c=>{var D,Z,ie,J,$e;let f=wt(c.nativeEvent.data);if(!f){if(m&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(c.nativeEvent.data,{app_id:m,instance_id:e})).catch(P=>{console.warn("[miniapp] onWebEvent l\u1ED7i",m,P)})}catch(P){console.warn("[miniapp] onWebEvent l\u1ED7i",m,P)}return}if(f.method==="log"){let{level:P,text:I}=f;$(`web:${e}`,P!=null?P:"log",I!=null?I:"");return}if(f.method==="pong"){H.current||B(!0);return}if(f.method==="touchAtTop"){s.emit(!!f.at_top);return}if(f.method==="contextApplied"){H.current&&clearTimeout(H.current),H.current=null,B(!0);return}if(f.method==="ready"){v.current=!0,B(!0);let P=(D=F.getState().instances[e])==null?void 0:D.context;P&&((Z=h.current)==null||Z.injectJavaScript(je(P)));return}try{let P=await Ot(f,{getHostData:()=>{var I,K;return(K=(I=F.getState().instances[e])==null?void 0:I.host_data)!=null?K:{}},getPermissions:()=>{var I,K;return m?(K=(I=x(m))==null?void 0:I.permissions)!=null?K:[]:[]},is_dark:r,close:ce,app_id:m!=null?m:"",instance_id:e,options:p,emit:(I,K)=>{var ct;(ct=h.current)==null||ct.injectJavaScript(vt(I,K))},isActive:()=>F.getState().active_key===e&&b.AppState.currentState!=="background"});f.id&&((ie=h.current)==null||ie.injectJavaScript(Mt(f.id,P)))}catch(P){if(!f.id)return;let I=P==null?void 0:P.code,K=P instanceof w?P:new w(typeof I=="string"?I:"HOST_ERROR",String((J=P==null?void 0:P.message)!=null?J:P));($e=h.current)==null||$e.injectJavaScript(yt(f.id,K))}},[e,r,m,s,p]),un=(0,d.useCallback)(()=>{X(!1),U(c=>c+1),g(c=>c+1)},[]);return(0,E.jsxs)(b.View,{style:[b.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&V.behind],pointerEvents:t?"auto":"none",children:[l?(0,E.jsx)(sn.default,{ref:h,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${u?ze():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:pn,onMessage:ln,bounces:!1,overScrollMode:"never",onLoadStart:c=>{W(e),$(`webview:${e}`,"load start",et(c.nativeEvent.url)),v.current=!1,B(!1)},onError:c=>{W(e),$(`webview:${e}`,"load error",et(c.nativeEvent.url),c.nativeEvent.description),X(!0),B(!1)},onLoadEnd:c=>{let f=c.nativeEvent.url;$(`webview:${e}`,"load end",et(f)),m&&(M==null||M({app_id:m,instance_id:e,url:f})),nt(1500)},onContentProcessDidTerminate:()=>{W(e),v.current=!1,B(!1),U(c=>c+1)},onRenderProcessGone:()=>(W(e),v.current=!1,B(!1),U(c=>c+1),!0),style:V.webview},ue):null,A&&(0,E.jsx)(In,{visible:!l||!re,interactive:le,children:(0,E.jsx)(Dn,{splash:a,app:A.app,is_dark:r,error:le,has_bundle:!!l,retry:un})})]})}),Dn=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,p=Ie(t.app_id),i=r?"error":!o&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,E.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?p==null?void 0:p.progress:void 0,retry:s})}),In=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new b.Animated.Value(e?1:0)).current,[o,s]=(0,d.useState)(e);return(0,d.useEffect)(()=>{if(e){s(!0),r.setValue(1);return}let a=b.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:p})=>{p&&s(!1)}),()=>a.stop()},[e,r]),o?(0,E.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},tt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,E.jsxs)(b.View,{style:[V.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,E.jsx)(b.View,{style:[V.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,E.jsx)(b.Image,{source:{uri:e.icon},style:V.splash_icon_image}):(0,E.jsx)(b.Text,{style:V.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,E.jsx)(b.Text,{style:[V.splash_name,{color:s}],children:e.name}),n==="error"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.Text,{style:V.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,E.jsx)(b.TouchableOpacity,{activeOpacity:.7,style:[V.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,E.jsx)(b.Text,{style:[V.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.ActivityIndicator,{style:V.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,E.jsxs)(b.Text,{style:V.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},on=(e,t)=>{let n=(0,d.useRef)(t),r=(0,d.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Ln=({container:e,splash:t=tt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:p})=>{on("container",e),on("splash",t);let i=e,u=z(F,l=>l.active_key),M=(0,d.useRef)(u);u&&(M.current=u);let h=z(F,l=>Object.keys(l.instances).join("|")),v=z(F,l=>{var k;return l.active_key?(k=l.instances[l.active_key])==null?void 0:k.app.name:void 0}),A=(0,d.useMemo)(()=>h?h.split("|"):[],[h]),[m,C]=(0,d.useState)({}),T=(0,d.useRef)(Cn()).current;(0,d.useEffect)(()=>{if(!u||!o)return;let l=b.BackHandler.addEventListener("hardwareBackPress",()=>(ce(),!0));return()=>l.remove()},[u,o]);let N=(0,d.useCallback)(()=>{let l=F.getState().active_key;l&&C(k=>({...k,[l]:(k[l]||0)+1}))},[]);return A.length?(0,E.jsx)(i,{visible:!!u,title:v!=null?v:"",is_dark:n,close:ce,reload:N,subscribeWebAtTop:T.subscribe,children:A.map(l=>(0,E.jsx)(kn,{instance_key:l,is_active:u===l,is_front:(u!=null?u:M.current)===l,is_dark:n,reload_tick:m[l]||0,web_at_top:T,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:p},l))}):null},V=b.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),an=d.default.memo(Ln);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
|
|
45
|
+
true;`},Ct={partner:"partner_token",chatbox:"chatbox_token"},It=(e,t)=>{let n={...e};for(let r of Object.values(Ct))t.includes(r)||delete n[r];return n},He=new Set,Ee=async(e,t)=>{if(He.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);He.add(e);try{return await t()}finally{He.delete(e)}},Sn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Re=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Lt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:c,options:i,emit:p,isActive:y})=>{var w,C,T,N,u,I,ue,Z,ve;let d=i==null?void 0:i.handlers,M={app_id:a,instance_id:c,close:s},A=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=mt(t);return Ee(e,()=>At(h,y))}case"speech.start":{if(!p)throw A();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new g("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);h[S]=t[S]}return yt(c,h,p,y)}case"speech.stop":return Mt(c);case"getBiometricAvailability":return((w=i==null?void 0:i.biometrics)!=null?w:await Je()).getAvailability();case"authenticateBiometric":{let h=Re(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return Ee(e,async()=>{var ie;return((ie=i==null?void 0:i.biometrics)!=null?ie:await Je()).authenticate({reason:h,cancelButtonText:S})})}case"requestPayment":{let h=d==null?void 0:d.requestPayment;if(!h)throw A();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let U={...t,amount:S,currency:Re(t==null?void 0:t.currency,"currency")};return Ee(e,()=>h(U,M))}case"printImage":{let h=d==null?void 0:d.printImage;if(!h)throw A();let S=Re(t==null?void 0:t.image,"image");await Ee(e,()=>h({image:S},M));return}case"openScreen":if(!(d!=null&&d.openScreen))throw A();await d.openScreen({screen:Re(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},M);return;case"closeApp":s();return;case"openWebview":{let h=String((C=t==null?void 0:t.url)!=null?C:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h));return}case"openLink":{let h=String((T=t==null?void 0:t.url)!=null?T:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h))}catch(S){throw new g("NOT_SUPPORTED",String((u=(N=S==null?void 0:S.message)!=null?N:S)!=null?u:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(ue=i==null?void 0:i.showToast)==null||ue.call(i,String((I=t==null?void 0:t.message)!=null?I:""));return;case"haptic":{let h=Sn.has(t==null?void 0:t.type)?t.type:"selection";(Z=i==null?void 0:i.haptic)==null||Z.call(i,h);return}case"getSystemInfo":return{platform:he.Platform.OS==="ios"?"ios":"android",appVersion:(ve=i==null?void 0:i.app_version)!=null?ve:"",theme:o?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let ie=n().access_token;if(!ie)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return ie}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let S=Ct[h];if(!r().includes(S))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let U=h==="partner"?n().partner_token:n().chatbox_token;if(!U)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return U}case"getUserInfo":{let h=n().user;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ze=e=>`bundle:${e}`,Ke=()=>`${R().file_system.document_dir}/miniapps`,Ye=Ke,Ge=(e,t,n="index.html",r=!1,o=[])=>{let s=`${Ye()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},We=e=>{var t;R().storage.setString(ze(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},bn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,x=e=>{let t=R().storage.getString(ze(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return Ge(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>R().file_system.exists(e.entry_uri.replace("file://","")),Qe=async e=>{let t=x(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},Dt=async(e,t)=>{let n=R().file_system,r=`${Ye()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},Nt=async e=>{var t;await((t=we[e])==null?void 0:t.catch(()=>{})),R().storage.setString(ze(e),""),await R().file_system.remove(`${Ye()}/${e}`).catch(()=>{})},ce=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},we={},Bt=(e,t)=>{var s;let r=((s=we[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return we[e]=o,o.then(()=>{we[e]===o&&delete we[e]}),r},_n=(e,t)=>{var o,s;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let c=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(c)return c}return 0},$t=({manifest:e,zip_path:t})=>Bt(e.app_id,async()=>{var s;let n=R().file_system,r=x(e.app_id);if(r&&_n(r.version,e.version)>=0&&await Q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=Ge(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),We(e),$("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Dt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Xe=(e,{base_url:t,onProgress:n}={})=>{let r=R().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(s)throw new ce},i=async()=>{var d;c();let p=x(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return We(e),x(e.app_id);c();let y=r.download({url:t?bn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(M,A)=>{var C;let w=A>0?A:(C=e.size)!=null?C:0;w>0&&(n==null||n(Math.min(1,M/w)))}});o=y;try{let{status:M}=await y.promise;if(c(),M!==200)throw new Error(`bundle ${M}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else $("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let A=Ge(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),We(e),Dt(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),A}catch(M){throw s?new ce:M}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Bt(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},Ae={},xn=__DEV__?0:60*1e3,kt={},Vt=(e,t)=>{var r,o;let n=x(e);return n&&Date.now()-((r=kt[t])!=null?r:0)<xn?Promise.resolve(n):((o=Ae[e])!=null||(Ae[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),c=await Xe(a,{base_url:t}).promise;return kt[t]=Date.now(),c})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),x(e))).finally(()=>{Ae[e]=void 0})),Ae[e])};var Te=new Map,Ft=(e,t)=>(Te.set(e,t),()=>{Te.get(e)===t&&Te.delete(e)}),Ut=(e,t)=>{let n=Te.get(e);return n?n(t):!1};var Oe=require("react"),Ce=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},K=(e,t,n=Object.is)=>{let r=(0,Oe.useRef)(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let c=t(s),i=a&&n(a.value,c)?a.value:c;return r.current={state:s,selector:t,value:i},i};return(0,Oe.useSyncExternalStore)(e.subscribe,o)};var V=Ce({active_key:null,instances:{}}),Jt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var c;let a=(c=R().keep_alive)==null?void 0:c.max_webviews;V.setState(i=>{let p=t!=null?t:e.app_id,y={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},d=Object.keys(y);return a&&a>0&&d.length>a&&d.filter(M=>M!==p).sort((M,A)=>y[M].last_used_at-y[A].last_used_at).slice(0,d.length-a).forEach(M=>{delete y[M]}),s?{active_key:p,instances:y}:{instances:y}})},qt=e=>Jt(e,!0),Ht=e=>Jt(e,!1),pe=()=>V.setState({active_key:null}),Ie=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var jt="catalog",En="paused_apps",Rn="removed_apps",Pn=10*1e3,Tn=2,On=3e3,Cn=()=>{var e;try{return JSON.parse((e=R().storage.getString(jt))!=null?e:"{}")}catch{return{}}},_=Ce({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Wt=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},De=new Set,zt=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let o=JSON.parse((r=R().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},H=zt(En),re=zt(Rn);gt(()=>{H.load(),re.load();let e=Cn(),t={};Object.keys(e).filter(n=>!re.has(n)).forEach(n=>{let r=x(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var Ne=e=>K(_,t=>e?t.downloads[e]:void 0),Kt=()=>K(_,e=>e.pause_reasons.length>0),q=(...e)=>$("queue",...e),O=[],X={},v=null,Le=new Set,ae={},Ze=new Set,te=e=>{Ze.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Yt=e=>(Ze.add(e),()=>{Ze.delete(e)}),Gt=()=>_.getState().downloads,D=(e,t)=>{let n=!!x(e),r=_.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?te({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&te({type:"progress",app_id:e,progress:s.progress,version:s.version})},ke=(e,t)=>{var n;(n=ae[e])==null||n.forEach(r=>r(t)),delete ae[e]},In=()=>_.getState().pause_reasons.length>0,ne=e=>{var c;if(v)return;let t=e?O.indexOf(e):In()?-1:O.findIndex(i=>!H.has(i));if(t<0||t>=O.length)return;let[n]=O.splice(t,1),r=_.getState().catalog[n];if(!r){ke(n,x(n)),ne();return}let o=Date.now();X[n]=((c=X[n])!=null?c:0)+1,D(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Xe(r,{onProgress:i=>{let p=Math.floor(i*100);p!==s&&(s=p,D(n,{progress:p/100,version:r.version}))}});v={app_id:n,handle:a,forced:!!e},q("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{q("installed",n,r.version,`${Date.now()-o}ms`),D(n,{status:"installed",progress:1,version:r.version}),ke(n,i)}).catch(i=>{var y;if(i instanceof ce){if(Le.has(n))return;q("paused",n),X[n]-=1,O.unshift(n),D(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((y=i==null?void 0:i.message)!=null?y:i);if(console.warn("[miniapp-queue] failed",n,p),X[n]<Tn){D(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var d;O.includes(n)||(v==null?void 0:v.app_id)===n||(O.push(n),ne((d=ae[n])!=null&&d.length?n:void 0))},On);return}D(n,{status:"failed",progress:0,version:r.version,error:p}),ke(n,x(n))}).finally(()=>{v=null;let i=O.find(p=>{var y;return(y=ae[p])==null?void 0:y.length});ne(i)})},Be=(e,{front:t=!1}={})=>{if((v==null?void 0:v.app_id)===e)return;let n=O.indexOf(e);if(n>=0){if(!t)return;O.splice(n,1)}t?O.unshift(e):O.push(e)},Ln=async e=>{let{host_id:t,client_token:n}=R(),r=new AbortController,o=setTimeout(()=>r.abort(),Pn);try{let s=`${_e}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(o)}},ye=null,$e=()=>(ye!=null||(ye=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(Ln)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(_.getState().catalog).filter(i=>!r[i]);R().storage.setString(jt,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(o.map(i=>Qt(i,{by_user:!1}))),o.forEach(i=>re.delete(i));let s=Object.keys(r).filter(i=>!re.has(i)),a=[],c={};for(let i of s.map(p=>r[p])){if(await Qe(i)){D(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=x(i.app_id);if(Wt(i.app_id)&&!De.has(i.app_id)&&p&&await Q(p)){D(i.app_id,{status:"installed",progress:1,version:p.version}),c[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:c}),a.forEach(i=>{X[i.app_id]=0,D(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Be(i.app_id)}),q("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),te({type:"sync_complete",app_ids:s,removed:o}),Object.values(c).forEach(i=>te({type:"update_available",...i})),ne(),{ok:!0,app_ids:s,removed:o}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),te({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ye=null}})()),ye),Qt=async(e,{by_user:t})=>{var o,s,a,c;if(t&&re.add(e),Le.has(e))return;Le.add(e),H.delete(e);let n=O.indexOf(e);n>=0&&O.splice(n,1),(v==null?void 0:v.app_id)===e&&v.handle.cancel();let r=(c=(a=(o=_.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=x(e))==null?void 0:s.version)!=null?c:"";D(e,{status:"uninstalling",progress:0,version:r}),await Nt(e),Ie(e),_.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete X[e],Le.delete(e),ke(e,null),q("uninstalled",e,t?"(user)":"(not in list)"),te({type:"uninstalled",app_id:e})},Xt=e=>Qt(e,{by_user:!0}),Zt=e=>{let t=le(e);return t?(re.delete(e),(v==null?void 0:v.app_id)===e||O.includes(e)||(X[e]=0,D(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Be(e),ne(),q("restore",e)),!0):!1},en=e=>{if(H.has(e))return;if(H.add(e),q("pause app",e),(v==null?void 0:v.app_id)===e&&!v.forced){v.handle.cancel();return}let t=_.getState().downloads[e];O.includes(e)&&t&&D(e,{status:"paused",progress:0,version:t.version})},tn=e=>{if(!H.delete(e))return;q("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!O.includes(e)&&le(e)&&(X[e]=0,Be(e)),O.includes(e)&&t&&D(e,{status:"queued",progress:0,version:t.version}),ne()},nn=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),q("pause",e),t.length===0&&te({type:"pause_change",paused:!0,reasons:[e]}),v&&!v.forced&&v.handle.cancel())},rn=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),q("resume",e),n.length===0&&te({type:"pause_change",paused:!1,reasons:n}),ne()},et=e=>_.getState().updates[e],on=async e=>{var n,r;let t=et(e);De.add(e);try{let o=await Me(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=le(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(_.setState(a=>{var i;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),q("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{De.delete(e)}},sn=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!x(e.app_id),removed_by_user:re.has(e.app_id)})),le=e=>_.getState().catalog[e],Me=async e=>{let t=le(e);if(!t)return;if(H.delete(e),re.delete(e),await Qe(t))return x(e);let n=x(e);if(Wt(e)&&!De.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=ae[e])!=null?s:ae[e]=[]).push(o)});return(v==null?void 0:v.app_id)===e?v.forced=!0:(X[e]=0,Be(e,{front:!0}),v&&!v.forced?v.handle.cancel():ne(e)),r};var E=require("react/jsx-runtime"),tt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),an=0,kn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Dn=f.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:c,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:y})=>{var at,ct;let d=(0,f.useRef)(null),M=(0,f.useRef)(!1),A=K(V,l=>l.instances[e]),w=A==null?void 0:A.app.app_id,C=A==null?void 0:A.app.manifest_url,T=A==null?void 0:A.context,N=A==null?void 0:A.url_params,[u,I]=(0,f.useState)(()=>w?x(w):null),[ue,Z]=(0,f.useState)(!1),[ve,h]=(0,f.useState)(0),[S,U]=(0,f.useState)(0),[ie,B]=(0,f.useState)(!1),j=(0,f.useRef)(null),rt=l=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,B(!0)},l)};(0,f.useEffect)(()=>()=>{j.current&&clearTimeout(j.current)},[]),(0,f.useEffect)(()=>{if(!w||!t&&u)return;let l=!0;return Z(!1),(async()=>{let m=x(w),L=m?await Q(m):!1;if(!l||(I(L?J=>!J||J.version!==m.version||J.permissions.join(",")!==m.permissions.join(",")?m:J:null),__DEV__&&Date.now()-an>1e4&&(an=Date.now(),await $e()),!l))return;let ee=await Me(w),oe=ee!==void 0?ee:C?await Vt(w,C):x(w);if(l){if(!oe){Z(!0);return}I(J=>J!=null?J:oe)}})(),()=>{l=!1}},[t,w,C,ve]),(0,f.useEffect)(()=>Ft(e,l=>d.current?(d.current.postMessage(l),!0):!1),[e]);let un=K(_,l=>{let m=w?l.downloads[w]:void 0;return(m==null?void 0:m.status)==="installed"?m.version:void 0});(0,f.useEffect)(()=>{if(t||!w||!u)return;let l=x(w);if(!l||l.version===u.version)return;let m=!0;return Q(l).then(L=>{!m||!L||($(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",u.version,"\u2192",l.version),I(l))}),()=>{m=!1}},[t,w,un,u==null?void 0:u.version]);let it=K(_,l=>{var m;return w&&(m=l.apply_ticks[w])!=null?m:0});(0,f.useEffect)(()=>{if(!it||!w)return;let l=x(w);if(!l||l.version===(u==null?void 0:u.version))return;let m=!0;return Q(l).then(L=>{!m||!L||($(`webview:${e}`,"c\u1EADp nh\u1EADt",u==null?void 0:u.version,"\u2192",l.version),B(!1),I(l))}),()=>{m=!1}},[it]),(0,f.useEffect)(()=>{var L;let l=(L=R().keep_alive)==null?void 0:L.idle_close_ms;if(t||!l||l<=0)return;let m=setTimeout(()=>{Ie(e)},l);return()=>clearTimeout(m)},[t,e]),(0,f.useEffect)(()=>{o>0&&(Z(!1),B(!1),U(l=>l+1),h(l=>l+1))},[o]);let ot=(0,f.useRef)(t);(0,f.useEffect)(()=>{var l;ot.current!==t&&(ot.current=t,M.current&&((l=d.current)==null||l.injectJavaScript(Rt(t?"resumed":"paused"))))},[t]);let de=`${(at=u==null?void 0:u.version)!=null?at:"none"}:${(ct=u==null?void 0:u.permissions.join(","))!=null?ct:""}:${S}`,ge=(0,f.useMemo)(()=>JSON.stringify([T!=null?T:{},N!=null?N:{}]),[T,N]),Ve=(0,f.useMemo)(()=>{var l;return It(N!=null?N:{},(l=u==null?void 0:u.permissions)!=null?l:[])},[ge,u==null?void 0:u.permissions]),dn=(0,f.useMemo)(()=>Ot(T!=null?T:{},Ve)+Et()+(R().debug?xt():""),[Ve]),Se=(0,f.useRef)(null),st=(0,f.useRef)(null);(0,f.useEffect)(()=>{var m,L,ee;if(!u)return;if(st.current!==de){st.current=de,Se.current=ge;return}if(Se.current===ge)return;let l=((L=JSON.parse((m=Se.current)!=null?m:"[]")[0])!=null?L:{}).org_id;if(Se.current=ge,l===(T==null?void 0:T.org_id)&&M.current){B(!1),rt(1500),(ee=d.current)==null||ee.injectJavaScript(Pt(T!=null?T:{},Ve));return}B(!1),U(oe=>oe+1)},[ge,u,de]),(0,f.useEffect)(()=>(t||z(e),()=>z(e)),[t,e,de,o]),(0,f.useEffect)(()=>{let l=b.AppState.addEventListener("change",m=>{m==="background"&&z(e)});return()=>l.remove()},[e]);let gn=(0,f.useCallback)(async l=>{var L,ee,oe,J,Fe;let m=vt(l.nativeEvent.data);if(!m){if(w&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(l.nativeEvent.data,{app_id:w,instance_id:e})).catch(P=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,P)})}catch(P){console.warn("[miniapp] onWebEvent l\u1ED7i",w,P)}return}if(m.method==="log"){let{level:P,text:k}=m;$(`web:${e}`,P!=null?P:"log",k!=null?k:"");return}if(m.method==="pong"){j.current||B(!0);return}if(m.method==="touchAtTop"){s.emit(!!m.at_top);return}if(m.method==="contextApplied"){j.current&&clearTimeout(j.current),j.current=null,B(!0);return}if(m.method==="ready"){M.current=!0,B(!0);let P=(L=V.getState().instances[e])==null?void 0:L.context;P&&((ee=d.current)==null||ee.injectJavaScript(je(P)));return}try{let P=await Lt(m,{getHostData:()=>{var k,Y;return(Y=(k=V.getState().instances[e])==null?void 0:k.host_data)!=null?Y:{}},getPermissions:()=>{var k,Y;return w?(Y=(k=x(w))==null?void 0:k.permissions)!=null?Y:[]:[]},is_dark:r,close:pe,app_id:w!=null?w:"",instance_id:e,options:c,emit:(k,Y)=>{var pt;(pt=d.current)==null||pt.injectJavaScript(_t(k,Y))},isActive:()=>V.getState().active_key===e&&b.AppState.currentState!=="background"});m.id&&((oe=d.current)==null||oe.injectJavaScript(St(m.id,P)))}catch(P){if(!m.id)return;let k=P==null?void 0:P.code,Y=P instanceof g?P:new g(typeof k=="string"?k:"HOST_ERROR",String((J=P==null?void 0:P.message)!=null?J:P));(Fe=d.current)==null||Fe.injectJavaScript(bt(m.id,Y))}},[e,r,w,s,c]),fn=(0,f.useCallback)(()=>{Z(!1),U(l=>l+1),h(l=>l+1)},[]);return(0,E.jsxs)(b.View,{style:[b.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&F.behind],pointerEvents:t?"auto":"none",children:[u?(0,E.jsx)(pn.default,{ref:d,source:{uri:u.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?Ke():u.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:dn,onMessage:gn,bounces:!1,overScrollMode:"never",onLoadStart:l=>{z(e),$(`webview:${e}`,"load start",tt(l.nativeEvent.url)),M.current=!1,B(!1)},onError:l=>{z(e),$(`webview:${e}`,"load error",tt(l.nativeEvent.url),l.nativeEvent.description),Z(!0),B(!1)},onLoadEnd:l=>{let m=l.nativeEvent.url;$(`webview:${e}`,"load end",tt(m)),w&&(y==null||y({app_id:w,instance_id:e,url:m})),rt(1500)},onContentProcessDidTerminate:()=>{z(e),M.current=!1,B(!1),U(l=>l+1)},onRenderProcessGone:()=>(z(e),M.current=!1,B(!1),U(l=>l+1),!0),style:F.webview},de):null,A&&(0,E.jsx)(Bn,{visible:!u||!ie,interactive:ue,children:(0,E.jsx)(Nn,{splash:a,app:A.app,is_dark:r,error:ue,has_bundle:!!u,retry:fn})})]})}),Nn=f.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,c=Ne(t.app_id),i=r?"error":!o&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return(0,E.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?c==null?void 0:c.progress:void 0,retry:s})}),Bn=({visible:e,interactive:t,children:n})=>{let r=(0,f.useRef)(new b.Animated.Value(e?1:0)).current,[o,s]=(0,f.useState)(e);return(0,f.useEffect)(()=>{if(e){s(!0),r.setValue(1);return}let a=b.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&s(!1)}),()=>a.stop()},[e,r]),o?(0,E.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},nt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,E.jsxs)(b.View,{style:[F.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,E.jsx)(b.View,{style:[F.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,E.jsx)(b.Image,{source:{uri:e.icon},style:F.splash_icon_image}):(0,E.jsx)(b.Text,{style:F.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,E.jsx)(b.Text,{style:[F.splash_name,{color:s}],children:e.name}),n==="error"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.Text,{style:F.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,E.jsx)(b.TouchableOpacity,{activeOpacity:.7,style:[F.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,E.jsx)(b.Text,{style:[F.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.ActivityIndicator,{style:F.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,E.jsxs)(b.Text,{style:F.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},cn=(e,t)=>{let n=(0,f.useRef)(t),r=(0,f.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},$n=({container:e,splash:t=nt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{cn("container",e),cn("splash",t);let i=e,p=K(V,u=>u.active_key),y=(0,f.useRef)(p);p&&(y.current=p);let d=K(V,u=>Object.keys(u.instances).join("|")),M=K(V,u=>{var I;return u.active_key?(I=u.instances[u.active_key])==null?void 0:I.app.name:void 0}),A=(0,f.useMemo)(()=>d?d.split("|"):[],[d]),[w,C]=(0,f.useState)({}),T=(0,f.useRef)(kn()).current;(0,f.useEffect)(()=>{if(!p||!o)return;let u=b.BackHandler.addEventListener("hardwareBackPress",()=>(pe(),!0));return()=>u.remove()},[p,o]);let N=(0,f.useCallback)(()=>{let u=V.getState().active_key;u&&C(I=>({...I,[u]:(I[u]||0)+1}))},[]);return A.length?(0,E.jsx)(i,{visible:!!p,title:M!=null?M:"",is_dark:n,close:pe,reload:N,subscribeWebAtTop:T.subscribe,children:A.map(u=>(0,E.jsx)(Dn,{instance_key:u,is_active:p===u,is_front:(p!=null?p:y.current)===u,is_dark:n,reload_tick:w[u]||0,web_at_top:T,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:c},u))}):null},F=b.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),ln=f.default.memo($n);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var $e="https://retion-miniapp-platform.vercel.app",oe=null,dt=new Set,en=e=>{oe=e,dt.forEach(t=>t())},_=()=>{if(!oe)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return oe},gt=e=>{dt.add(e),oe&&e()},B=(...e)=>{oe!=null&&oe.debug&&console.log("[miniapp]",...e)};var tn=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:o})=>{let{jobId:s,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:i})=>o==null?void 0:o(c,i)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(s)}}}),nn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import rt,{useCallback as tt,useEffect as k,useMemo as De,useRef as H,useState as ce}from"react";import{AppState as jt,ActivityIndicator as Nn,Animated as Ze,BackHandler as Bn,Image as $n,StyleSheet as it,Text as ye,TouchableOpacity as Vn,View as nt}from"react-native";import Fn from"react-native-webview";import{Linking as yt,Platform as sn}from"react-native";var ft=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),be,Ve=()=>(be||(be=import("react-native-biometrics").then(({default:e})=>ft(new e({allowDeviceCredentials:!1}))).catch(e=>{throw be=void 0,new f("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),be);import{PermissionsAndroid as se,Platform as rn}from"react-native";var ht=e=>{var n,r,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new f("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new f("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[s,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let i=t[s];if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||i<a||i>c))throw new f("INVALID_PARAMS",`${s} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},mt=(e,t=()=>!0)=>new Promise((n,r)=>{let o=!1,s=(i,p)=>{o||(o=!0,clearTimeout(a),i?r(i):n(p))},a=setTimeout(()=>s(new f("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>o?!1:t()?!0:(s(new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let i;try{i=(await import("@react-native-community/geolocation")).default}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(rn.OS==="android"){let p=se.PERMISSIONS.ACCESS_FINE_LOCATION,w=se.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await se.check(p);if(!c())return;let y=d||await se.check(w);if(!c())return;if(!d&&!y){let m=await se.requestMultiple([p,w]);if(!c())return;if(m[p]!==se.RESULTS.GRANTED&&m[w]!==se.RESULTS.GRANTED)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&i.getCurrentPosition(p=>{c()&&s(void 0,p)},p=>{var d;if(!c())return;let w=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[p.code])!=null?d:"LOCATION_ERROR";s(new f(w,p.message))},e)}})().catch(i=>s(i))});import{Platform as on}from"react-native";var K,Fe=e=>{var t;if(K===e&&(K=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&on.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},At=async(e,t,n,r=()=>!0)=>{var s,a,c,i,p;if(K)throw new f("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};K=o;try{let w;try{w=await import("expo-speech-recognition")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=w.ExpoSpeechRecognitionModule;if(o.native=d,o.cancelled||!r())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let y=await d.requestPermissionsAsync();if(o.cancelled||!r())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new f("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!r())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(d.addListener("result",m=>{var A,T;K!==o||o.cancelled||n(m.isFinal?"speech.final":"speech.partial",{...m,text:(T=(A=m.results[0])==null?void 0:A.transcript)!=null?T:""})}),d.addListener("error",m=>{K===o&&!o.cancelled&&n("speech.error",{...m,code:m.error})}),d.addListener("end",()=>{K===o&&(Fe(o),n("speech.end"))})),o.started=!0,d.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(i=t.addsPunctuation)!=null?i:!0,requiresOnDeviceRecognition:(p=t.requiresOnDeviceRecognition)!=null?p:!1,iosCategory:{category:w.AVAudioSessionCategory.playAndRecord,categoryOptions:[w.AVAudioSessionCategoryOptions.defaultToSpeaker,w.AVAudioSessionCategoryOptions.allowBluetooth],mode:w.AVAudioSessionMode.measurement}})}catch(w){throw Fe(o),w}},wt=e=>{let t=K;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Y=e=>{let t=K;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Fe(t)}};var Ee=1,f=class extends Error{constructor(n,r){super(r);this.code=n}},Mt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ee&&typeof t.method=="string"?t:null}catch{return null}},ge=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,vt=(e,t)=>ge({id:e,result:t}),St=(e,t)=>ge({id:e,error:{code:t.code,message:t.message}}),bt=(e,t)=>ge({event:e,data:t}),Je=e=>ge({event:"context",data:e});var _t=()=>`(function () {
|
|
2
2
|
var post = function (level, args) {
|
|
3
3
|
try {
|
|
4
4
|
var parts = [];
|
|
@@ -8,7 +8,7 @@ var Ne="https://retion-miniapp-platform.vercel.app",oe=null,ut=new Set,Gt=e=>{oe
|
|
|
8
8
|
else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
|
|
9
9
|
else { parts.push(String(a)); }
|
|
10
10
|
}
|
|
11
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
11
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ee}, method: 'log', level: level, text: parts.join(' ') }));
|
|
12
12
|
} catch (e) {}
|
|
13
13
|
};
|
|
14
14
|
['log', 'info', 'warn', 'error'].forEach(function (level) {
|
|
@@ -19,7 +19,7 @@ var Ne="https://retion-miniapp-platform.vercel.app",oe=null,ut=new Set,Gt=e=>{oe
|
|
|
19
19
|
window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
|
|
20
20
|
// Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
|
|
21
21
|
post('info', ['[page] ' + location.pathname + location.hash]);
|
|
22
|
-
})(); true;`,
|
|
22
|
+
})(); true;`,xt=()=>`(function () {
|
|
23
23
|
function atTop(el) {
|
|
24
24
|
for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
|
|
25
25
|
if (n.scrollTop > 0) { return false; }
|
|
@@ -30,7 +30,7 @@ var Ne="https://retion-miniapp-platform.vercel.app",oe=null,ut=new Set,Gt=e=>{oe
|
|
|
30
30
|
function report(at_top) {
|
|
31
31
|
if (at_top === last) { return; }
|
|
32
32
|
last = at_top;
|
|
33
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
33
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ee}, method: 'touchAtTop', at_top: at_top }));
|
|
34
34
|
}
|
|
35
35
|
document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
|
|
36
36
|
// Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
|
|
@@ -38,8 +38,8 @@ var Ne="https://retion-miniapp-platform.vercel.app",oe=null,ut=new Set,Gt=e=>{oe
|
|
|
38
38
|
var el = e.target === document ? document.documentElement : e.target;
|
|
39
39
|
if (el && el.scrollTop > 0) { report(false); }
|
|
40
40
|
}, { capture: true, passive: true });
|
|
41
|
-
})(); true;`,
|
|
42
|
-
${
|
|
41
|
+
})(); true;`,Et=e=>ge({event:e}),Rt=(e,t)=>{let n=Pt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
|
|
42
|
+
${Je(e)}`},Pt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Tt=(e,t={})=>{let n=Pt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ee} };
|
|
43
43
|
window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
|
|
44
44
|
${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
|
|
45
|
-
true;`},Rt={partner:"partner_token",chatbox:"chatbox_token"},Pt=(e,t)=>{let n={...e};for(let r of Object.values(Rt))t.includes(r)||delete n[r];return n},Fe=new Set,Ve=async(e,t)=>{if(Fe.has(e))throw new A("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Fe.add(e);try{return await t()}finally{Fe.delete(e)}},nn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),be=(e,t)=>{if(typeof e!="string"||!e)throw new A("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Tt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:p,options:i,emit:u,isActive:w})=>{var h,T,E,L,l,O,pe,X,ye;let f=i==null?void 0:i.handlers,y={app_id:a,instance_id:p,close:s},m=()=>new A("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"speech.start":{if(!u)throw m();let d={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new A("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");d.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new A("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);d[v]=t[v]}return ft(p,d,u,w)}case"speech.stop":return ht(p);case"getBiometricAvailability":return((h=i==null?void 0:i.biometrics)!=null?h:await Be()).getAvailability();case"authenticateBiometric":{let d=be(t==null?void 0:t.reason,"reason").trim();if(!d||d.length>200)throw new A("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new A("INVALID_PARAMS","Invalid cancelButtonText");return Ve(e,async()=>{var re;return((re=i==null?void 0:i.biometrics)!=null?re:await Be()).authenticate({reason:d,cancelButtonText:v})})}case"requestPayment":{let d=f==null?void 0:f.requestPayment;if(!d)throw m();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new A("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let V={...t,amount:v,currency:be(t==null?void 0:t.currency,"currency")};return Ve(e,()=>d(V,y))}case"printImage":{let d=f==null?void 0:f.printImage;if(!d)throw m();let v=be(t==null?void 0:t.image,"image");await Ve(e,()=>d({image:v},y));return}case"openScreen":if(!(f!=null&&f.openScreen))throw m();await f.openScreen({screen:be(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":s();return;case"openWebview":{let d=String((T=t==null?void 0:t.url)!=null?T:"");if(!/^https?:\/\//i.test(d))throw new A("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(d):mt.openURL(d));return}case"openLink":{let d=String((E=t==null?void 0:t.url)!=null?E:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(d)||/^(javascript|file|data|about|blob):/i.test(d))throw new A("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(d):mt.openURL(d))}catch(v){throw new A("NOT_SUPPORTED",String((l=(L=v==null?void 0:v.message)!=null?L:v)!=null?l:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(pe=i==null?void 0:i.showToast)==null||pe.call(i,String((O=t==null?void 0:t.message)!=null?O:""));return;case"haptic":{let d=nn.has(t==null?void 0:t.type)?t.type:"selection";(X=i==null?void 0:i.haptic)==null||X.call(i,d);return}case"getSystemInfo":return{platform:tn.OS==="ios"?"ios":"android",appVersion:(ye=i==null?void 0:i.app_version)!=null?ye:"",theme:o?"dark":"light"};case"getAccessToken":{let d=n().access_token;if(!d)throw new A("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return d}case"getToken":{let d=t==null?void 0:t.type;if(d==="access"){let re=n().access_token;if(!re)throw new A("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(d!=="partner"&&d!=="chatbox")throw new A("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(d)}`);let v=Rt[d];if(!r().includes(v))throw new A("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let V=d==="partner"?n().partner_token:n().chatbox_token;if(!V)throw new A("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return V}case"getUserInfo":{let d=n().user;if(!d)throw new A("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return d}case"getPageInfo":{let d=n().page;if(!d)throw new A("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return d}case"sendMessage":case"insertText":throw new A("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new A("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var qe=e=>`bundle:${e}`,je=()=>`${_().file_system.document_dir}/miniapps`,He=je,We=(e,t,n="index.html",r=!1,o=[])=>{let s=`${He()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},Je=e=>{var t;_().storage.setString(qe(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},rn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,b=e=>{let t=_().storage.getString(qe(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return We(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>_().file_system.exists(e.entry_uri.replace("file://","")),ze=async e=>{let t=b(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},Ct=async(e,t)=>{let n=_().file_system,r=`${He()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},kt=async e=>{var t;await((t=fe[e])==null?void 0:t.catch(()=>{})),_().storage.setString(qe(e),""),await _().file_system.remove(`${He()}/${e}`).catch(()=>{})},ce=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},fe={},Dt=(e,t)=>{var s;let r=((s=fe[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return fe[e]=o,o.then(()=>{fe[e]===o&&delete fe[e]}),r},on=(e,t)=>{var o,s;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let p=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(p)return p}return 0},sn=({manifest:e,zip_path:t})=>Dt(e.app_id,async()=>{var s;let n=_().file_system,r=b(e.app_id);if(r&&on(r.version,e.version)>=0&&await Q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=We(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),Je(e),B("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Ct(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Ke=(e,{base_url:t,onProgress:n}={})=>{let r=_().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(s)throw new ce},i=async()=>{var f;p();let u=b(e.app_id);if((u==null?void 0:u.version)===e.version&&await r.exists(u.dir))return Je(e),b(e.app_id);p();let w=r.download({url:t?rn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,m)=>{var T;let h=m>0?m:(T=e.size)!=null?T:0;h>0&&(n==null||n(Math.min(1,y/h)))}});o=w;try{let{status:y}=await w.promise;if(p(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else B("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let m=We(e.app_id,e.version,e.entry,!!e.context_update,(f=e.permissions)!=null?f:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),Je(e),Ct(e.app_id,[e.version,u==null?void 0:u.version].filter(Boolean)),m}catch(y){throw s?new ce:y}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Dt(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},ge={},an=__DEV__?0:60*1e3,Ot={},It=(e,t)=>{var r,o;let n=b(e);return n&&Date.now()-((r=Ot[t])!=null?r:0)<an?Promise.resolve(n):((o=ge[e])!=null||(ge[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),p=await Ke(a,{base_url:t}).promise;return Ot[t]=Date.now(),p})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),b(e))).finally(()=>{ge[e]=void 0})),ge[e])};var xe=new Map,Lt=(e,t)=>(xe.set(e,t),()=>{xe.get(e)===t&&xe.delete(e)}),cn=(e,t)=>{let n=xe.get(e);return n?n(t):!1};import{useRef as pn,useSyncExternalStore as ln}from"react";var Ee=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},W=(e,t,n=Object.is)=>{let r=pn(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let p=t(s),i=a&&n(a.value,p)?a.value:p;return r.current={state:s,selector:t,value:i},i};return ln(e.subscribe,o)};var $=Ee({active_key:null,instances:{}}),Nt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var p;let a=(p=_().keep_alive)==null?void 0:p.max_webviews;$.setState(i=>{let u=t!=null?t:e.app_id,w={...i.instances,[u]:{key:u,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},f=Object.keys(w);return a&&a>0&&f.length>a&&f.filter(y=>y!==u).sort((y,m)=>w[y].last_used_at-w[m].last_used_at).slice(0,f.length-a).forEach(y=>{delete w[y]}),s?{active_key:u,instances:w}:{instances:w}})},un=e=>Nt(e,!0),dn=e=>Nt(e,!1),he=()=>$.setState({active_key:null}),Re=e=>{$.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Bt="catalog",gn="paused_apps",fn="removed_apps",hn=10*1e3,mn=2,An=3e3,wn=()=>{var e;try{return JSON.parse((e=_().storage.getString(Bt))!=null?e:"{}")}catch{return{}}},S=Ee({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),$t=e=>{var t;return!!((t=_().manual_update)!=null&&t.includes(e))},Oe=new Set,Ft=e=>{let t=new Set,n=()=>_().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let o=JSON.parse((r=_().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},q=Ft(gn),ne=Ft(fn);dt(()=>{q.load(),ne.load();let e=wn(),t={};Object.keys(e).filter(n=>!ne.has(n)).forEach(n=>{let r=b(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:q.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),S.setState({catalog:e,downloads:t})});var Qe=e=>W(S,t=>e?t.downloads[e]:void 0),Mn=()=>W(S,e=>e.pause_reasons.length>0),J=(...e)=>B("queue",...e),R=[],G={},M=null,Pe=new Set,se={},Ye=new Set,ee=e=>{Ye.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},yn=e=>(Ye.add(e),()=>{Ye.delete(e)}),vn=()=>S.getState().downloads,D=(e,t)=>{let n=!!b(e),r=S.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};S.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?ee({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&ee({type:"progress",app_id:e,progress:s.progress,version:s.version})},Te=(e,t)=>{var n;(n=se[e])==null||n.forEach(r=>r(t)),delete se[e]},Sn=()=>S.getState().pause_reasons.length>0,te=e=>{var p;if(M)return;let t=e?R.indexOf(e):Sn()?-1:R.findIndex(i=>!q.has(i));if(t<0||t>=R.length)return;let[n]=R.splice(t,1),r=S.getState().catalog[n];if(!r){Te(n,b(n)),te();return}let o=Date.now();G[n]=((p=G[n])!=null?p:0)+1,D(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Ke(r,{onProgress:i=>{let u=Math.floor(i*100);u!==s&&(s=u,D(n,{progress:u/100,version:r.version}))}});M={app_id:n,handle:a,forced:!!e},J("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{J("installed",n,r.version,`${Date.now()-o}ms`),D(n,{status:"installed",progress:1,version:r.version}),Te(n,i)}).catch(i=>{var w;if(i instanceof ce){if(Pe.has(n))return;J("paused",n),G[n]-=1,R.unshift(n),D(n,{status:q.has(n)?"paused":"queued",progress:0,version:r.version});return}let u=String((w=i==null?void 0:i.message)!=null?w:i);if(console.warn("[miniapp-queue] failed",n,u),G[n]<mn){D(n,{status:"queued",progress:0,version:r.version,error:u}),setTimeout(()=>{var f;R.includes(n)||(M==null?void 0:M.app_id)===n||(R.push(n),te((f=se[n])!=null&&f.length?n:void 0))},An);return}D(n,{status:"failed",progress:0,version:r.version,error:u}),Te(n,b(n))}).finally(()=>{M=null;let i=R.find(u=>{var w;return(w=se[u])==null?void 0:w.length});te(i)})},Ce=(e,{front:t=!1}={})=>{if((M==null?void 0:M.app_id)===e)return;let n=R.indexOf(e);if(n>=0){if(!t)return;R.splice(n,1)}t?R.unshift(e):R.push(e)},bn=async e=>{let{host_id:t,client_token:n}=_(),r=new AbortController,o=setTimeout(()=>r.abort(),hn);try{let s=`${Ne}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(o)}},me=null,Ge=()=>(me!=null||(me=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(_().channels.map(bn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(S.getState().catalog).filter(i=>!r[i]);_().storage.setString(Bt,JSON.stringify(r)),S.setState({catalog:r}),await Promise.all(o.map(i=>Vt(i,{by_user:!1}))),o.forEach(i=>ne.delete(i));let s=Object.keys(r).filter(i=>!ne.has(i)),a=[],p={};for(let i of s.map(u=>r[u])){if(await ze(i)){D(i.app_id,{status:"installed",progress:1,version:i.version});continue}let u=b(i.app_id);if($t(i.app_id)&&!Oe.has(i.app_id)&&u&&await Q(u)){D(i.app_id,{status:"installed",progress:1,version:u.version}),p[i.app_id]={app_id:i.app_id,current_version:u.version,next_version:i.version};continue}a.push(i)}return S.setState({updates:p}),a.forEach(i=>{G[i.app_id]=0,D(i.app_id,{status:q.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ce(i.app_id)}),J("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),ee({type:"sync_complete",app_ids:s,removed:o}),Object.values(p).forEach(i=>ee({type:"update_available",...i})),te(),{ok:!0,app_ids:s,removed:o}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ee({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{me=null}})()),me),Vt=async(e,{by_user:t})=>{var o,s,a,p;if(t&&ne.add(e),Pe.has(e))return;Pe.add(e),q.delete(e);let n=R.indexOf(e);n>=0&&R.splice(n,1),(M==null?void 0:M.app_id)===e&&M.handle.cancel();let r=(p=(a=(o=S.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=b(e))==null?void 0:s.version)!=null?p:"";D(e,{status:"uninstalling",progress:0,version:r}),await kt(e),Re(e),S.setState(i=>{let u={...i.downloads};return delete u[e],{downloads:u}}),delete G[e],Pe.delete(e),Te(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),ee({type:"uninstalled",app_id:e})},_n=e=>Vt(e,{by_user:!0}),xn=e=>{let t=Ae(e);return t?(ne.delete(e),(M==null?void 0:M.app_id)===e||R.includes(e)||(G[e]=0,D(e,{status:q.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ce(e),te(),J("restore",e)),!0):!1},En=e=>{if(q.has(e))return;if(q.add(e),J("pause app",e),(M==null?void 0:M.app_id)===e&&!M.forced){M.handle.cancel();return}let t=S.getState().downloads[e];R.includes(e)&&t&&D(e,{status:"paused",progress:0,version:t.version})},Rn=e=>{if(!q.delete(e))return;J("resume app",e);let t=S.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!R.includes(e)&&Ae(e)&&(G[e]=0,Ce(e)),R.includes(e)&&t&&D(e,{status:"queued",progress:0,version:t.version}),te()},Pn=e=>{let{pause_reasons:t}=S.getState();t.includes(e)||(S.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&ee({type:"pause_change",paused:!0,reasons:[e]}),M&&!M.forced&&M.handle.cancel())},Tn=e=>{let{pause_reasons:t}=S.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);S.setState({pause_reasons:n}),J("resume",e),n.length===0&&ee({type:"pause_change",paused:!1,reasons:n}),te()},Ut=e=>S.getState().updates[e],On=async e=>{var n,r;let t=Ut(e);Oe.add(e);try{let o=await ke(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=Ae(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(S.setState(a=>{var i;let p={...a.updates};return delete p[e],{updates:p,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),J("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{Oe.delete(e)}},Cn=()=>Object.values(S.getState().catalog).map(e=>({...e,installed:!!b(e.app_id),removed_by_user:ne.has(e.app_id)})),Ae=e=>S.getState().catalog[e],ke=async e=>{let t=Ae(e);if(!t)return;if(q.delete(e),ne.delete(e),await ze(t))return b(e);let n=b(e);if($t(e)&&!Oe.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=se[e])!=null?s:se[e]=[]).push(o)});return(M==null?void 0:M.app_id)===e?M.forced=!0:(G[e]=0,Ce(e,{front:!0}),M&&!M.forced?M.handle.cancel():te(e)),r};import{Fragment as Ht,jsx as P,jsxs as Me}from"react/jsx-runtime";var Ze=e=>(e!=null?e:"").replace(/\?[^#]*/,""),qt=0,Bn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},$n=nt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:p,opaque_background:i,allow_embedded_miniapps:u,onWebLoadEnd:w})=>{var ct,pt;let f=j(null),y=j(!1),m=W($,c=>c.instances[e]),h=m==null?void 0:m.app.app_id,T=m==null?void 0:m.app.manifest_url,E=m==null?void 0:m.context,L=m==null?void 0:m.url_params,[l,O]=ae(()=>h?b(h):null),[pe,X]=ae(!1),[ye,d]=ae(0),[v,V]=ae(0),[re,N]=ae(!1),H=j(null),it=c=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,N(!0)},c)};I(()=>()=>{H.current&&clearTimeout(H.current)},[]),I(()=>{if(!h||!t&&l)return;let c=!0;return X(!1),(async()=>{let g=b(h),C=g?await Q(g):!1;if(!c||(O(C?U=>!U||U.version!==g.version||U.permissions.join(",")!==g.permissions.join(",")?g:U:null),__DEV__&&Date.now()-qt>1e4&&(qt=Date.now(),await Ge()),!c))return;let Z=await ke(h),ie=Z!==void 0?Z:T?await It(h,T):b(h);if(c){if(!ie){X(!0);return}O(U=>U!=null?U:ie)}})(),()=>{c=!1}},[t,h,T,ye]),I(()=>Lt(e,c=>f.current?(f.current.postMessage(c),!0):!1),[e]);let zt=W(S,c=>{let g=h?c.downloads[h]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});I(()=>{if(t||!h||!l)return;let c=b(h);if(!c||c.version===l.version)return;let g=!0;return Q(c).then(C=>{!g||!C||(B(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),O(c))}),()=>{g=!1}},[t,h,zt,l==null?void 0:l.version]);let ot=W(S,c=>{var g;return h&&(g=c.apply_ticks[h])!=null?g:0});I(()=>{if(!ot||!h)return;let c=b(h);if(!c||c.version===(l==null?void 0:l.version))return;let g=!0;return Q(c).then(C=>{!g||!C||(B(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),N(!1),O(c))}),()=>{g=!1}},[ot]),I(()=>{var C;let c=(C=_().keep_alive)==null?void 0:C.idle_close_ms;if(t||!c||c<=0)return;let g=setTimeout(()=>{Re(e)},c);return()=>clearTimeout(g)},[t,e]),I(()=>{o>0&&(X(!1),N(!1),V(c=>c+1),d(c=>c+1))},[o]);let st=j(t);I(()=>{var c;st.current!==t&&(st.current=t,y.current&&((c=f.current)==null||c.injectJavaScript(bt(t?"resumed":"paused"))))},[t]);let le=`${(ct=l==null?void 0:l.version)!=null?ct:"none"}:${(pt=l==null?void 0:l.permissions.join(","))!=null?pt:""}:${v}`,ue=De(()=>JSON.stringify([E!=null?E:{},L!=null?L:{}]),[E,L]),Ie=De(()=>{var c;return Pt(L!=null?L:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[ue,l==null?void 0:l.permissions]),Kt=De(()=>Et(E!=null?E:{},Ie)+St()+(_().debug?vt():""),[Ie]),ve=j(null),at=j(null);I(()=>{var g,C,Z;if(!l)return;if(at.current!==le){at.current=le,ve.current=ue;return}if(ve.current===ue)return;let c=((C=JSON.parse((g=ve.current)!=null?g:"[]")[0])!=null?C:{}).org_id;if(ve.current=ue,c===(E==null?void 0:E.org_id)&&y.current){N(!1),it(1500),(Z=f.current)==null||Z.injectJavaScript(_t(E!=null?E:{},Ie));return}N(!1),V(ie=>ie+1)},[ue,l,le]),I(()=>(t||Y(e),()=>Y(e)),[t,e,le,o]),I(()=>{let c=Jt.addEventListener("change",g=>{g==="background"&&Y(e)});return()=>c.remove()},[e]);let Yt=et(async c=>{var C,Z,ie,U,Le;let g=At(c.nativeEvent.data);if(!g){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(c.nativeEvent.data,{app_id:h,instance_id:e})).catch(x=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,x)})}catch(x){console.warn("[miniapp] onWebEvent l\u1ED7i",h,x)}return}if(g.method==="log"){let{level:x,text:k}=g;B(`web:${e}`,x!=null?x:"log",k!=null?k:"");return}if(g.method==="pong"){H.current||N(!0);return}if(g.method==="touchAtTop"){s.emit(!!g.at_top);return}if(g.method==="contextApplied"){H.current&&clearTimeout(H.current),H.current=null,N(!0);return}if(g.method==="ready"){y.current=!0,N(!0);let x=(C=$.getState().instances[e])==null?void 0:C.context;x&&((Z=f.current)==null||Z.injectJavaScript(Ue(x)));return}try{let x=await Tt(g,{getHostData:()=>{var k,z;return(z=(k=$.getState().instances[e])==null?void 0:k.host_data)!=null?z:{}},getPermissions:()=>{var k,z;return h?(z=(k=b(h))==null?void 0:k.permissions)!=null?z:[]:[]},is_dark:r,close:he,app_id:h!=null?h:"",instance_id:e,options:p,emit:(k,z)=>{var lt;(lt=f.current)==null||lt.injectJavaScript(yt(k,z))},isActive:()=>$.getState().active_key===e&&Jt.currentState!=="background"});g.id&&((ie=f.current)==null||ie.injectJavaScript(wt(g.id,x)))}catch(x){if(!g.id)return;let k=x==null?void 0:x.code,z=x instanceof A?x:new A(typeof k=="string"?k:"HOST_ERROR",String((U=x==null?void 0:x.message)!=null?U:x));(Le=f.current)==null||Le.injectJavaScript(Mt(g.id,z))}},[e,r,h,s,p]),Qt=et(()=>{X(!1),V(c=>c+1),d(c=>c+1)},[]);return Me(tt,{style:[rt.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&F.behind],pointerEvents:t?"auto":"none",children:[l?P(Nn,{ref:f,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${u?je():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Kt,onMessage:Yt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{Y(e),B(`webview:${e}`,"load start",Ze(c.nativeEvent.url)),y.current=!1,N(!1)},onError:c=>{Y(e),B(`webview:${e}`,"load error",Ze(c.nativeEvent.url),c.nativeEvent.description),X(!0),N(!1)},onLoadEnd:c=>{let g=c.nativeEvent.url;B(`webview:${e}`,"load end",Ze(g)),h&&(w==null||w({app_id:h,instance_id:e,url:g})),it(1500)},onContentProcessDidTerminate:()=>{Y(e),y.current=!1,N(!1),V(c=>c+1)},onRenderProcessGone:()=>(Y(e),y.current=!1,N(!1),V(c=>c+1),!0),style:F.webview},le):null,m&&P(Vn,{visible:!l||!re,interactive:pe,children:P(Fn,{splash:a,app:m.app,is_dark:r,error:pe,has_bundle:!!l,retry:Qt})})]})}),Fn=nt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,p=Qe(t.app_id),i=r?"error":!o&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return P(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?p==null?void 0:p.progress:void 0,retry:s})}),Vn=({visible:e,interactive:t,children:n})=>{let r=j(new Xe.Value(e?1:0)).current,[o,s]=ae(e);return I(()=>{if(e){s(!0),r.setValue(1);return}let a=Xe.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:p})=>{p&&s(!1)}),()=>a.stop()},[e,r]),o?P(Xe.View,{style:[rt.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Wt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return Me(tt,{style:[F.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[P(tt,{style:[F.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?P(In,{source:{uri:e.icon},style:F.splash_icon_image}):P(we,{style:F.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),P(we,{style:[F.splash_name,{color:s}],children:e.name}),n==="error"?Me(Ht,{children:[P(we,{style:F.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),P(Ln,{activeOpacity:.7,style:[F.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:P(we,{style:[F.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):Me(Ht,{children:[P(kn,{style:F.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Me(we,{style:F.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},jt=(e,t)=>{let n=j(t),r=j(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Un=({container:e,splash:t=Wt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:p})=>{jt("container",e),jt("splash",t);let i=e,u=W($,l=>l.active_key),w=j(u);u&&(w.current=u);let f=W($,l=>Object.keys(l.instances).join("|")),y=W($,l=>{var O;return l.active_key?(O=l.instances[l.active_key])==null?void 0:O.app.name:void 0}),m=De(()=>f?f.split("|"):[],[f]),[h,T]=ae({}),E=j(Bn()).current;I(()=>{if(!u||!o)return;let l=Dn.addEventListener("hardwareBackPress",()=>(he(),!0));return()=>l.remove()},[u,o]);let L=et(()=>{let l=$.getState().active_key;l&&T(O=>({...O,[l]:(O[l]||0)+1}))},[]);return m.length?P(i,{visible:!!u,title:y!=null?y:"",is_dark:n,close:he,reload:L,subscribeWebAtTop:E.subscribe,children:m.map(l=>P($n,{instance_key:l,is_active:u===l,is_front:(u!=null?u:w.current)===l,is_dark:n,reload_tick:h[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:p},l))}):null},F=rt.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Jn=nt.memo(Un);export{Wt as DefaultMiniAppSplash,Ne as MINIAPP_PLATFORM_URL,Jn as MiniAppHost,A as MiniAppHostError,he as closeMiniApp,Gt as configureMiniApp,Zt as createMmkvStorage,gt as createReactNativeBiometrics,Xt as createRnfsFileSystem,ke as ensureMiniApp,b as getLocalMiniApp,Cn as getMiniAppCatalog,Ae as getMiniAppCatalogEntry,vn as getMiniAppStatuses,Ut as getMiniAppUpdate,sn as installBundledMiniApp,yn as onMiniAppEvent,un as openMiniApp,En as pauseMiniApp,Pn as pauseMiniAppDownloads,dn as preloadMiniApp,Y as releaseSpeechFor,xn as restoreMiniApp,Rn as resumeMiniApp,Tn as resumeMiniAppDownloads,cn as sendEventToWeb,Ge as syncMiniAppCatalog,_n as uninstallMiniApp,On as updateMiniApp,Qe as useMiniAppDownload,Mn as useMiniAppDownloadsPaused};
|
|
45
|
+
true;`},Ot={partner:"partner_token",chatbox:"chatbox_token"},Ct=(e,t)=>{let n={...e};for(let r of Object.values(Ot))t.includes(r)||delete n[r];return n},Ue=new Set,_e=async(e,t)=>{if(Ue.has(e))throw new f("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ue.add(e);try{return await t()}finally{Ue.delete(e)}},an=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),xe=(e,t)=>{if(typeof e!="string"||!e)throw new f("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},It=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:c,options:i,emit:p,isActive:w})=>{var A,T,E,D,u,O,le,X,ve;let d=i==null?void 0:i.handlers,y={app_id:a,instance_id:c,close:s},m=()=>new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let g=ht(t);return _e(e,()=>mt(g,w))}case"speech.start":{if(!p)throw m();let g={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new f("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");g.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new f("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);g[v]=t[v]}return At(c,g,p,w)}case"speech.stop":return wt(c);case"getBiometricAvailability":return((A=i==null?void 0:i.biometrics)!=null?A:await Ve()).getAvailability();case"authenticateBiometric":{let g=xe(t==null?void 0:t.reason,"reason").trim();if(!g||g.length>200)throw new f("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new f("INVALID_PARAMS","Invalid cancelButtonText");return _e(e,async()=>{var re;return((re=i==null?void 0:i.biometrics)!=null?re:await Ve()).authenticate({reason:g,cancelButtonText:v})})}case"requestPayment":{let g=d==null?void 0:d.requestPayment;if(!g)throw m();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new f("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let F={...t,amount:v,currency:xe(t==null?void 0:t.currency,"currency")};return _e(e,()=>g(F,y))}case"printImage":{let g=d==null?void 0:d.printImage;if(!g)throw m();let v=xe(t==null?void 0:t.image,"image");await _e(e,()=>g({image:v},y));return}case"openScreen":if(!(d!=null&&d.openScreen))throw m();await d.openScreen({screen:xe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":s();return;case"openWebview":{let g=String((T=t==null?void 0:t.url)!=null?T:"");if(!/^https?:\/\//i.test(g))throw new f("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(g):yt.openURL(g));return}case"openLink":{let g=String((E=t==null?void 0:t.url)!=null?E:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(g)||/^(javascript|file|data|about|blob):/i.test(g))throw new f("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(g):yt.openURL(g))}catch(v){throw new f("NOT_SUPPORTED",String((u=(D=v==null?void 0:v.message)!=null?D:v)!=null?u:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(le=i==null?void 0:i.showToast)==null||le.call(i,String((O=t==null?void 0:t.message)!=null?O:""));return;case"haptic":{let g=an.has(t==null?void 0:t.type)?t.type:"selection";(X=i==null?void 0:i.haptic)==null||X.call(i,g);return}case"getSystemInfo":return{platform:sn.OS==="ios"?"ios":"android",appVersion:(ve=i==null?void 0:i.app_version)!=null?ve:"",theme:o?"dark":"light"};case"getAccessToken":{let g=n().access_token;if(!g)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return g}case"getToken":{let g=t==null?void 0:t.type;if(g==="access"){let re=n().access_token;if(!re)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return re}if(g!=="partner"&&g!=="chatbox")throw new f("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(g)}`);let v=Ot[g];if(!r().includes(v))throw new f("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let F=g==="partner"?n().partner_token:n().chatbox_token;if(!F)throw new f("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return F}case"getUserInfo":{let g=n().user;if(!g)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return g}case"getPageInfo":{let g=n().page;if(!g)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return g}case"sendMessage":case"insertText":throw new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new f("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var He=e=>`bundle:${e}`,je=()=>`${_().file_system.document_dir}/miniapps`,We=je,ze=(e,t,n="index.html",r=!1,o=[])=>{let s=`${We()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},qe=e=>{var t;_().storage.setString(He(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},cn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,b=e=>{let t=_().storage.getString(He(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return ze(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},G=e=>_().file_system.exists(e.entry_uri.replace("file://","")),Ke=async e=>{let t=b(e.app_id);return(t==null?void 0:t.version)===e.version&&await G(t)},kt=async(e,t)=>{let n=_().file_system,r=`${We()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},Dt=async e=>{var t;await((t=he[e])==null?void 0:t.catch(()=>{})),_().storage.setString(He(e),""),await _().file_system.remove(`${We()}/${e}`).catch(()=>{})},pe=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},he={},Nt=(e,t)=>{var s;let r=((s=he[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return he[e]=o,o.then(()=>{he[e]===o&&delete he[e]}),r},pn=(e,t)=>{var o,s;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let c=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(c)return c}return 0},ln=({manifest:e,zip_path:t})=>Nt(e.app_id,async()=>{var s;let n=_().file_system,r=b(e.app_id);if(r&&pn(r.version,e.version)>=0&&await G(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=ze(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),qe(e),B("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),kt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Ye=(e,{base_url:t,onProgress:n}={})=>{let r=_().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(s)throw new pe},i=async()=>{var d;c();let p=b(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return qe(e),b(e.app_id);c();let w=r.download({url:t?cn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,m)=>{var T;let A=m>0?m:(T=e.size)!=null?T:0;A>0&&(n==null||n(Math.min(1,y/A)))}});o=w;try{let{status:y}=await w.promise;if(c(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else B("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let m=ze(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),qe(e),kt(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),m}catch(y){throw s?new pe:y}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Nt(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},fe={},un=__DEV__?0:60*1e3,Lt={},Bt=(e,t)=>{var r,o;let n=b(e);return n&&Date.now()-((r=Lt[t])!=null?r:0)<un?Promise.resolve(n):((o=fe[e])!=null||(fe[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),c=await Ye(a,{base_url:t}).promise;return Lt[t]=Date.now(),c})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),b(e))).finally(()=>{fe[e]=void 0})),fe[e])};var Re=new Map,$t=(e,t)=>(Re.set(e,t),()=>{Re.get(e)===t&&Re.delete(e)}),dn=(e,t)=>{let n=Re.get(e);return n?n(t):!1};import{useRef as gn,useSyncExternalStore as fn}from"react";var Pe=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},W=(e,t,n=Object.is)=>{let r=gn(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let c=t(s),i=a&&n(a.value,c)?a.value:c;return r.current={state:s,selector:t,value:i},i};return fn(e.subscribe,o)};var $=Pe({active_key:null,instances:{}}),Vt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var c;let a=(c=_().keep_alive)==null?void 0:c.max_webviews;$.setState(i=>{let p=t!=null?t:e.app_id,w={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},d=Object.keys(w);return a&&a>0&&d.length>a&&d.filter(y=>y!==p).sort((y,m)=>w[y].last_used_at-w[m].last_used_at).slice(0,d.length-a).forEach(y=>{delete w[y]}),s?{active_key:p,instances:w}:{instances:w}})},hn=e=>Vt(e,!0),mn=e=>Vt(e,!1),me=()=>$.setState({active_key:null}),Te=e=>{$.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Ft="catalog",An="paused_apps",wn="removed_apps",yn=10*1e3,Mn=2,vn=3e3,Sn=()=>{var e;try{return JSON.parse((e=_().storage.getString(Ft))!=null?e:"{}")}catch{return{}}},S=Pe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Ut=e=>{var t;return!!((t=_().manual_update)!=null&&t.includes(e))},Ie=new Set,Jt=e=>{let t=new Set,n=()=>_().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let o=JSON.parse((r=_().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},q=Jt(An),ne=Jt(wn);gt(()=>{q.load(),ne.load();let e=Sn(),t={};Object.keys(e).filter(n=>!ne.has(n)).forEach(n=>{let r=b(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:q.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),S.setState({catalog:e,downloads:t})});var Qe=e=>W(S,t=>e?t.downloads[e]:void 0),bn=()=>W(S,e=>e.pause_reasons.length>0),J=(...e)=>B("queue",...e),R=[],Q={},M=null,Oe=new Set,ae={},Ge=new Set,ee=e=>{Ge.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},_n=e=>(Ge.add(e),()=>{Ge.delete(e)}),xn=()=>S.getState().downloads,L=(e,t)=>{let n=!!b(e),r=S.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};S.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?ee({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&ee({type:"progress",app_id:e,progress:s.progress,version:s.version})},Ce=(e,t)=>{var n;(n=ae[e])==null||n.forEach(r=>r(t)),delete ae[e]},En=()=>S.getState().pause_reasons.length>0,te=e=>{var c;if(M)return;let t=e?R.indexOf(e):En()?-1:R.findIndex(i=>!q.has(i));if(t<0||t>=R.length)return;let[n]=R.splice(t,1),r=S.getState().catalog[n];if(!r){Ce(n,b(n)),te();return}let o=Date.now();Q[n]=((c=Q[n])!=null?c:0)+1,L(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Ye(r,{onProgress:i=>{let p=Math.floor(i*100);p!==s&&(s=p,L(n,{progress:p/100,version:r.version}))}});M={app_id:n,handle:a,forced:!!e},J("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{J("installed",n,r.version,`${Date.now()-o}ms`),L(n,{status:"installed",progress:1,version:r.version}),Ce(n,i)}).catch(i=>{var w;if(i instanceof pe){if(Oe.has(n))return;J("paused",n),Q[n]-=1,R.unshift(n),L(n,{status:q.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((w=i==null?void 0:i.message)!=null?w:i);if(console.warn("[miniapp-queue] failed",n,p),Q[n]<Mn){L(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var d;R.includes(n)||(M==null?void 0:M.app_id)===n||(R.push(n),te((d=ae[n])!=null&&d.length?n:void 0))},vn);return}L(n,{status:"failed",progress:0,version:r.version,error:p}),Ce(n,b(n))}).finally(()=>{M=null;let i=R.find(p=>{var w;return(w=ae[p])==null?void 0:w.length});te(i)})},Le=(e,{front:t=!1}={})=>{if((M==null?void 0:M.app_id)===e)return;let n=R.indexOf(e);if(n>=0){if(!t)return;R.splice(n,1)}t?R.unshift(e):R.push(e)},Rn=async e=>{let{host_id:t,client_token:n}=_(),r=new AbortController,o=setTimeout(()=>r.abort(),yn);try{let s=`${$e}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(o)}},Ae=null,Xe=()=>(Ae!=null||(Ae=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(_().channels.map(Rn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(S.getState().catalog).filter(i=>!r[i]);_().storage.setString(Ft,JSON.stringify(r)),S.setState({catalog:r}),await Promise.all(o.map(i=>qt(i,{by_user:!1}))),o.forEach(i=>ne.delete(i));let s=Object.keys(r).filter(i=>!ne.has(i)),a=[],c={};for(let i of s.map(p=>r[p])){if(await Ke(i)){L(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=b(i.app_id);if(Ut(i.app_id)&&!Ie.has(i.app_id)&&p&&await G(p)){L(i.app_id,{status:"installed",progress:1,version:p.version}),c[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return S.setState({updates:c}),a.forEach(i=>{Q[i.app_id]=0,L(i.app_id,{status:q.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Le(i.app_id)}),J("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),ee({type:"sync_complete",app_ids:s,removed:o}),Object.values(c).forEach(i=>ee({type:"update_available",...i})),te(),{ok:!0,app_ids:s,removed:o}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ee({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{Ae=null}})()),Ae),qt=async(e,{by_user:t})=>{var o,s,a,c;if(t&&ne.add(e),Oe.has(e))return;Oe.add(e),q.delete(e);let n=R.indexOf(e);n>=0&&R.splice(n,1),(M==null?void 0:M.app_id)===e&&M.handle.cancel();let r=(c=(a=(o=S.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=b(e))==null?void 0:s.version)!=null?c:"";L(e,{status:"uninstalling",progress:0,version:r}),await Dt(e),Te(e),S.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete Q[e],Oe.delete(e),Ce(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),ee({type:"uninstalled",app_id:e})},Pn=e=>qt(e,{by_user:!0}),Tn=e=>{let t=we(e);return t?(ne.delete(e),(M==null?void 0:M.app_id)===e||R.includes(e)||(Q[e]=0,L(e,{status:q.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Le(e),te(),J("restore",e)),!0):!1},On=e=>{if(q.has(e))return;if(q.add(e),J("pause app",e),(M==null?void 0:M.app_id)===e&&!M.forced){M.handle.cancel();return}let t=S.getState().downloads[e];R.includes(e)&&t&&L(e,{status:"paused",progress:0,version:t.version})},Cn=e=>{if(!q.delete(e))return;J("resume app",e);let t=S.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!R.includes(e)&&we(e)&&(Q[e]=0,Le(e)),R.includes(e)&&t&&L(e,{status:"queued",progress:0,version:t.version}),te()},In=e=>{let{pause_reasons:t}=S.getState();t.includes(e)||(S.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&ee({type:"pause_change",paused:!0,reasons:[e]}),M&&!M.forced&&M.handle.cancel())},Ln=e=>{let{pause_reasons:t}=S.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);S.setState({pause_reasons:n}),J("resume",e),n.length===0&&ee({type:"pause_change",paused:!1,reasons:n}),te()},Ht=e=>S.getState().updates[e],kn=async e=>{var n,r;let t=Ht(e);Ie.add(e);try{let o=await ke(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=we(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(S.setState(a=>{var i;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),J("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{Ie.delete(e)}},Dn=()=>Object.values(S.getState().catalog).map(e=>({...e,installed:!!b(e.app_id),removed_by_user:ne.has(e.app_id)})),we=e=>S.getState().catalog[e],ke=async e=>{let t=we(e);if(!t)return;if(q.delete(e),ne.delete(e),await Ke(t))return b(e);let n=b(e);if(Ut(e)&&!Ie.has(e)&&n&&await G(n))return n;let r=new Promise(o=>{var s;((s=ae[e])!=null?s:ae[e]=[]).push(o)});return(M==null?void 0:M.app_id)===e?M.forced=!0:(Q[e]=0,Le(e,{front:!0}),M&&!M.forced?M.handle.cancel():te(e)),r};import{Fragment as Kt,jsx as P,jsxs as Me}from"react/jsx-runtime";var et=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Wt=0,Un=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Jn=rt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:c,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:w})=>{var pt,lt;let d=H(null),y=H(!1),m=W($,l=>l.instances[e]),A=m==null?void 0:m.app.app_id,T=m==null?void 0:m.app.manifest_url,E=m==null?void 0:m.context,D=m==null?void 0:m.url_params,[u,O]=ce(()=>A?b(A):null),[le,X]=ce(!1),[ve,g]=ce(0),[v,F]=ce(0),[re,N]=ce(!1),j=H(null),ot=l=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,N(!0)},l)};k(()=>()=>{j.current&&clearTimeout(j.current)},[]),k(()=>{if(!A||!t&&u)return;let l=!0;return X(!1),(async()=>{let h=b(A),C=h?await G(h):!1;if(!l||(O(C?U=>!U||U.version!==h.version||U.permissions.join(",")!==h.permissions.join(",")?h:U:null),__DEV__&&Date.now()-Wt>1e4&&(Wt=Date.now(),await Xe()),!l))return;let Z=await ke(A),ie=Z!==void 0?Z:T?await Bt(A,T):b(A);if(l){if(!ie){X(!0);return}O(U=>U!=null?U:ie)}})(),()=>{l=!1}},[t,A,T,ve]),k(()=>$t(e,l=>d.current?(d.current.postMessage(l),!0):!1),[e]);let Gt=W(S,l=>{let h=A?l.downloads[A]:void 0;return(h==null?void 0:h.status)==="installed"?h.version:void 0});k(()=>{if(t||!A||!u)return;let l=b(A);if(!l||l.version===u.version)return;let h=!0;return G(l).then(C=>{!h||!C||(B(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",u.version,"\u2192",l.version),O(l))}),()=>{h=!1}},[t,A,Gt,u==null?void 0:u.version]);let st=W(S,l=>{var h;return A&&(h=l.apply_ticks[A])!=null?h:0});k(()=>{if(!st||!A)return;let l=b(A);if(!l||l.version===(u==null?void 0:u.version))return;let h=!0;return G(l).then(C=>{!h||!C||(B(`webview:${e}`,"c\u1EADp nh\u1EADt",u==null?void 0:u.version,"\u2192",l.version),N(!1),O(l))}),()=>{h=!1}},[st]),k(()=>{var C;let l=(C=_().keep_alive)==null?void 0:C.idle_close_ms;if(t||!l||l<=0)return;let h=setTimeout(()=>{Te(e)},l);return()=>clearTimeout(h)},[t,e]),k(()=>{o>0&&(X(!1),N(!1),F(l=>l+1),g(l=>l+1))},[o]);let at=H(t);k(()=>{var l;at.current!==t&&(at.current=t,y.current&&((l=d.current)==null||l.injectJavaScript(Et(t?"resumed":"paused"))))},[t]);let ue=`${(pt=u==null?void 0:u.version)!=null?pt:"none"}:${(lt=u==null?void 0:u.permissions.join(","))!=null?lt:""}:${v}`,de=De(()=>JSON.stringify([E!=null?E:{},D!=null?D:{}]),[E,D]),Ne=De(()=>{var l;return Ct(D!=null?D:{},(l=u==null?void 0:u.permissions)!=null?l:[])},[de,u==null?void 0:u.permissions]),Qt=De(()=>Tt(E!=null?E:{},Ne)+xt()+(_().debug?_t():""),[Ne]),Se=H(null),ct=H(null);k(()=>{var h,C,Z;if(!u)return;if(ct.current!==ue){ct.current=ue,Se.current=de;return}if(Se.current===de)return;let l=((C=JSON.parse((h=Se.current)!=null?h:"[]")[0])!=null?C:{}).org_id;if(Se.current=de,l===(E==null?void 0:E.org_id)&&y.current){N(!1),ot(1500),(Z=d.current)==null||Z.injectJavaScript(Rt(E!=null?E:{},Ne));return}N(!1),F(ie=>ie+1)},[de,u,ue]),k(()=>(t||Y(e),()=>Y(e)),[t,e,ue,o]),k(()=>{let l=jt.addEventListener("change",h=>{h==="background"&&Y(e)});return()=>l.remove()},[e]);let Xt=tt(async l=>{var C,Z,ie,U,Be;let h=Mt(l.nativeEvent.data);if(!h){if(A&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(l.nativeEvent.data,{app_id:A,instance_id:e})).catch(x=>{console.warn("[miniapp] onWebEvent l\u1ED7i",A,x)})}catch(x){console.warn("[miniapp] onWebEvent l\u1ED7i",A,x)}return}if(h.method==="log"){let{level:x,text:I}=h;B(`web:${e}`,x!=null?x:"log",I!=null?I:"");return}if(h.method==="pong"){j.current||N(!0);return}if(h.method==="touchAtTop"){s.emit(!!h.at_top);return}if(h.method==="contextApplied"){j.current&&clearTimeout(j.current),j.current=null,N(!0);return}if(h.method==="ready"){y.current=!0,N(!0);let x=(C=$.getState().instances[e])==null?void 0:C.context;x&&((Z=d.current)==null||Z.injectJavaScript(Je(x)));return}try{let x=await It(h,{getHostData:()=>{var I,z;return(z=(I=$.getState().instances[e])==null?void 0:I.host_data)!=null?z:{}},getPermissions:()=>{var I,z;return A?(z=(I=b(A))==null?void 0:I.permissions)!=null?z:[]:[]},is_dark:r,close:me,app_id:A!=null?A:"",instance_id:e,options:c,emit:(I,z)=>{var ut;(ut=d.current)==null||ut.injectJavaScript(bt(I,z))},isActive:()=>$.getState().active_key===e&&jt.currentState!=="background"});h.id&&((ie=d.current)==null||ie.injectJavaScript(vt(h.id,x)))}catch(x){if(!h.id)return;let I=x==null?void 0:x.code,z=x instanceof f?x:new f(typeof I=="string"?I:"HOST_ERROR",String((U=x==null?void 0:x.message)!=null?U:x));(Be=d.current)==null||Be.injectJavaScript(St(h.id,z))}},[e,r,A,s,c]),Zt=tt(()=>{X(!1),F(l=>l+1),g(l=>l+1)},[]);return Me(nt,{style:[it.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&V.behind],pointerEvents:t?"auto":"none",children:[u?P(Fn,{ref:d,source:{uri:u.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?je():u.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Qt,onMessage:Xt,bounces:!1,overScrollMode:"never",onLoadStart:l=>{Y(e),B(`webview:${e}`,"load start",et(l.nativeEvent.url)),y.current=!1,N(!1)},onError:l=>{Y(e),B(`webview:${e}`,"load error",et(l.nativeEvent.url),l.nativeEvent.description),X(!0),N(!1)},onLoadEnd:l=>{let h=l.nativeEvent.url;B(`webview:${e}`,"load end",et(h)),A&&(w==null||w({app_id:A,instance_id:e,url:h})),ot(1500)},onContentProcessDidTerminate:()=>{Y(e),y.current=!1,N(!1),F(l=>l+1)},onRenderProcessGone:()=>(Y(e),y.current=!1,N(!1),F(l=>l+1),!0),style:V.webview},ue):null,m&&P(Hn,{visible:!u||!re,interactive:le,children:P(qn,{splash:a,app:m.app,is_dark:r,error:le,has_bundle:!!u,retry:Zt})})]})}),qn=rt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,c=Qe(t.app_id),i=r?"error":!o&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return P(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?c==null?void 0:c.progress:void 0,retry:s})}),Hn=({visible:e,interactive:t,children:n})=>{let r=H(new Ze.Value(e?1:0)).current,[o,s]=ce(e);return k(()=>{if(e){s(!0),r.setValue(1);return}let a=Ze.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&s(!1)}),()=>a.stop()},[e,r]),o?P(Ze.View,{style:[it.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Yt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return Me(nt,{style:[V.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[P(nt,{style:[V.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?P($n,{source:{uri:e.icon},style:V.splash_icon_image}):P(ye,{style:V.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),P(ye,{style:[V.splash_name,{color:s}],children:e.name}),n==="error"?Me(Kt,{children:[P(ye,{style:V.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),P(Vn,{activeOpacity:.7,style:[V.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:P(ye,{style:[V.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):Me(Kt,{children:[P(Nn,{style:V.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Me(ye,{style:V.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},zt=(e,t)=>{let n=H(t),r=H(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},jn=({container:e,splash:t=Yt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{zt("container",e),zt("splash",t);let i=e,p=W($,u=>u.active_key),w=H(p);p&&(w.current=p);let d=W($,u=>Object.keys(u.instances).join("|")),y=W($,u=>{var O;return u.active_key?(O=u.instances[u.active_key])==null?void 0:O.app.name:void 0}),m=De(()=>d?d.split("|"):[],[d]),[A,T]=ce({}),E=H(Un()).current;k(()=>{if(!p||!o)return;let u=Bn.addEventListener("hardwareBackPress",()=>(me(),!0));return()=>u.remove()},[p,o]);let D=tt(()=>{let u=$.getState().active_key;u&&T(O=>({...O,[u]:(O[u]||0)+1}))},[]);return m.length?P(i,{visible:!!p,title:y!=null?y:"",is_dark:n,close:me,reload:D,subscribeWebAtTop:E.subscribe,children:m.map(u=>P(Jn,{instance_key:u,is_active:p===u,is_front:(p!=null?p:w.current)===u,is_dark:n,reload_tick:A[u]||0,web_at_top:E,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:c},u))}):null},V=it.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Wn=rt.memo(jn);export{Yt as DefaultMiniAppSplash,$e as MINIAPP_PLATFORM_URL,Wn as MiniAppHost,f as MiniAppHostError,me as closeMiniApp,en as configureMiniApp,nn as createMmkvStorage,ft as createReactNativeBiometrics,tn as createRnfsFileSystem,ke as ensureMiniApp,b as getLocalMiniApp,Dn as getMiniAppCatalog,we as getMiniAppCatalogEntry,xn as getMiniAppStatuses,Ht as getMiniAppUpdate,ln as installBundledMiniApp,_n as onMiniAppEvent,hn as openMiniApp,On as pauseMiniApp,In as pauseMiniAppDownloads,mn as preloadMiniApp,Y as releaseSpeechFor,Tn as restoreMiniApp,Cn as resumeMiniApp,Ln as resumeMiniAppDownloads,dn as sendEventToWeb,Xe as syncMiniAppCatalog,Pn as uninstallMiniApp,kn as updateMiniApp,Qe as useMiniAppDownload,bn as useMiniAppDownloadsPaused};
|