@retion-miniapp/react-native 0.10.4 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app.plugin.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // Expo prebuild plugin. Bare React Native hosts set NSFaceIDUsageDescription in Info.plist.
2
2
  const { withInfoPlist, withAndroidManifest } = require('expo/config-plugins');
3
3
  const withSpeechRecognition = require('expo-speech-recognition/app.plugin.js');
4
+ // Plugin này build từ ES module nên hàm nằm ở .default.
5
+ const withVisionCamera = require('react-native-vision-camera/app.plugin.js').default;
4
6
 
5
7
  module.exports = function withMiniApp(config, options = {}) {
6
8
  config = withInfoPlist(config, config => {
@@ -15,7 +17,7 @@ module.exports = function withMiniApp(config, options = {}) {
15
17
  || 'Allow this app to access your photos to upload them.';
16
18
  config.modResults.NSCameraUsageDescription = options.cameraPermission
17
19
  || config.modResults.NSCameraUsageDescription
18
- || 'Allow this app to use the camera to take photos and videos to upload.';
20
+ || 'Allow this app to use the camera to scan codes and to take photos and videos to upload.';
19
21
  return config;
20
22
  });
21
23
  config = withSpeechRecognition(config, {
@@ -23,6 +25,11 @@ module.exports = function withMiniApp(config, options = {}) {
23
25
  speechRecognitionPermission: options.speechRecognitionPermission,
24
26
  androidSpeechServicePackages: options.androidSpeechServicePackages,
25
27
  });
28
+ // Thêm quyền CAMERA Android và nhúng sẵn model quét mã (ML Kit, khoảng 2,4 MB) để quét được ngay, không cần tải.
29
+ const camera_text = config.ios?.infoPlist?.NSCameraUsageDescription;
30
+ config = withVisionCamera(config, { enableCodeScanner: true });
31
+ // Plugin vision-camera tự đặt câu mặc định, có thể đè câu của app; câu quyền đã xử lý ở withInfoPlist phía trên.
32
+ if (camera_text === undefined) { delete config.ios.infoPlist.NSCameraUsageDescription; }
26
33
  return withAndroidManifest(config, config => {
27
34
  const manifest = config.modResults.manifest;
28
35
  const permissions = manifest['uses-permission'] || [];
package/dist/index.d.mts CHANGED
@@ -638,6 +638,65 @@ interface SpeechOptions {
638
638
  /** Đó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. */
639
639
  declare const releaseSpeechFor: (owner: string) => void;
640
640
 
641
+ /** Giá trị trùng với react-native-vision-camera → truyền thẳng xuống native, không phải map. */
642
+ declare const CODE_TYPES: {
643
+ readonly qr: "qr";
644
+ readonly ean13: "ean-13";
645
+ readonly ean8: "ean-8";
646
+ readonly upcA: "upc-a";
647
+ readonly upcE: "upc-e";
648
+ readonly code128: "code-128";
649
+ readonly code39: "code-39";
650
+ readonly code93: "code-93";
651
+ readonly codabar: "codabar";
652
+ readonly itf: "itf";
653
+ readonly pdf417: "pdf-417";
654
+ readonly aztec: "aztec";
655
+ readonly dataMatrix: "data-matrix";
656
+ };
657
+ type CodeType = (typeof CODE_TYPES)[keyof typeof CODE_TYPES];
658
+ declare const CodeType: {
659
+ all: CodeType[];
660
+ qr: "qr";
661
+ ean13: "ean-13";
662
+ ean8: "ean-8";
663
+ upcA: "upc-a";
664
+ upcE: "upc-e";
665
+ code128: "code-128";
666
+ code39: "code-39";
667
+ code93: "code-93";
668
+ codabar: "codabar";
669
+ itf: "itf";
670
+ pdf417: "pdf-417";
671
+ aztec: "aztec";
672
+ dataMatrix: "data-matrix";
673
+ };
674
+ declare const ScannerMethod: {
675
+ readonly scan: "scanner.scan";
676
+ readonly start: "scanner.start";
677
+ readonly stop: "scanner.stop";
678
+ };
679
+ declare const ScannerEvent: {
680
+ readonly result: "scanner.result";
681
+ readonly end: "scanner.end";
682
+ };
683
+ declare const ScannerEndReason: {
684
+ readonly user: "user";
685
+ readonly web: "web";
686
+ readonly closed: "closed";
687
+ readonly error: "error";
688
+ };
689
+ type ScannerEndReason = (typeof ScannerEndReason)[keyof typeof ScannerEndReason];
690
+ interface ScannerOptions {
691
+ types?: CodeType[];
692
+ /** Quét liên tiếp: thời gian trước khi nhận lại cùng một mã. */
693
+ cooldown_ms?: number;
694
+ }
695
+ interface ScannerResult {
696
+ value: string;
697
+ type: string;
698
+ }
699
+
641
700
  interface LocationOptions {
642
701
  enableHighAccuracy?: boolean;
643
702
  timeout?: number;
@@ -691,4 +750,4 @@ interface UploadCapabilities {
691
750
  /** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
692
751
  declare const uploadToUrl: MiniAppUploader;
693
752
 
694
- 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 MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, 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, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
753
+ export { CodeType, 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 MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, ScannerEndReason, ScannerEvent, ScannerMethod, type ScannerOptions, type ScannerResult, type SpeechOptions, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, 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, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.d.ts CHANGED
@@ -638,6 +638,65 @@ interface SpeechOptions {
638
638
  /** Đó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. */
639
639
  declare const releaseSpeechFor: (owner: string) => void;
640
640
 
641
+ /** Giá trị trùng với react-native-vision-camera → truyền thẳng xuống native, không phải map. */
642
+ declare const CODE_TYPES: {
643
+ readonly qr: "qr";
644
+ readonly ean13: "ean-13";
645
+ readonly ean8: "ean-8";
646
+ readonly upcA: "upc-a";
647
+ readonly upcE: "upc-e";
648
+ readonly code128: "code-128";
649
+ readonly code39: "code-39";
650
+ readonly code93: "code-93";
651
+ readonly codabar: "codabar";
652
+ readonly itf: "itf";
653
+ readonly pdf417: "pdf-417";
654
+ readonly aztec: "aztec";
655
+ readonly dataMatrix: "data-matrix";
656
+ };
657
+ type CodeType = (typeof CODE_TYPES)[keyof typeof CODE_TYPES];
658
+ declare const CodeType: {
659
+ all: CodeType[];
660
+ qr: "qr";
661
+ ean13: "ean-13";
662
+ ean8: "ean-8";
663
+ upcA: "upc-a";
664
+ upcE: "upc-e";
665
+ code128: "code-128";
666
+ code39: "code-39";
667
+ code93: "code-93";
668
+ codabar: "codabar";
669
+ itf: "itf";
670
+ pdf417: "pdf-417";
671
+ aztec: "aztec";
672
+ dataMatrix: "data-matrix";
673
+ };
674
+ declare const ScannerMethod: {
675
+ readonly scan: "scanner.scan";
676
+ readonly start: "scanner.start";
677
+ readonly stop: "scanner.stop";
678
+ };
679
+ declare const ScannerEvent: {
680
+ readonly result: "scanner.result";
681
+ readonly end: "scanner.end";
682
+ };
683
+ declare const ScannerEndReason: {
684
+ readonly user: "user";
685
+ readonly web: "web";
686
+ readonly closed: "closed";
687
+ readonly error: "error";
688
+ };
689
+ type ScannerEndReason = (typeof ScannerEndReason)[keyof typeof ScannerEndReason];
690
+ interface ScannerOptions {
691
+ types?: CodeType[];
692
+ /** Quét liên tiếp: thời gian trước khi nhận lại cùng một mã. */
693
+ cooldown_ms?: number;
694
+ }
695
+ interface ScannerResult {
696
+ value: string;
697
+ type: string;
698
+ }
699
+
641
700
  interface LocationOptions {
642
701
  enableHighAccuracy?: boolean;
643
702
  timeout?: number;
@@ -691,4 +750,4 @@ interface UploadCapabilities {
691
750
  /** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
692
751
  declare const uploadToUrl: MiniAppUploader;
693
752
 
694
- 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 MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, 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, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
753
+ export { CodeType, 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 MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, ScannerEndReason, ScannerEvent, ScannerMethod, type ScannerOptions, type ScannerResult, type SpeechOptions, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, 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, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Hn=Object.create;var $e=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var Kn=Object.getOwnPropertyNames;var Yn=Object.getPrototypeOf,Gn=Object.prototype.hasOwnProperty;var Qn=(e,t)=>{for(var n in t)$e(e,n,{get:t[n],enumerable:!0})},Et=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Kn(t))!Gn.call(e,r)&&r!==n&&$e(e,r,{get:()=>t[r],enumerable:!(i=Jn(t,r))||i.enumerable});return e};var ue=(e,t,n)=>(n=e!=null?Hn(Yn(e)):{},Et(t||!e||!e.__esModule?$e(n,"default",{value:e,enumerable:!0}):n,e)),Xn=e=>Et($e({},"__esModule",{value:!0}),e);var Fi={};Qn(Fi,{DefaultMiniAppSplash:()=>St,MINIAPP_PLATFORM_URL:()=>Be,MiniAppHost:()=>zn,MiniAppHostError:()=>u,closeMiniApp:()=>be,configureMiniApp:()=>Rt,createMmkvStorage:()=>Ct,createReactNativeBiometrics:()=>rt,createRnfsFileSystem:()=>Tt,ensureMiniApp:()=>Ue,getLocalMiniApp:()=>R,getMiniAppCatalog:()=>Bn,getMiniAppCatalogEntry:()=>xe,getMiniAppStatuses:()=>Cn,getMiniAppUpdate:()=>Mt,installBundledMiniApp:()=>wn,onMiniAppEvent:()=>Tn,openMiniApp:()=>bn,pauseMiniApp:()=>Dn,pauseMiniAppDownloads:()=>Nn,preloadMiniApp:()=>xn,releaseSpeechFor:()=>te,restoreMiniApp:()=>Ln,resumeMiniApp:()=>Un,resumeMiniAppDownloads:()=>Fn,sendEventToWeb:()=>Sn,syncMiniAppCatalog:()=>tt,uninstallMiniApp:()=>kn,updateMiniApp:()=>$n,uploadToUrl:()=>ct,useMiniAppDownload:()=>Ze,useMiniAppDownloadsPaused:()=>On});module.exports=Xn(Fi);var Be="https://retion-miniapp-platform.vercel.app",Ae=null,Pt=new Set,Rt=e=>{Ae=e,Pt.forEach(t=>t())},I=()=>{if(!Ae)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Ae},Ot=e=>{Pt.add(e),Ae&&e()},J=(...e)=>{Ae!=null&&Ae.debug&&console.log("[miniapp]",...e)};var Tt=(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(i=>i.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:r})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>r==null?void 0:r(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Ct=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var w=ue(require("react")),E=require("react-native"),jn=ue(require("react-native-webview"));var Ce=require("react-native");var rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),qe,ot=()=>(qe||(qe=import("react-native-biometrics").then(({default:e})=>rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw qe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),qe);var ee=require("react-native");var It=e=>{var n,i,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("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 u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},kt=(e,t=()=>!0)=>new Promise((n,i)=>{let r=!1,o=(a,s)=>{r||(r=!0,clearTimeout(c),a?i(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>r?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(ee.Platform.OS==="android"){let s=ee.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=ee.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ee.PermissionsAndroid.check(s);if(!p())return;let y=g||await ee.PermissionsAndroid.check(d);if(!p())return;if(!g&&!y){let l=await ee.PermissionsAndroid.requestMultiple([s,d]);if(!p())return;if(l[s]!==ee.PermissionsAndroid.RESULTS.GRANTED&&l[d]!==ee.PermissionsAndroid.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});var at=require("react-native");var st=20,Lt=20,Bt=/^[a-z][a-z0-9_-]{0,31}$/,Zn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,ei=["low","medium","high"],de=e=>!!e&&typeof e=="object"&&!Array.isArray(e),U=e=>new u("INVALID_PARAMS",e),Oe=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Dt=(e,t)=>{if(e===void 0)return{};if(!de(e)||Object.keys(e).length>Lt||Object.values(e).some(n=>typeof n!="string"))throw U(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Lt} key)`);return e},qt=e=>{var n,i,r,o;if(e!==void 0&&!de(e))throw U("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Bt.test(t.source)))throw U("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Zn.test(c))))throw U("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Oe(t.max_count,1,st))throw U(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${st}`);if(t.max_size!==void 0&&!Oe(t.max_size,1,Number.MAX_SAFE_INTEGER))throw U("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Oe(t.concurrency,1,5))throw U("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:ti(t.process),target:ni(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},ti=e=>{if(e===void 0)return{};if(!de(e))throw U("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!de(n))throw U("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!Oe(n[i],1,1e4))throw U(`process.image.${i} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw U("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!de(n))throw U("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Oe(n.max_duration,1,3600))throw U("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!ei.includes(n.quality))throw U("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},ni=e=>{var n,i,r,o;if(e===void 0)return{target:"host",params:{}};if(!de(e))throw U("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Bt.test(t))throw U("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!de(e.params))throw U("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw U("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw U(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Dt(e.headers,"upload.headers"),form_data:Dt(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(o=e.url_field)!=null?o:"url"}},Vt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},ii=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=Vt(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===i:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},ri=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},Ee,oi=()=>(Ee!=null||(Ee=import("react-native-image-picker").catch(e=>{throw Ee=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ee),Ut=e=>async({accept:t,max_count:n,process:i})=>{var a,s,d,g,y,l,h,T,_;let r=await oi(),o=ri(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=i.image)==null?void 0:a.max_width,maxHeight:(s=i.image)==null?void 0:s.max_height,quality:(g=(d=i.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(y=i.video)==null?void 0:y.quality)!=null?l:"medium",durationLimit:(h=i.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await r.launchCamera({...c,saveToPhotos:!1}):await r.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let b=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(b,(T=p.errorMessage)!=null?T:p.errorCode)}return((_=p.assets)!=null?_:[]).filter(b=>b.uri).map((b,f)=>{var L,G,$;return{uri:b.uri,name:(L=b.fileName)!=null?L:`file_${f+1}`,mime_type:(G=b.type)!=null?G:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!(($=b.type)!=null&&$.startsWith("video/"))||at.Platform.OS==="ios"}})},si={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},ai={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},ci=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let i=t.map(s=>{var d;return(d=si[s])!=null?d:ai[s]}),r=!t.length||i.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(i)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var T,_,b;return{uri:l.uri,name:(T=l.name)!=null?T:`file_${h+1}`,mime_type:(_=l.type)!=null?_:"application/octet-stream",size:(b=l.size)!=null?b:void 0}});if(at.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),y=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=y.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Pe,pi=async e=>(Pe!=null||(Pe=import("@react-native-documents/picker").then(t=>ci(t)).catch(t=>{throw Pe=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Pe)(e)),jt={library:Ut("library"),camera:Ut("camera"),document:pi},Nt={type:"image",label:"\u1EA2nh",accept:["image/*"]},Ft={type:"video",label:"Video",accept:["video/*"]},$t={library:[Nt,Ft,{type:"media",label:"\u1EA2nh + video",accept:["image/*","video/*"]}],camera:[Nt,Ft],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"office",label:"Word / Excel",accept:[".doc",".docx",".xls",".xlsx"]}]},Re,zt=()=>(Re!=null||(Re=import("react-native-compressor").catch(()=>(Re=void 0,null))),Re),Wt=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},li=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),ui={low:640,medium:1280,high:1920},di=async(e,{image:t})=>{var i;if(!t||!li.has(e.mime_type.toLowerCase()))return e;let n=await zt();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(i=t.quality)!=null?i:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Wt(n,r,e.size),processed:!0}}catch{return e}},gi=async(e,{video:t})=>{var i;let n=await zt();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:ui[(i=t==null?void 0:t.quality)!=null?i:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Wt(n,r,e.size),processed:!0}}catch{return e}},mi={image:di,video:gi},fi=(e,t)=>t.split(".").reduce((n,i)=>de(n)?n[i]:void 0,e),ct=({file:e,target:t,onProgress:n,signal:i})=>new Promise((r,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,y])=>a.append(g,y)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();i.addEventListener("abort",s);let d=g=>{i.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,y])=>p.setRequestHeader(g,y)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let y=fi(g,c.url_field);if(typeof y!="string"||!y){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}r({url:y,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Ht=e=>{var i,r;let t={...jt};for(let[o,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[o]=c:delete t[o];let n={url:ct};for(let[o,c]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Jt=e=>{let{sources:t,targets:n}=Ht(e),i=Object.keys(t),r=Object.fromEntries(i.filter(o=>t[o]===jt[o]&&$t[o]).map(o=>[o,$t[o]]));return{sources:i,file_types:r,targets:Object.keys(n),max_count:st}},je=new Map,Kt=(e,t)=>`${e}:${t}`,hi=0,Yt=(e,t)=>{var n;typeof t=="string"&&((n=je.get(Kt(e,t)))==null||n.abort())},we=e=>{for(let[t,n]of je)t.startsWith(`${e}:`)&&n.abort()},Ve=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),yi=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Gt=async(e,t)=>{var a;let{sources:n,targets:i}=Ht(t.config),r=n[e.source];if(!r)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=i[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=Kt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++hi}`);je.set(p,c);try{return await Ai(e,t,r,o,c.signal)}finally{je.delete(p)}},Ai=async(e,{instance_id:t,app_id:n,getContext:i,task_id:r,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var A,S,z;let g={app_id:n!=null?n:"",instance_id:t,context:{...(A=i==null?void 0:i())!=null?A:{}}},y=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw Ve();if(!y.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=y.filter(v=>ii(v,e.accept)?!0:(l.push({name:v.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${v.mime_type||Vt(v.name)}`}),!1)),T=h.map(()=>0),_=h.map(v=>{var D;return(D=v.size)!=null?D:0}),b=0,f=0,L=(v=!1)=>{if(!c||!r)return;let D=Date.now();if(!v&&D-f<200)return;f=D;let ie=_.reduce((C,W)=>C+W,0),B=T.reduce((C,W)=>C+W,0);c("upload.progress",{task_id:r,loaded:B,total:ie,percent:ie?Math.min(100,Math.round(B/ie*100)):0,done_count:b,count:h.length})},G=[],$=0,Se=async()=>{var v,D,ie;for(;$<h.length;){let B=$++,C=h[B];try{if(d.aborted)throw Ve();let W=C.mime_type.startsWith("image/")?"image":C.mime_type.startsWith("video/")?"video":void 0,pe=W&&!C.processed?(D=(v=o==null?void 0:o.processors)==null?void 0:v[W])!=null?D:mi[W]:void 0;if(pe&&(C=await pe(C,e.process),_[B]=(ie=C.size)!=null?ie:_[B],d.aborted))throw Ve();if(e.max_size&&C.size&&C.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${C.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let he=(Ne,Fe)=>{T[B]=Ne,Fe&&(_[B]=Fe),L()},re=await s({file:C,target:e.target,onProgress:he,signal:d,caller:g});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:nt,...oe}=re;G[B]={url:nt,name:C.name,mime_type:C.mime_type,size:C.size,width:C.width,height:C.height,duration:C.duration,...Object.keys(oe).length?{response:"response"in oe?oe.response:oe}:{}},T[B]=_[B]}catch(W){l.push(yi(h[B].name,W))}finally{b++,L(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},Se)),d.aborted)throw Ve();let ce=G.filter(v=>!!v);if(!ce.length){let v=l[0];throw new u((S=v==null?void 0:v.code)!=null?S:"UPLOAD_FAILED",(z=v==null?void 0:v.message)!=null?z:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:l}};var Me=require("react-native");var K,Qt=()=>Me.Platform.OS==="android"&&!!(K!=null&&K.requesting_permission),wi=1500,Mi=()=>new Promise(e=>{if(Me.Platform.OS!=="android"||Me.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),i.remove(),e()},n=setTimeout(t,wi),i=Me.AppState.addEventListener("change",r=>{r==="active"&&t()})}),pt=e=>{var t;if(K===e&&(K=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Me.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Xt=async(e,t,n,i=()=>!0)=>{var o,c,p,a,s;if(K)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};K=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(r.native=g,r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await g.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await Mi(),r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(g.addListener("result",l=>{var h,T;K!==r||r.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(T=(h=l.results[0])==null?void 0:h.transcript)!=null?T:""})}),g.addListener("error",l=>{K===r&&!r.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{K===r&&(pt(r),n("speech.end"))})),r.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw pt(r),d}},Zt=e=>{let t=K;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},te=e=>{let t=K;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{pt(t)}};var We=1,u=class extends Error{constructor(n,i){super(i);this.code=n}},en=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===We&&typeof t.method=="string"?t:null}catch{return null}},Ie=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,tn=(e,t)=>Ie({id:e,result:t}),nn=(e,t)=>Ie({id:e,error:{code:t.code,message:t.message}}),rn=(e,t)=>Ie({event:e,data:t}),ut=e=>Ie({event:"context",data:e});var on=()=>`(function () {
1
+ "use strict";var Mr=Object.create;var Xe=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var _r=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,Er=Object.prototype.hasOwnProperty;var Pr=(e,t)=>{for(var n in t)Xe(e,n,{get:t[n],enumerable:!0})},zt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _r(t))!Er.call(e,o)&&o!==n&&Xe(e,o,{get:()=>t[o],enumerable:!(r=vr(t,o))||r.enumerable});return e};var de=(e,t,n)=>(n=e!=null?Mr(xr(e)):{},zt(t||!e||!e.__esModule?Xe(n,"default",{value:e,enumerable:!0}):n,e)),Rr=e=>zt(Xe({},"__esModule",{value:!0}),e);var ho={};Pr(ho,{CodeType:()=>rt,DefaultMiniAppSplash:()=>Bt,MINIAPP_PLATFORM_URL:()=>Qe,MiniAppHost:()=>Ar,MiniAppHostError:()=>u,ScannerEndReason:()=>Re,ScannerEvent:()=>ot,ScannerMethod:()=>Ie,closeMiniApp:()=>De,configureMiniApp:()=>Wt,createMmkvStorage:()=>Kt,createReactNativeBiometrics:()=>yt,createRnfsFileSystem:()=>Yt,ensureMiniApp:()=>Ge,getLocalMiniApp:()=>C,getMiniAppCatalog:()=>fr,getMiniAppCatalogEntry:()=>Ne,getMiniAppStatuses:()=>sr,getMiniAppUpdate:()=>Ft,installBundledMiniApp:()=>Yn,onMiniAppEvent:()=>ir,openMiniApp:()=>Zn,pauseMiniApp:()=>pr,pauseMiniAppDownloads:()=>dr,preloadMiniApp:()=>er,releaseSpeechFor:()=>le,restoreMiniApp:()=>lr,resumeMiniApp:()=>ur,resumeMiniAppDownloads:()=>gr,sendEventToWeb:()=>Xn,syncMiniAppCatalog:()=>ft,uninstallMiniApp:()=>cr,updateMiniApp:()=>mr,uploadToUrl:()=>bt,useMiniAppDownload:()=>gt,useMiniAppDownloadsPaused:()=>or});module.exports=Rr(ho);var Qe="https://retion-miniapp-platform.vercel.app",xe=null,Ht=new Set,Wt=e=>{xe=e,Ht.forEach(t=>t())},k=()=>{if(!xe)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return xe},Jt=e=>{Ht.add(e),xe&&e()},Z=(...e)=>{xe!=null&&xe.debug&&console.log("[miniapp]",...e)};var Yt=(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:i,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:c})=>o==null?void 0:o(l,c)});return{promise:a.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(i)}}}),Kt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var S=de(require("react")),E=require("react-native"),wr=de(require("react-native-webview"));var He=require("react-native");var yt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Ze,wt=()=>(Ze||(Ze=import("react-native-biometrics").then(({default:e})=>yt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Ze=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Ze);var ce=require("react-native");var Gt=e=>{var n,r,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("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 u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,l]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<a||c>l))throw new u("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${l} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},Xt=(e,t=()=>!0)=>new Promise((n,r)=>{let o=!1,i=(c,s)=>{o||(o=!0,clearTimeout(a),c?r(c):n(s))},a=setTimeout(()=>i(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),l=()=>o?!1:t()?!0:(i(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!l())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(l()){if(ce.Platform.OS==="android"){let s=ce.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=ce.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ce.PermissionsAndroid.check(s);if(!l())return;let y=g||await ce.PermissionsAndroid.check(d);if(!l())return;if(!g&&!y){let p=await ce.PermissionsAndroid.requestMultiple([s,d]);if(!l())return;if(p[s]!==ce.PermissionsAndroid.RESULTS.GRANTED&&p[d]!==ce.PermissionsAndroid.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}l()&&c.getCurrentPosition(s=>{l()&&i(void 0,s)},s=>{var g;if(!l())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";i(new u(d,s.message))},e)}})().catch(c=>i(c))});var St=require("react-native");var At=20,Qt=20,on=/^[a-z][a-z0-9_-]{0,31}$/,Or=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Cr=["low","medium","high"],ye=e=>!!e&&typeof e=="object"&&!Array.isArray(e),F=e=>new u("INVALID_PARAMS",e),je=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Zt=(e,t)=>{if(e===void 0)return{};if(!ye(e)||Object.keys(e).length>Qt||Object.values(e).some(n=>typeof n!="string"))throw F(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Qt} key)`);return e},sn=e=>{var n,r,o,i;if(e!==void 0&&!ye(e))throw F("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!on.test(t.source)))throw F("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!Or.test(a))))throw F("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!je(t.max_count,1,At))throw F(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${At}`);if(t.max_size!==void 0&&!je(t.max_size,1,Number.MAX_SAFE_INTEGER))throw F("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!je(t.concurrency,1,5))throw F("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(a=>a.toLowerCase()),max_count:(o=t.max_count)!=null?o:1,max_size:t.max_size,process:Tr(t.process),target:kr(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},Tr=e=>{if(e===void 0)return{};if(!ye(e))throw F("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!ye(n))throw F("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!je(n[r],1,1e4))throw F(`process.image.${r} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw F("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!ye(n))throw F("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!je(n.max_duration,1,3600))throw F("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Cr.includes(n.quality))throw F("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},kr=e=>{var n,r,o,i;if(e===void 0)return{target:"host",params:{}};if(!ye(e))throw F("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!on.test(t))throw F("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!ye(e.params))throw F("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw F("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw F(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Zt(e.headers,"upload.headers"),form_data:Zt(e.form_data,"upload.form_data"),field_name:(o=e.field_name)!=null?o:"file",url_field:(i=e.url_field)!=null?i:"url"}},an=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Ir=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=an(e.name);return t.some(o=>o==="*/*"?!0:o.startsWith(".")?o===r:o.endsWith("/*")?n.startsWith(o.slice(0,-1)):n===o)},Lr=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},Be,Dr=()=>(Be!=null||(Be=import("react-native-image-picker").catch(e=>{throw Be=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Be),en=e=>async({accept:t,max_count:n,process:r})=>{var c,s,d,g,y,p,f,T,v;let o=await Dr(),i=Lr(t),a={mediaType:i==="image"?"photo":i,maxWidth:(c=r.image)==null?void 0:c.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(p=(y=r.video)==null?void 0:y.quality)!=null?p:"medium",durationLimit:(f=r.video)==null?void 0:f.max_duration,assetRepresentationMode:"compatible"},l=e==="camera"?await o.launchCamera({...a,saveToPhotos:!1}):await o.launchImageLibrary({...a,selectionLimit:n});if(l.didCancel)return[];if(l.errorCode){let _=l.errorCode==="permission"?"PERMISSION_DENIED":l.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(_,(T=l.errorMessage)!=null?T:l.errorCode)}return((v=l.assets)!=null?v:[]).filter(_=>_.uri).map((_,b)=>{var w,z,ne;return{uri:_.uri,name:(w=_.fileName)!=null?w:`file_${b+1}`,mime_type:(z=_.type)!=null?z:"application/octet-stream",size:_.fileSize,width:_.width,height:_.height,duration:_.duration,processed:!((ne=_.type)!=null&&ne.startsWith("video/"))||St.Platform.OS==="ios"}})},Nr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Ur={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Fr=e=>async({accept:t,max_count:n})=>{var i,a,l,c;let r=t.map(s=>{var d;return(d=Nr[s])!=null?d:Ur[s]}),o=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:o,allowMultiSelection:n>1,mode:"import"})).filter(p=>p.uri&&!p.error).map((p,f)=>{var T,v,_;return{uri:p.uri,name:(T=p.name)!=null?T:`file_${f+1}`,mime_type:(v=p.type)!=null?v:"application/octet-stream",size:(_=p.size)!=null?_:void 0}});if(St.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(p=>p.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(p=>({uri:p.uri,fileName:p.name})),destination:"cachesDirectory"}),y=new Map(g.map(p=>[p.sourceUri,p.status==="success"?p.localUri:void 0]));return d.map(p=>{var f;return{...p,uri:(f=y.get(p.uri))!=null?f:p.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((c=(l=e.errorCodes)==null?void 0:l.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},qe,$r=async e=>(qe!=null||(qe=import("@react-native-documents/picker").then(t=>Fr(t)).catch(t=>{throw qe=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await qe)(e)),cn={library:en("library"),camera:en("camera"),document:$r},tn={type:"image",label:"\u1EA2nh",accept:["image/*"]},nn={type:"video",label:"Video",accept:["video/*"]},rn={library:[tn,nn],camera:[tn,nn],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},Ve,ln=()=>(Ve!=null||(Ve=import("react-native-compressor").catch(()=>(Ve=void 0,null))),Ve),pn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Br=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),qr={low:640,medium:1280,high:1920},Vr=async(e,{image:t})=>{var r;if(!t||!Br.has(e.mime_type.toLowerCase()))return e;let n=await ln();if(!n)return e;try{let o=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:o,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await pn(n,o,e.size),processed:!0}}catch{return e}},jr=async(e,{video:t})=>{var r;let n=await ln();if(!n)return e;try{let o=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:qr[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:o,mime_type:"video/mp4",size:await pn(n,o,e.size),processed:!0}}catch{return e}},zr={image:Vr,video:jr},Hr=(e,t)=>t.split(".").reduce((n,r)=>ye(n)?n[r]:void 0,e),bt=({file:e,target:t,onProgress:n,signal:r})=>new Promise((o,i)=>{if(t.target!=="url"||!("url"in t)){i(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(r.aborted){i(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let l=new XMLHttpRequest,c=new FormData;Object.entries(a.form_data).forEach(([g,y])=>c.append(g,y)),c.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>l.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};l.open("POST",a.url),Object.entries(a.headers).forEach(([g,y])=>l.setRequestHeader(g,y)),l.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),l.onload=()=>d(()=>{let g=l.responseText;try{g=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){i(new u("UPLOAD_FAILED",`HTTP ${l.status}`));return}let y=Hr(g,a.url_field);if(typeof y!="string"||!y){i(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}o({url:y,response:g})}),l.onerror=()=>d(()=>i(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),l.onabort=()=>d(()=>i(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),l.send(c)}),un=e=>{var r,o;let t={...cn};for(let[i,a]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))a?t[i]=a:delete t[i];let n={url:bt};for(let[i,a]of Object.entries((o=e==null?void 0:e.targets)!=null?o:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},dn=e=>{let{sources:t,targets:n}=un(e),r=Object.keys(t),o=Object.fromEntries(r.filter(i=>t[i]===cn[i]&&rn[i]).map(i=>[i,rn[i]]));return{sources:r,file_types:o,targets:Object.keys(n),max_count:At}},tt=new Map,gn=(e,t)=>`${e}:${t}`,Wr=0,mn=(e,t)=>{var n;typeof t=="string"&&((n=tt.get(gn(e,t)))==null||n.abort())},Ee=e=>{for(let[t,n]of tt)t.startsWith(`${e}:`)&&n.abort()},et=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Jr=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},fn=async(e,t)=>{var c;let{sources:n,targets:r}=un(t.config),o=n[e.source];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=r[e.target.target];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,l=gn(t.instance_id,(c=t.task_id)!=null?c:`auto-${++Wr}`);tt.set(l,a);try{return await Yr(e,t,o,i,a.signal)}finally{tt.delete(l)}},Yr=async(e,{instance_id:t,app_id:n,getContext:r,task_id:o,config:i,emit:a,exclusivePick:l=g=>g()},c,s,d)=>{var h,M,V;let g={app_id:n!=null?n:"",instance_id:t,context:{...(h=r==null?void 0:r())!=null?h:{}}},y=(await l(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw et();if(!y.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let p=[],f=y.filter(P=>Ir(P,e.accept)?!0:(p.push({name:P.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${P.mime_type||an(P.name)}`}),!1)),T=f.map(()=>0),v=f.map(P=>{var D;return(D=P.size)!=null?D:0}),_=0,b=0,w=(P=!1)=>{if(!a||!o)return;let D=Date.now();if(!P&&D-b<200)return;b=D;let B=v.reduce((I,X)=>I+X,0),j=T.reduce((I,X)=>I+X,0);a("upload.progress",{task_id:o,loaded:j,total:B,percent:B?Math.min(100,Math.round(j/B*100)):0,done_count:_,count:f.length})},z=[],ne=0,ae=async()=>{var P,D,B;for(;ne<f.length;){let j=ne++,I=f[j];try{if(d.aborted)throw et();let X=I.mime_type.startsWith("image/")?"image":I.mime_type.startsWith("video/")?"video":void 0,Ue=X&&!I.processed?(D=(P=i==null?void 0:i.processors)==null?void 0:P[X])!=null?D:zr[X]:void 0;if(Ue&&(I=await Ue(I,e.process),v[j]=(B=I.size)!=null?B:v[j],d.aborted))throw et();if(e.max_size&&I.size&&I.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${I.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let ve=(Te,$e)=>{T[j]=Te,$e&&(v[j]=$e),w()},re=await s({file:I,target:e.target,onProgress:ve,signal:d,caller:g});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Fe,...Ce}=re;z[j]={url:Fe,name:I.name,mime_type:I.mime_type,size:I.size,width:I.width,height:I.height,duration:I.duration,...Object.keys(Ce).length?{response:"response"in Ce?Ce.response:Ce}:{}},T[j]=v[j]}catch(X){p.push(Jr(f[j].name,X))}finally{_++,w(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,f.length)},ae)),d.aborted)throw et();let Me=z.filter(P=>!!P);if(!Me.length){let P=p[0];throw new u((M=P==null?void 0:P.code)!=null?M:"UPLOAD_FAILED",(V=P==null?void 0:P.message)!=null?V:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:Me,failed:p}};var bn=require("react-native");var Pe=require("react-native");var ee,hn=()=>Pe.Platform.OS==="android"&&!!(ee!=null&&ee.requesting_permission),Kr=1500,vt=()=>new Promise(e=>{if(Pe.Platform.OS!=="android"||Pe.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),r.remove(),e()},n=setTimeout(t,Kr),r=Pe.AppState.addEventListener("change",o=>{o==="active"&&t()})}),Mt=e=>{var t;if(ee===e&&(ee=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Pe.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},yn=async(e,t,n,r=()=>!0)=>{var i,a,l,c,s;if(ee)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};ee=o;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(o.native=g,o.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.requesting_permission=!0;let y;try{y=await g.requestPermissionsAsync()}finally{o.requesting_permission=!1}if(await vt(),o.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("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 u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(g.addListener("result",p=>{var f,T;ee!==o||o.cancelled||n(p.isFinal?"speech.final":"speech.partial",{...p,text:(T=(f=p.results[0])==null?void 0:f.transcript)!=null?T:""})}),g.addListener("error",p=>{ee===o&&!o.cancelled&&n("speech.error",{...p,code:p.error})}),g.addListener("end",()=>{ee===o&&(Mt(o),n("speech.end"))})),o.started=!0,g.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(l=t.interimResults)!=null?l:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Mt(o),d}},wn=e=>{let t=ee;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},le=e=>{let t=ee;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Mt(t)}};var nt=require("react"),ke=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(i=>i())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},W=(e,t,n=Object.is)=>{let r=(0,nt.useRef)(null),o=()=>{let i=e.getState(),a=r.current;if(a&&a.state===i&&a.selector===t)return a.value;let l=t(i),c=a&&n(a.value,l)?a.value:l;return r.current={state:i,selector:t,value:c},c};return(0,nt.useSyncExternalStore)(e.subscribe,o)};var An={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},rt={...An,all:Object.values(An)},Ie={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},ot={result:"scanner.result",end:"scanner.end"},Re={user:"user",web:"web",closed:"closed",error:"error"},ge={once:"once",continuous:"continuous"},Gr=1500,Sn=6e4,U,pe=ke({active:null,last_value:null,hit_tick:0}),Mn=()=>bn.Platform.OS==="android"&&!!(U!=null&&U.requesting_permission),_t=e=>{let{types:t,cooldown_ms:n}=e!=null?e:{},r={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(o=>rt.all.includes(o)))throw new u("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");r.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Sn)throw new u("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Sn}`);r.cooldown_ms=n}return r},xt=e=>U!==e?!1:(U=void 0,pe.setState({active:null,last_value:null}),!0),vn=async(e,t)=>{if(U)throw new u("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");U=e;let n=()=>{if(e.cancelled||!t())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let r;try{r=await import("react-native-vision-camera")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n(),e.requesting_permission=!0;let o;try{o=await r.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await vt(),n(),o!=="granted")throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera");if(!r.Camera.getAvailableCameraDevices().some(i=>i.position==="back"))throw new u("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");pe.setState({active:{owner:e.owner,mode:e.mode,types:e.types,vision:r},last_value:null})}catch(r){throw xt(e),r}},_n=(e,t,n)=>{var r,o;return{owner:e,mode:t,types:(r=n.types)!=null?r:rt.all,cooldown_ms:(o=n.cooldown_ms)!=null?o:Gr,cancelled:!1,requesting_permission:!1,last_seen:new Map}},xn=(e,t,n=()=>!0,r)=>new Promise((o,i)=>{let a=_n(e,ge.once,t);a.onHit=r,a.resolve=o,a.reject=i,vn(a,n).catch(i)}),En=(e,t,n,r=()=>!0,o)=>{let i=_n(e,ge.continuous,t);return i.emit=n,i.onHit=o,vn(i,r)},it=(e,t,n)=>{var r,o;if(!pe.getState().active){e.cancelled=!0;return}if(xt(e)){if(e.mode===ge.once){(r=e.reject)==null||r.call(e,t===Re.error?new u("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new u("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(o=e.emit)==null||o.call(e,ot.end,n?{reason:t,message:n}:{reason:t})}},Pn=e=>{(U==null?void 0:U.owner)===e&&it(U,Re.web)},we=e=>{(U==null?void 0:U.owner)===e&&it(U,Re.closed)},Et=()=>{U&&it(U,Re.user)},Rn=e=>{U&&it(U,Re.error,e)},On=(e,t=Date.now())=>{var r,o,i;let n=U;if(!(!n||!pe.getState().active))for(let{value:a,type:l}of e){if(!a)continue;let c=n.last_seen.get(a);if(!(c!==void 0&&t-c<n.cooldown_ms)){if(n.last_seen.set(a,t),(r=n.onHit)==null||r.call(n),n.mode===ge.once){xt(n),(o=n.resolve)==null||o.call(n,{value:a,type:l});return}pe.setState(s=>({last_value:a,hit_tick:s.hit_tick+1})),(i=n.emit)==null||i.call(n,ot.result,{value:a,type:l})}}};var at=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Cn=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===at&&typeof t.method=="string"?t:null}catch{return null}},We=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Tn=(e,t)=>We({id:e,result:t}),kn=(e,t)=>We({id:e,error:{code:t.code,message:t.message}}),In=(e,t)=>We({event:e,data:t}),Rt=e=>We({event:"context",data:e});var Ln=()=>`(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: ${We}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${at}, 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;`,sn=()=>`(function () {
22
+ })(); true;`,Dn=()=>`(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: ${We}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${at}, 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,7 +38,7 @@
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;`,an=()=>`(function () {
41
+ })(); true;`,Nn=()=>`(function () {
42
42
  if (window.__retionSafeAreaFrozen) { return; }
43
43
  window.__retionSafeAreaFrozen = true;
44
44
  var max = {};
@@ -59,8 +59,8 @@
59
59
  },
60
60
  });
61
61
  };
62
- })(); true;`,cn=e=>Ie({event:e}),pn=(e,t)=>{let n=ln(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${ut(e)}`},ln=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),un=(e,t={})=>{let n=ln(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${We} };
62
+ })(); true;`,Un=e=>We({event:e}),Fn=(e,t)=>{let n=$n(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${Rt(e)}`},$n=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Bn=(e,t={})=>{let n=$n(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${at} };
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
66
- true;`},dn={partner:"partner_token",chatbox:"chatbox_token"},gn=(e,t)=>{let n={...e};for(let i of Object.values(dn))t.includes(i)||delete n[i];return n},lt=new Set,Te=async(e,t)=>{if(lt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);lt.add(e);try{return await t()}finally{lt.delete(e)}},vi=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ze=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},mn=async({method:e,params:t},{getHostData:n,getPermissions:i,getContext:r,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var T,_,b,f,L,G,$,Se,ce;let y=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let A=It(t);return Te(e,()=>kt(A,g))}case"speech.start":{if(!d)throw h();let A={};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 u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");A.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 u("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);A[S]=t[S]}return Xt(a,A,d,g)}case"speech.stop":return Zt(a);case"uploadFiles":{let{task_id:A,...S}=t!=null?t:{};if(A!==void 0&&(typeof A!="string"||!A))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Gt(qt(S),{instance_id:a,app_id:p,getContext:r,task_id:A,config:s==null?void 0:s.upload,emit:d,exclusivePick:z=>Te("uploadFiles.pick",z)})}case"uploadFiles.cancel":Yt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Jt(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await ot()).getAvailability();case"authenticateBiometric":{let A=ze(t==null?void 0:t.reason,"reason").trim();if(!A||A.length>200)throw new u("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 u("INVALID_PARAMS","Invalid cancelButtonText");return Te(e,async()=>{var v;return((v=s==null?void 0:s.biometrics)!=null?v:await ot()).authenticate({reason:A,cancelButtonText:S})})}case"requestPayment":{let A=y==null?void 0:y.requestPayment;if(!A)throw h();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:ze(t==null?void 0:t.currency,"currency")};return Te(e,()=>A(z,l))}case"printImage":{let A=y==null?void 0:y.printImage;if(!A)throw h();let S=ze(t==null?void 0:t.image,"image");await Te(e,()=>A({image:S},l));return}case"openScreen":if(!(y!=null&&y.openScreen))throw h();await y.openScreen({screen:ze(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let A=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(A))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(A):Ce.Linking.openURL(A));return}case"openLink":{let A=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(A)||/^(javascript|file|data|about|blob):/i.test(A))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(A):Ce.Linking.openURL(A))}catch(S){throw new u("NOT_SUPPORTED",String((L=(f=S==null?void 0:S.message)!=null?f:S)!=null?L:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":($=s==null?void 0:s.showToast)==null||$.call(s,String((G=t==null?void 0:t.message)!=null?G:""));return;case"haptic":{let A=vi.has(t==null?void 0:t.type)?t.type:"selection";(Se=s==null?void 0:s.haptic)==null||Se.call(s,A);return}case"getSystemInfo":return{platform:Ce.Platform.OS==="ios"?"ios":"android",appVersion:(ce=s==null?void 0:s.app_version)!=null?ce:"",theme:o?"dark":"light"};case"getAccessToken":{let A=n().access_token;if(!A)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return A}case"getToken":{let A=t==null?void 0:t.type;if(A==="access"){let v=n().access_token;if(!v)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return v}if(A!=="partner"&&A!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(A)}`);let S=dn[A];if(!i().includes(S))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=A==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let A=n().user;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return A}case"getPageInfo":{let A=n().page;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return A}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var gt=e=>`bundle:${e}`,mt=()=>`${I().file_system.document_dir}/miniapps`,ft=mt,ht=(e,t,n="index.html",i=!1,r=[])=>{let o=`${ft()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:i,permissions:r}},dt=e=>{var t;I().storage.setString(gt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Si=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,R=e=>{let t=I().storage.getString(gt(e));if(!t)return null;try{let{version:n,entry:i,context_update:r,permissions:o}=JSON.parse(t);return ht(e,n,i,!!r,Array.isArray(o)?o:[])}catch{return null}},se=e=>I().file_system.exists(e.entry_uri.replace("file://","")),yt=async e=>{let t=R(e.app_id);return(t==null?void 0:t.version)===e.version&&await se(t)},hn=async(e,t)=>{let n=I().file_system,i=`${ft()}/${e}`,r=await n.listDir(i).catch(()=>[]);await Promise.all(r.filter(o=>!t.includes(o)).map(o=>n.remove(`${i}/${o}`).catch(()=>{})))},yn=async e=>{var t;await((t=Le[e])==null?void 0:t.catch(()=>{})),I().storage.setString(gt(e),""),await I().file_system.remove(`${ft()}/${e}`).catch(()=>{})},_e=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Le={},An=(e,t)=>{var o;let i=((o=Le[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),r=i.catch(()=>{});return Le[e]=r,r.then(()=>{Le[e]===r&&delete Le[e]}),i},_i=(e,t)=>{var r,o;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let p=((r=n[c])!=null?r:0)-((o=i[c])!=null?o:0);if(p)return p}return 0},wn=({manifest:e,zip_path:t})=>An(e.app_id,async()=>{var o;let n=I().file_system,i=R(e.app_id);if(i&&_i(i.version,e.version)>=0&&await se(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=ht(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),dt(e),J("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),hn(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),r}),At=(e,{base_url:t,onProgress:n}={})=>{let i=I().file_system,r=null,o=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new _e},a=async()=>{var g;p();let s=R(e.app_id);if((s==null?void 0:s.version)===e.version&&await i.exists(s.dir))return dt(e),R(e.app_id);p();let d=i.download({url:t?Si(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(y,l)=>{var T;let h=l>0?l:(T=e.size)!=null?T:0;h>0&&(n==null||n(Math.min(1,y/h)))}});r=d;try{let{status:y}=await d.promise;if(p(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else J("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ht(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await i.remove(l.dir).catch(()=>{}),await i.mkdir(l.dir),await i.unzip(c,l.dir),dt(e),hn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(y){throw o?new _e:y}finally{r=null,i.remove(c).catch(()=>{})}};return{promise:An(e.app_id,a),cancel:()=>{o=!0,r==null||r.cancel()}}},ke={},bi=__DEV__?0:60*1e3,fn={},Mn=(e,t)=>{var i,r;let n=R(e);return n&&Date.now()-((i=fn[t])!=null?i:0)<bi?Promise.resolve(n):((r=ke[e])!=null||(ke[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await At(c,{base_url:t}).promise;return fn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),R(e))).finally(()=>{ke[e]=void 0})),ke[e])};var He=new Map,vn=(e,t)=>(He.set(e,t),()=>{He.get(e)===t&&He.delete(e)}),Sn=(e,t)=>{let n=He.get(e);return n?n(t):!1};var Je=require("react"),Ke=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let r=typeof i=="function"?i(t):i;t={...t,...r},n.forEach(o=>o())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},ne=(e,t,n=Object.is)=>{let i=(0,Je.useRef)(null),r=()=>{let o=e.getState(),c=i.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return i.current={state:o,selector:t,value:a},a};return(0,Je.useSyncExternalStore)(e.subscribe,r)};var V=Ke({active_key:null,instances:{}}),_n=({app:e,instance_id:t,context:n={},url_params:i={},host_data:r={}},o)=>{var p;let c=(p=I().keep_alive)==null?void 0:p.max_webviews;V.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:i,host_data:r,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(y=>y!==s).sort((y,l)=>d[y].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(y=>{delete d[y]}),o?{active_key:s,instances:d}:{instances:d}})},bn=e=>_n(e,!0),xn=e=>_n(e,!1),be=()=>V.setState({active_key:null}),Ye=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var En="catalog",xi="paused_apps",Ei="removed_apps",Pi=10*1e3,Ri=2,Oi=3e3,Ti=()=>{var e;try{return JSON.parse((e=I().storage.getString(En))!=null?e:"{}")}catch{return{}}},P=Ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Pn=e=>{var t;return!!((t=I().manual_update)!=null&&t.includes(e))},Xe=new Set,Rn=e=>{let t=new Set,n=()=>I().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let r=JSON.parse((i=I().storage.getString(e))!=null?i:"[]");Array.isArray(r)&&r.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Z=Rn(xi),fe=Rn(Ei);Ot(()=>{Z.load(),fe.load();let e=Ti(),t={};Object.keys(e).filter(n=>!fe.has(n)).forEach(n=>{let i=R(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:Z.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),P.setState({catalog:e,downloads:t})});var Ze=e=>ne(P,t=>e?t.downloads[e]:void 0),On=()=>ne(P,e=>e.pause_reasons.length>0),X=(...e)=>J("queue",...e),N=[],ae={},x=null,Ge=new Set,ve={},wt=new Set,ge=e=>{wt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Tn=e=>(wt.add(e),()=>{wt.delete(e)}),Cn=()=>P.getState().downloads,j=(e,t)=>{let n=!!R(e),i=P.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,o={...i!=null?i:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};P.setState(c=>({downloads:{...c.downloads,[e]:o}})),(i==null?void 0:i.status)!==o.status||(i==null?void 0:i.version)!==o.version||(i==null?void 0:i.has_local)!==o.has_local?ge({type:"status_change",app_id:e,state:o}):i.progress!==o.progress&&ge({type:"progress",app_id:e,progress:o.progress,version:o.version})},Qe=(e,t)=>{var n;(n=ve[e])==null||n.forEach(i=>i(t)),delete ve[e]},Ci=()=>P.getState().pause_reasons.length>0,me=e=>{var p;if(x)return;let t=e?N.indexOf(e):Ci()?-1:N.findIndex(a=>!Z.has(a));if(t<0||t>=N.length)return;let[n]=N.splice(t,1),i=P.getState().catalog[n];if(!i){Qe(n,R(n)),me();return}let r=Date.now();ae[n]=((p=ae[n])!=null?p:0)+1,j(n,{status:"downloading",progress:0,version:i.version,error:void 0});let o=0,c=At(i,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,j(n,{progress:s/100,version:i.version}))}});x={app_id:n,handle:c,forced:!!e},X("start",n,i.version,e?"(forced)":""),c.promise.then(a=>{X("installed",n,i.version,`${Date.now()-r}ms`),j(n,{status:"installed",progress:1,version:i.version}),Qe(n,a)}).catch(a=>{var d;if(a instanceof _e){if(Ge.has(n))return;X("paused",n),ae[n]-=1,N.unshift(n),j(n,{status:Z.has(n)?"paused":"queued",progress:0,version:i.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),ae[n]<Ri){j(n,{status:"queued",progress:0,version:i.version,error:s}),setTimeout(()=>{var g;N.includes(n)||(x==null?void 0:x.app_id)===n||(N.push(n),me((g=ve[n])!=null&&g.length?n:void 0))},Oi);return}j(n,{status:"failed",progress:0,version:i.version,error:s}),Qe(n,R(n))}).finally(()=>{x=null;let a=N.find(s=>{var d;return(d=ve[s])==null?void 0:d.length});me(a)})},et=(e,{front:t=!1}={})=>{if((x==null?void 0:x.app_id)===e)return;let n=N.indexOf(e);if(n>=0){if(!t)return;N.splice(n,1)}t?N.unshift(e):N.push(e)},Ii=async e=>{let{host_id:t,client_token:n}=I(),i=new AbortController,r=setTimeout(()=>i.abort(),Pi);try{let o=`${Be}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(r)}},De=null,tt=()=>(De!=null||(De=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(I().channels.map(Ii)),i={};[...n].reverse().flat().forEach(a=>{i[a.app_id]=a});let r=Object.keys(P.getState().catalog).filter(a=>!i[a]);I().storage.setString(En,JSON.stringify(i)),P.setState({catalog:i}),await Promise.all(r.map(a=>In(a,{by_user:!1}))),r.forEach(a=>fe.delete(a));let o=Object.keys(i).filter(a=>!fe.has(a)),c=[],p={};for(let a of o.map(s=>i[s])){if(await yt(a)){j(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=R(a.app_id);if(Pn(a.app_id)&&!Xe.has(a.app_id)&&s&&await se(s)){j(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return P.setState({updates:p}),c.forEach(a=>{ae[a.app_id]=0,j(a.app_id,{status:Z.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),et(a.app_id)}),X("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",r,`${Date.now()-e}ms`),ge({type:"sync_complete",app_ids:o,removed:r}),Object.values(p).forEach(a=>ge({type:"update_available",...a})),me(),{ok:!0,app_ids:o,removed:r}}catch(n){let i=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",i),ge({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{De=null}})()),De),In=async(e,{by_user:t})=>{var r,o,c,p;if(t&&fe.add(e),Ge.has(e))return;Ge.add(e),Z.delete(e);let n=N.indexOf(e);n>=0&&N.splice(n,1),(x==null?void 0:x.app_id)===e&&x.handle.cancel();let i=(p=(c=(r=P.getState().downloads[e])==null?void 0:r.version)!=null?c:(o=R(e))==null?void 0:o.version)!=null?p:"";j(e,{status:"uninstalling",progress:0,version:i}),await yn(e),Ye(e),P.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete ae[e],Ge.delete(e),Qe(e,null),X("uninstalled",e,t?"(user)":"(not in list)"),ge({type:"uninstalled",app_id:e})},kn=e=>In(e,{by_user:!0}),Ln=e=>{let t=xe(e);return t?(fe.delete(e),(x==null?void 0:x.app_id)===e||N.includes(e)||(ae[e]=0,j(e,{status:Z.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),et(e),me(),X("restore",e)),!0):!1},Dn=e=>{if(Z.has(e))return;if(Z.add(e),X("pause app",e),(x==null?void 0:x.app_id)===e&&!x.forced){x.handle.cancel();return}let t=P.getState().downloads[e];N.includes(e)&&t&&j(e,{status:"paused",progress:0,version:t.version})},Un=e=>{if(!Z.delete(e))return;X("resume app",e);let t=P.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!N.includes(e)&&xe(e)&&(ae[e]=0,et(e)),N.includes(e)&&t&&j(e,{status:"queued",progress:0,version:t.version}),me()},Nn=e=>{let{pause_reasons:t}=P.getState();t.includes(e)||(P.setState({pause_reasons:[...t,e]}),X("pause",e),t.length===0&&ge({type:"pause_change",paused:!0,reasons:[e]}),x&&!x.forced&&x.handle.cancel())},Fn=e=>{let{pause_reasons:t}=P.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);P.setState({pause_reasons:n}),X("resume",e),n.length===0&&ge({type:"pause_change",paused:!1,reasons:n}),me()},Mt=e=>P.getState().updates[e],$n=async e=>{var n,i;let t=Mt(e);Xe.add(e);try{let r=await Ue(e),o=(i=t==null?void 0:t.next_version)!=null?i:(n=xe(e))==null?void 0:n.version;return!r||!o||r.version!==o?!1:(P.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),X("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Xe.delete(e)}},Bn=()=>Object.values(P.getState().catalog).map(e=>({...e,installed:!!R(e.app_id),removed_by_user:fe.has(e.app_id)})),xe=e=>P.getState().catalog[e],Ue=async e=>{let t=xe(e);if(!t)return;if(Z.delete(e),fe.delete(e),await yt(t))return R(e);let n=R(e);if(Pn(e)&&!Xe.has(e)&&n&&await se(n))return n;let i=new Promise(r=>{var o;((o=ve[e])!=null?o:ve[e]=[]).push(r)});return(x==null?void 0:x.app_id)===e?x.forced=!0:(ae[e]=0,et(e,{front:!0}),x&&!x.forced?x.handle.cancel():me(e)),i};var O=require("react/jsx-runtime"),vt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),qn=0,ki=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Li=w.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:r,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=(0,w.useRef)(null),y=(0,w.useRef)(!1),l=ne(V,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,T=l==null?void 0:l.app.manifest_url,_=l==null?void 0:l.context,b=l==null?void 0:l.url_params,[f,L]=(0,w.useState)(()=>h?R(h):null),[G,$]=(0,w.useState)(!1),[Se,ce]=(0,w.useState)(0),[A,S]=(0,w.useState)(0),[z,v]=(0,w.useState)(!1),D=(0,w.useRef)(null),ie=m=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,v(!0)},m)};(0,w.useEffect)(()=>()=>{D.current&&clearTimeout(D.current)},[]),(0,w.useEffect)(()=>{if(!h||!t&&f)return;let m=!0;return $(!1),(async()=>{let M=R(h),q=M?await se(M):!1;if(!m||(L(q?Q=>!Q||Q.version!==M.version||Q.permissions.join(",")!==M.permissions.join(",")?M:Q:null),__DEV__&&Date.now()-qn>1e4&&(qn=Date.now(),await tt()),!m))return;let le=await Ue(h),ye=le!==void 0?le:T?await Mn(h,T):R(h);if(m){if(!ye){$(!0);return}L(Q=>Q!=null?Q:ye)}})(),()=>{m=!1}},[t,h,T,Se]),(0,w.useEffect)(()=>vn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let B=ne(P,m=>{let M=h?m.downloads[h]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});(0,w.useEffect)(()=>{if(t||!h||!f)return;let m=R(h);if(!m||m.version===f.version)return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),L(m))}),()=>{M=!1}},[t,h,B,f==null?void 0:f.version]);let C=ne(P,m=>{var M;return h&&(M=m.apply_ticks[h])!=null?M:0});(0,w.useEffect)(()=>{if(!C||!h)return;let m=R(h);if(!m||m.version===(f==null?void 0:f.version))return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),v(!1),L(m))}),()=>{M=!1}},[C]),(0,w.useEffect)(()=>{var q;let m=(q=I().keep_alive)==null?void 0:q.idle_close_ms;if(t||!m||m<=0)return;let M=setTimeout(()=>{Ye(e)},m);return()=>clearTimeout(M)},[t,e]),(0,w.useEffect)(()=>{r>0&&($(!1),v(!1),S(m=>m+1),ce(m=>m+1))},[r]);let W=(0,w.useRef)(t);(0,w.useEffect)(()=>{var m;W.current!==t&&(W.current=t,y.current&&((m=g.current)==null||m.injectJavaScript(cn(t?"resumed":"paused"))))},[t]);let pe=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${A}`,he=(0,w.useMemo)(()=>JSON.stringify([_!=null?_:{},b!=null?b:{}]),[_,b]),re=(0,w.useMemo)(()=>{var m;return gn(b!=null?b:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[he,f==null?void 0:f.permissions]),nt=(0,w.useMemo)(()=>un(_!=null?_:{},re)+sn()+(E.Platform.OS==="android"?an():"")+(I().debug?on():""),[re]),oe=(0,w.useRef)(null),Ne=(0,w.useRef)(null);(0,w.useEffect)(()=>{var M,q,le;if(!f)return;if(Ne.current!==pe){Ne.current=pe,oe.current=he;return}if(oe.current===he)return;let m=((q=JSON.parse((M=oe.current)!=null?M:"[]")[0])!=null?q:{}).org_id;if(oe.current=he,m===(_==null?void 0:_.org_id)&&y.current){v(!1),ie(1500),(le=g.current)==null||le.injectJavaScript(pn(_!=null?_:{},re));return}v(!1),S(ye=>ye+1)},[he,f,pe]),(0,w.useEffect)(()=>(t||(te(e),we(e)),()=>{te(e),we(e)}),[t,e,pe,r]),(0,w.useEffect)(()=>{let m=E.AppState.addEventListener("change",M=>{M==="background"&&!Qt()&&te(e)});return()=>m.remove()},[e]);let Fe=(0,w.useCallback)(async m=>{var q,le,ye,Q,it;let M=en(m.nativeEvent.data);if(!M){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(k=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,k)})}catch(k){console.warn("[miniapp] onWebEvent l\u1ED7i",h,k)}return}if(M.method==="log"){let{level:k,text:F}=M;J(`web:${e}`,k!=null?k:"log",F!=null?F:"");return}if(M.method==="pong"){D.current||v(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){D.current&&clearTimeout(D.current),D.current=null,v(!0);return}if(M.method==="ready"){y.current=!0,v(!0);let k=(q=V.getState().instances[e])==null?void 0:q.context;k&&((le=g.current)==null||le.injectJavaScript(ut(k)));return}try{let k=await mn(M,{getHostData:()=>{var F,H;return(H=(F=V.getState().instances[e])==null?void 0:F.host_data)!=null?H:{}},getPermissions:()=>{var F,H;return h?(H=(F=R(h))==null?void 0:F.permissions)!=null?H:[]:[]},getContext:()=>{var F,H;return(H=(F=V.getState().instances[e])==null?void 0:F.context)!=null?H:{}},is_dark:i,close:be,app_id:h!=null?h:"",instance_id:e,options:p,emit:(F,H)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(rn(F,H))},isActive:()=>V.getState().active_key===e&&E.AppState.currentState!=="background"});M.id&&((ye=g.current)==null||ye.injectJavaScript(tn(M.id,k)))}catch(k){if(!M.id)return;let F=k==null?void 0:k.code,H=k instanceof u?k:new u(typeof F=="string"?F:"HOST_ERROR",String((Q=k==null?void 0:k.message)!=null?Q:k));(it=g.current)==null||it.injectJavaScript(nn(M.id,H))}},[e,i,h,o,p]),Wn=(0,w.useCallback)(()=>{$(!1),S(m=>m+1),ce(m=>m+1)},[]);return(0,O.jsxs)(E.View,{style:[E.StyleSheet.absoluteFill,a&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&Y.behind],pointerEvents:t?"auto":"none",children:[f?(0,O.jsx)(jn.default,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,allowingReadAccessToURL:`file://${s?mt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:nt,onMessage:Fe,bounces:!1,overScrollMode:"never",onLoadStart:m=>{te(e),we(e),J(`webview:${e}`,"load start",vt(m.nativeEvent.url)),y.current=!1,v(!1)},onError:m=>{te(e),we(e),J(`webview:${e}`,"load error",vt(m.nativeEvent.url),m.nativeEvent.description),$(!0),v(!1)},onLoadEnd:m=>{let M=m.nativeEvent.url;J(`webview:${e}`,"load end",vt(M)),h&&(d==null||d({app_id:h,instance_id:e,url:M})),ie(1500)},onContentProcessDidTerminate:()=>{te(e),we(e),y.current=!1,v(!1),S(m=>m+1)},onRenderProcessGone:()=>(te(e),we(e),y.current=!1,v(!1),S(m=>m+1),!0),style:Y.webview},pe):null,l&&(0,O.jsx)(Ui,{visible:!f||!z,interactive:G,children:(0,O.jsx)(Di,{splash:c,app:l.app,is_dark:i,error:G,has_bundle:!!f,retry:Wn})})]})}),Di=w.default.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:r,retry:o})=>{let c=e,p=Ze(t.app_id),a=i?"error":!r&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,O.jsx)(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Ui=({visible:e,interactive:t,children:n})=>{let i=(0,w.useRef)(new E.Animated.Value(e?1:0)).current,[r,o]=(0,w.useState)(e);return(0,w.useEffect)(()=>{if(e){o(!0),i.setValue(1);return}let c=E.Animated.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,i]),r?(0,O.jsx)(E.Animated.View,{style:[E.StyleSheet.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},St=({app:e,is_dark:t,status:n,progress:i,retry:r})=>{let o=t?"#FAFAFA":"#18181B";return(0,O.jsxs)(E.View,{style:[Y.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,O.jsx)(E.View,{style:[Y.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,O.jsx)(E.Image,{source:{uri:e.icon},style:Y.splash_icon_image}):(0,O.jsx)(E.Text,{style:Y.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,O.jsx)(E.Text,{style:[Y.splash_name,{color:o}],children:e.name}),n==="error"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.Text,{style:Y.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,O.jsx)(E.TouchableOpacity,{activeOpacity:.7,style:[Y.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,O.jsx)(E.Text,{style:[Y.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.ActivityIndicator,{style:Y.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,O.jsxs)(E.Text,{style:Y.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},Vn=(e,t)=>{let n=(0,w.useRef)(t),i=(0,w.useRef)(!1);__DEV__&&!i.current&&n.current!==t&&(i.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.`))},Ni=({container:e,splash:t=St,is_dark:n=!1,bridge:i,close_on_back:r=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Vn("container",e),Vn("splash",t);let a=e,s=ne(V,f=>f.active_key),d=(0,w.useRef)(s);s&&(d.current=s);let g=ne(V,f=>Object.keys(f.instances).join("|")),y=ne(V,f=>{var L;return f.active_key?(L=f.instances[f.active_key])==null?void 0:L.app.name:void 0}),l=(0,w.useMemo)(()=>g?g.split("|"):[],[g]),[h,T]=(0,w.useState)({}),_=(0,w.useRef)(ki()).current;(0,w.useEffect)(()=>{if(!s||!r)return;let f=E.BackHandler.addEventListener("hardwareBackPress",()=>(be(),!0));return()=>f.remove()},[s,r]);let b=(0,w.useCallback)(()=>{let f=V.getState().active_key;f&&T(L=>({...L,[f]:(L[f]||0)+1}))},[]);return l.length?(0,O.jsx)(a,{visible:!!s,title:y!=null?y:"",is_dark:n,close:be,reload:b,subscribeWebAtTop:_.subscribe,children:l.map(f=>(0,O.jsx)(Li,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:_,splash:t,bridge:i,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},Y=E.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"}}),zn=w.default.memo(Ni);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,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
66
+ true;`},qn={partner:"partner_token",chatbox:"chatbox_token"},Vn=(e,t)=>{let n={...e};for(let r of Object.values(qn))t.includes(r)||delete n[r];return n},Pt=new Set,ze=async(e,t)=>{if(Pt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Pt.add(e);try{return await t()}finally{Pt.delete(e)}},Xr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),st=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},jn=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:o,is_dark:i,close:a,app_id:l,instance_id:c,options:s,emit:d,isActive:g})=>{var T,v,_,b,w,z,ne,ae,Me;let y=s==null?void 0:s.handlers,p={app_id:l,instance_id:c,close:a},f=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Gt(t);return ze(e,()=>Xt(h,g))}case"speech.start":{if(!d)throw f();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 u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let M of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[M])!==void 0){if(typeof t[M]!="boolean")throw new u("INVALID_PARAMS",`${M} ph\u1EA3i l\xE0 boolean`);h[M]=t[M]}return yn(c,h,d,g)}case"speech.stop":return wn(c);case Ie.scan:return xn(c,_t(t),g,()=>{var h;return(h=s==null?void 0:s.haptic)==null?void 0:h.call(s,"notificationSuccess")});case Ie.start:{if(!d)throw f();return En(c,_t(t),d,g,()=>{var h;return(h=s==null?void 0:s.haptic)==null?void 0:h.call(s,"notificationSuccess")})}case Ie.stop:return Pn(c);case"uploadFiles":{let{task_id:h,...M}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return fn(sn(M),{instance_id:c,app_id:l,getContext:o,task_id:h,config:s==null?void 0:s.upload,emit:d,exclusivePick:V=>ze("uploadFiles.pick",V)})}case"uploadFiles.cancel":mn(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return dn(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await wt()).getAvailability();case"authenticateBiometric":{let h=st(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let M=t==null?void 0:t.cancelButtonText;if(M!==void 0&&(typeof M!="string"||!M.trim()||M.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return ze(e,async()=>{var P;return((P=s==null?void 0:s.biometrics)!=null?P:await wt()).authenticate({reason:h,cancelButtonText:M})})}case"requestPayment":{let h=y==null?void 0:y.requestPayment;if(!h)throw f();let M=t==null?void 0:t.amount;if(typeof M!="number"||!Number.isFinite(M)||M<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let V={...t,amount:M,currency:st(t==null?void 0:t.currency,"currency")};return ze(e,()=>h(V,p))}case"printImage":{let h=y==null?void 0:y.printImage;if(!h)throw f();let M=st(t==null?void 0:t.image,"image");await ze(e,()=>h({image:M},p));return}case"openScreen":if(!(y!=null&&y.openScreen))throw f();await y.openScreen({screen:st(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},p);return;case"closeApp":a();return;case"openWebview":{let h=String((v=t==null?void 0:t.url)!=null?v:"");if(!/^https?:\/\//i.test(h))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(h):He.Linking.openURL(h));return}case"openLink":{let h=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(h):He.Linking.openURL(h))}catch(M){throw new u("NOT_SUPPORTED",String((w=(b=M==null?void 0:M.message)!=null?b:M)!=null?w:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(ne=s==null?void 0:s.showToast)==null||ne.call(s,String((z=t==null?void 0:t.message)!=null?z:""));return;case"haptic":{let h=Xr.has(t==null?void 0:t.type)?t.type:"selection";(ae=s==null?void 0:s.haptic)==null||ae.call(s,h);return}case"getSystemInfo":return{platform:He.Platform.OS==="ios"?"ios":"android",appVersion:(Me=s==null?void 0:s.app_version)!=null?Me:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new u("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 P=n().access_token;if(!P)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return P}if(h!=="partner"&&h!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let M=qn[h];if(!r().includes(M))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${M} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let V=h==="partner"?n().partner_token:n().chatbox_token;if(!V)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${M}`);return V}case"getUserInfo":{let h=n().user;if(!h)throw new u("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 u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Ct=e=>`bundle:${e}`,Tt=()=>`${k().file_system.document_dir}/miniapps`,kt=Tt,It=(e,t,n="index.html",r=!1,o=[])=>{let i=`${kt()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:r,permissions:o}},Ot=e=>{var t;k().storage.setString(Ct(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Qr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,C=e=>{let t=k().storage.getString(Ct(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:i}=JSON.parse(t);return It(e,n,r,!!o,Array.isArray(i)?i:[])}catch{return null}},me=e=>k().file_system.exists(e.entry_uri.replace("file://","")),Lt=async e=>{let t=C(e.app_id);return(t==null?void 0:t.version)===e.version&&await me(t)},Hn=async(e,t)=>{let n=k().file_system,r=`${kt()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(i=>!t.includes(i)).map(i=>n.remove(`${r}/${i}`).catch(()=>{})))},Wn=async e=>{var t;await((t=Ye[e])==null?void 0:t.catch(()=>{})),k().storage.setString(Ct(e),""),await k().file_system.remove(`${kt()}/${e}`).catch(()=>{})},Le=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Ye={},Jn=(e,t)=>{var i;let r=((i=Ye[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return Ye[e]=o,o.then(()=>{Ye[e]===o&&delete Ye[e]}),r},Zr=(e,t)=>{var o,i;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 l=((o=n[a])!=null?o:0)-((i=r[a])!=null?i:0);if(l)return l}return 0},Yn=({manifest:e,zip_path:t})=>Jn(e.app_id,async()=>{var i;let n=k().file_system,r=C(e.app_id);if(r&&Zr(r.version,e.version)>=0&&await me(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=It(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),Ot(e),Z("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Hn(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Dt=(e,{base_url:t,onProgress:n}={})=>{let r=k().file_system,o=null,i=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(i)throw new Le},c=async()=>{var g;l();let s=C(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return Ot(e),C(e.app_id);l();let d=r.download({url:t?Qr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,p)=>{var T;let f=p>0?p:(T=e.size)!=null?T:0;f>0&&(n==null||n(Math.min(1,y/f)))}});o=d;try{let{status:y}=await d.promise;if(l(),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 Z("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let p=It(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(p.dir).catch(()=>{}),await r.mkdir(p.dir),await r.unzip(a,p.dir),Ot(e),Hn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),p}catch(y){throw i?new Le:y}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Jn(e.app_id,c),cancel:()=>{i=!0,o==null||o.cancel()}}},Je={},eo=__DEV__?0:60*1e3,zn={},Kn=(e,t)=>{var r,o;let n=C(e);return n&&Date.now()-((r=zn[t])!=null?r:0)<eo?Promise.resolve(n):((o=Je[e])!=null||(Je[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),l=await Dt(a,{base_url:t}).promise;return zn[t]=Date.now(),l})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),C(e))).finally(()=>{Je[e]=void 0})),Je[e])};var ct=new Map,Gn=(e,t)=>(ct.set(e,t),()=>{ct.get(e)===t&&ct.delete(e)}),Xn=(e,t)=>{let n=ct.get(e);return n?n(t):!1};var ue=require("react"),N=require("react-native");var Y=require("react/jsx-runtime"),to="#22C55E",Nt=({scanner:e})=>{let{vision:t,types:n,mode:r}=e,o=t.useCameraDevice("back"),[i,a]=(0,ue.useState)(!1),l=W(pe,p=>p.last_value),c=W(pe,p=>p.hit_tick),s=(0,ue.useRef)(new N.Animated.Value(0)).current,d=t.useCodeScanner({codeTypes:n,onCodeScanned:(0,ue.useCallback)(p=>On(p),[])});(0,ue.useEffect)(()=>{let p=N.BackHandler.addEventListener("hardwareBackPress",()=>(Et(),!0));return()=>p.remove()},[]);let g=(0,ue.useRef)(c);(0,ue.useEffect)(()=>{if(c===g.current)return;s.setValue(1);let p=N.Animated.timing(s,{toValue:0,duration:350,useNativeDriver:!0});return p.start(),()=>p.stop()},[c,s]);let y=!!(o!=null&&o.hasTorch);return(0,Y.jsxs)(N.View,{style:r===ge.continuous?J.continuous:J.once,children:[o&&(0,Y.jsx)(t.Camera,{style:N.StyleSheet.absoluteFill,device:o,isActive:!0,codeScanner:d,torch:i&&y?"on":"off",onError:p=>Rn(p.message)}),(0,Y.jsxs)(N.View,{style:J.frame_wrap,pointerEvents:"none",children:[(0,Y.jsx)(N.View,{style:J.frame}),(0,Y.jsx)(N.Animated.View,{style:[J.frame,J.frame_hit,{opacity:s}]})]}),(0,Y.jsxs)(N.View,{style:J.footer,children:[(0,Y.jsx)(N.TouchableOpacity,{activeOpacity:.7,style:J.button,onPress:Et,accessibilityRole:"button",children:(0,Y.jsx)(N.Text,{style:J.button_text,children:"\u0110\xF3ng"})}),(0,Y.jsx)(N.Text,{style:J.last_value,numberOfLines:1,children:l!=null?l:""}),y&&(0,Y.jsx)(N.TouchableOpacity,{activeOpacity:.7,style:[J.button,i&&J.button_on],onPress:()=>a(p=>!p),accessibilityRole:"button",children:(0,Y.jsx)(N.Text,{style:[J.button_text,i&&J.button_text_on],children:"\u0110\xE8n"})})]})]})},J=N.StyleSheet.create({continuous:{height:"38%",backgroundColor:"#000000",overflow:"hidden"},once:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},frame_wrap:{position:"absolute",top:0,left:0,right:0,bottom:0,alignItems:"center",justifyContent:"center"},frame:{width:"70%",aspectRatio:1.6,maxHeight:"60%",borderRadius:12,borderWidth:2,borderColor:"rgba(255,255,255,0.8)"},frame_hit:{position:"absolute",borderWidth:4,borderColor:to},footer:{position:"absolute",left:12,right:12,bottom:12,flexDirection:"row",alignItems:"center",gap:8},last_value:{flex:1,textAlign:"center",color:"#FFFFFF",fontWeight:"600"},button:{paddingHorizontal:14,paddingVertical:8,borderRadius:999,backgroundColor:"rgba(0,0,0,0.6)"},button_on:{backgroundColor:"#FFFFFF"},button_text:{color:"#FFFFFF",fontWeight:"600"},button_text_on:{color:"#18181B"}});var K=ke({active_key:null,instances:{}}),Qn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},i)=>{var l;let a=(l=k().keep_alive)==null?void 0:l.max_webviews;K.setState(c=>{let s=t!=null?t:e.app_id,d={...c.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},g=Object.keys(d);return a&&a>0&&g.length>a&&g.filter(y=>y!==s).sort((y,p)=>d[y].last_used_at-d[p].last_used_at).slice(0,g.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},Zn=e=>Qn(e,!0),er=e=>Qn(e,!1),De=()=>K.setState({active_key:null}),lt=e=>{K.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var tr="catalog",no="paused_apps",ro="removed_apps",oo=10*1e3,io=2,so=3e3,ao=()=>{var e;try{return JSON.parse((e=k().storage.getString(tr))!=null?e:"{}")}catch{return{}}},O=ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),nr=e=>{var t;return!!((t=k().manual_update)!=null&&t.includes(e))},dt=new Set,rr=e=>{let t=new Set,n=()=>k().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=k().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},se=rr(no),be=rr(ro);Jt(()=>{se.load(),be.load();let e=ao(),t={};Object.keys(e).filter(n=>!be.has(n)).forEach(n=>{let r=C(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:se.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),O.setState({catalog:e,downloads:t})});var gt=e=>W(O,t=>e?t.downloads[e]:void 0),or=()=>W(O,e=>e.pause_reasons.length>0),ie=(...e)=>Z("queue",...e),$=[],fe={},x=null,pt=new Set,Oe={},Ut=new Set,Ae=e=>{Ut.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},ir=e=>(Ut.add(e),()=>{Ut.delete(e)}),sr=()=>O.getState().downloads,G=(e,t)=>{let n=!!C(e),r=O.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,i={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};O.setState(a=>({downloads:{...a.downloads,[e]:i}})),(r==null?void 0:r.status)!==i.status||(r==null?void 0:r.version)!==i.version||(r==null?void 0:r.has_local)!==i.has_local?Ae({type:"status_change",app_id:e,state:i}):r.progress!==i.progress&&Ae({type:"progress",app_id:e,progress:i.progress,version:i.version})},ut=(e,t)=>{var n;(n=Oe[e])==null||n.forEach(r=>r(t)),delete Oe[e]},co=()=>O.getState().pause_reasons.length>0,Se=e=>{var l;if(x)return;let t=e?$.indexOf(e):co()?-1:$.findIndex(c=>!se.has(c));if(t<0||t>=$.length)return;let[n]=$.splice(t,1),r=O.getState().catalog[n];if(!r){ut(n,C(n)),Se();return}let o=Date.now();fe[n]=((l=fe[n])!=null?l:0)+1,G(n,{status:"downloading",progress:0,version:r.version,error:void 0});let i=0,a=Dt(r,{onProgress:c=>{let s=Math.floor(c*100);s!==i&&(i=s,G(n,{progress:s/100,version:r.version}))}});x={app_id:n,handle:a,forced:!!e},ie("start",n,r.version,e?"(forced)":""),a.promise.then(c=>{ie("installed",n,r.version,`${Date.now()-o}ms`),G(n,{status:"installed",progress:1,version:r.version}),ut(n,c)}).catch(c=>{var d;if(c instanceof Le){if(pt.has(n))return;ie("paused",n),fe[n]-=1,$.unshift(n),G(n,{status:se.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=c==null?void 0:c.message)!=null?d:c);if(console.warn("[miniapp-queue] failed",n,s),fe[n]<io){G(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;$.includes(n)||(x==null?void 0:x.app_id)===n||($.push(n),Se((g=Oe[n])!=null&&g.length?n:void 0))},so);return}G(n,{status:"failed",progress:0,version:r.version,error:s}),ut(n,C(n))}).finally(()=>{x=null;let c=$.find(s=>{var d;return(d=Oe[s])==null?void 0:d.length});Se(c)})},mt=(e,{front:t=!1}={})=>{if((x==null?void 0:x.app_id)===e)return;let n=$.indexOf(e);if(n>=0){if(!t)return;$.splice(n,1)}t?$.unshift(e):$.push(e)},lo=async e=>{let{host_id:t,client_token:n}=k(),r=new AbortController,o=setTimeout(()=>r.abort(),oo);try{let i=`${Qe}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{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(c=>({...c,channel:e}))}finally{clearTimeout(o)}},Ke=null,ft=()=>(Ke!=null||(Ke=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(k().channels.map(lo)),r={};[...n].reverse().flat().forEach(c=>{r[c.app_id]=c});let o=Object.keys(O.getState().catalog).filter(c=>!r[c]);k().storage.setString(tr,JSON.stringify(r)),O.setState({catalog:r}),await Promise.all(o.map(c=>ar(c,{by_user:!1}))),o.forEach(c=>be.delete(c));let i=Object.keys(r).filter(c=>!be.has(c)),a=[],l={};for(let c of i.map(s=>r[s])){if(await Lt(c)){G(c.app_id,{status:"installed",progress:1,version:c.version});continue}let s=C(c.app_id);if(nr(c.app_id)&&!dt.has(c.app_id)&&s&&await me(s)){G(c.app_id,{status:"installed",progress:1,version:s.version}),l[c.app_id]={app_id:c.app_id,current_version:s.version,next_version:c.version};continue}a.push(c)}return O.setState({updates:l}),a.forEach(c=>{fe[c.app_id]=0,G(c.app_id,{status:se.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),mt(c.app_id)}),ie("catalog",i.length,"apps, outdated",a.map(c=>c.app_id),"removed",o,`${Date.now()-e}ms`),Ae({type:"sync_complete",app_ids:i,removed:o}),Object.values(l).forEach(c=>Ae({type:"update_available",...c})),Se(),{ok:!0,app_ids:i,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),Ae({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{Ke=null}})()),Ke),ar=async(e,{by_user:t})=>{var o,i,a,l;if(t&&be.add(e),pt.has(e))return;pt.add(e),se.delete(e);let n=$.indexOf(e);n>=0&&$.splice(n,1),(x==null?void 0:x.app_id)===e&&x.handle.cancel();let r=(l=(a=(o=O.getState().downloads[e])==null?void 0:o.version)!=null?a:(i=C(e))==null?void 0:i.version)!=null?l:"";G(e,{status:"uninstalling",progress:0,version:r}),await Wn(e),lt(e),O.setState(c=>{let s={...c.downloads};return delete s[e],{downloads:s}}),delete fe[e],pt.delete(e),ut(e,null),ie("uninstalled",e,t?"(user)":"(not in list)"),Ae({type:"uninstalled",app_id:e})},cr=e=>ar(e,{by_user:!0}),lr=e=>{let t=Ne(e);return t?(be.delete(e),(x==null?void 0:x.app_id)===e||$.includes(e)||(fe[e]=0,G(e,{status:se.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),mt(e),Se(),ie("restore",e)),!0):!1},pr=e=>{if(se.has(e))return;if(se.add(e),ie("pause app",e),(x==null?void 0:x.app_id)===e&&!x.forced){x.handle.cancel();return}let t=O.getState().downloads[e];$.includes(e)&&t&&G(e,{status:"paused",progress:0,version:t.version})},ur=e=>{if(!se.delete(e))return;ie("resume app",e);let t=O.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!$.includes(e)&&Ne(e)&&(fe[e]=0,mt(e)),$.includes(e)&&t&&G(e,{status:"queued",progress:0,version:t.version}),Se()},dr=e=>{let{pause_reasons:t}=O.getState();t.includes(e)||(O.setState({pause_reasons:[...t,e]}),ie("pause",e),t.length===0&&Ae({type:"pause_change",paused:!0,reasons:[e]}),x&&!x.forced&&x.handle.cancel())},gr=e=>{let{pause_reasons:t}=O.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);O.setState({pause_reasons:n}),ie("resume",e),n.length===0&&Ae({type:"pause_change",paused:!1,reasons:n}),Se()},Ft=e=>O.getState().updates[e],mr=async e=>{var n,r;let t=Ft(e);dt.add(e);try{let o=await Ge(e),i=(r=t==null?void 0:t.next_version)!=null?r:(n=Ne(e))==null?void 0:n.version;return!o||!i||o.version!==i?!1:(O.setState(a=>{var c;let l={...a.updates};return delete l[e],{updates:l,apply_ticks:{...a.apply_ticks,[e]:((c=a.apply_ticks[e])!=null?c:0)+1}}}),ie("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{dt.delete(e)}},fr=()=>Object.values(O.getState().catalog).map(e=>({...e,installed:!!C(e.app_id),removed_by_user:be.has(e.app_id)})),Ne=e=>O.getState().catalog[e],Ge=async e=>{let t=Ne(e);if(!t)return;if(se.delete(e),be.delete(e),await Lt(t))return C(e);let n=C(e);if(nr(e)&&!dt.has(e)&&n&&await me(n))return n;let r=new Promise(o=>{var i;((i=Oe[e])!=null?i:Oe[e]=[]).push(o)});return(x==null?void 0:x.app_id)===e?x.forced=!0:(fe[e]=0,mt(e,{front:!0}),x&&!x.forced?x.handle.cancel():Se(e)),r};var R=require("react/jsx-runtime"),$t=e=>(e!=null?e:"").replace(/\?[^#]*/,""),hr=0,po=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},uo=S.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:i,splash:a,bridge:l,opaque_background:c,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var qt,Vt;let g=(0,S.useRef)(null),y=(0,S.useRef)(!1),p=W(K,m=>m.instances[e]),f=p==null?void 0:p.app.app_id,T=p==null?void 0:p.app.manifest_url,v=p==null?void 0:p.context,_=p==null?void 0:p.url_params,b=W(pe,m=>{var A;return((A=m.active)==null?void 0:A.owner)===e?m.active:null}),[w,z]=(0,S.useState)(()=>f?C(f):null),[ne,ae]=(0,S.useState)(!1),[Me,h]=(0,S.useState)(0),[M,V]=(0,S.useState)(0),[P,D]=(0,S.useState)(!1),B=(0,S.useRef)(null),j=m=>{B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{B.current=null,D(!0)},m)};(0,S.useEffect)(()=>()=>{B.current&&clearTimeout(B.current)},[]),(0,S.useEffect)(()=>{if(!f||!t&&w)return;let m=!0;return ae(!1),(async()=>{let A=C(f),H=A?await me(A):!1;if(!m||(z(H?oe=>!oe||oe.version!==A.version||oe.permissions.join(",")!==A.permissions.join(",")?A:oe:null),__DEV__&&Date.now()-hr>1e4&&(hr=Date.now(),await ft()),!m))return;let he=await Ge(f),_e=he!==void 0?he:T?await Kn(f,T):C(f);if(m){if(!_e){ae(!0);return}z(oe=>oe!=null?oe:_e)}})(),()=>{m=!1}},[t,f,T,Me]),(0,S.useEffect)(()=>Gn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let I=W(O,m=>{let A=f?m.downloads[f]:void 0;return(A==null?void 0:A.status)==="installed"?A.version:void 0});(0,S.useEffect)(()=>{if(t||!f||!w)return;let m=C(f);if(!m||m.version===w.version)return;let A=!0;return me(m).then(H=>{!A||!H||(Z(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",w.version,"\u2192",m.version),z(m))}),()=>{A=!1}},[t,f,I,w==null?void 0:w.version]);let X=W(O,m=>{var A;return f&&(A=m.apply_ticks[f])!=null?A:0});(0,S.useEffect)(()=>{if(!X||!f)return;let m=C(f);if(!m||m.version===(w==null?void 0:w.version))return;let A=!0;return me(m).then(H=>{!A||!H||(Z(`webview:${e}`,"c\u1EADp nh\u1EADt",w==null?void 0:w.version,"\u2192",m.version),D(!1),z(m))}),()=>{A=!1}},[X]),(0,S.useEffect)(()=>{var H;let m=(H=k().keep_alive)==null?void 0:H.idle_close_ms;if(t||!m||m<=0)return;let A=setTimeout(()=>{lt(e)},m);return()=>clearTimeout(A)},[t,e]),(0,S.useEffect)(()=>{o>0&&(ae(!1),D(!1),V(m=>m+1),h(m=>m+1))},[o]);let Ue=(0,S.useRef)(t);(0,S.useEffect)(()=>{var m;Ue.current!==t&&(Ue.current=t,y.current&&((m=g.current)==null||m.injectJavaScript(Un(t?"resumed":"paused"))))},[t]);let ve=`${(qt=w==null?void 0:w.version)!=null?qt:"none"}:${(Vt=w==null?void 0:w.permissions.join(","))!=null?Vt:""}:${M}`,re=(0,S.useMemo)(()=>JSON.stringify([v!=null?v:{},_!=null?_:{}]),[v,_]),Fe=(0,S.useMemo)(()=>{var m;return Vn(_!=null?_:{},(m=w==null?void 0:w.permissions)!=null?m:[])},[re,w==null?void 0:w.permissions]),Ce=(0,S.useMemo)(()=>Bn(v!=null?v:{},Fe)+Dn()+(E.Platform.OS==="android"?Nn():"")+(k().debug?Ln():""),[Fe]),Te=(0,S.useRef)(null),$e=(0,S.useRef)(null);(0,S.useEffect)(()=>{var A,H,he;if(!w)return;if($e.current!==ve){$e.current=ve,Te.current=re;return}if(Te.current===re)return;let m=((H=JSON.parse((A=Te.current)!=null?A:"[]")[0])!=null?H:{}).org_id;if(Te.current=re,m===(v==null?void 0:v.org_id)&&y.current){D(!1),j(1500),(he=g.current)==null||he.injectJavaScript(Fn(v!=null?v:{},Fe));return}D(!1),V(_e=>_e+1)},[re,w,ve]),(0,S.useEffect)(()=>(t||(le(e),we(e),Ee(e)),()=>{le(e),we(e),Ee(e)}),[t,e,ve,o]),(0,S.useEffect)(()=>{let m=E.AppState.addEventListener("change",A=>{A==="background"&&!hn()&&le(e),A==="background"&&!Mn()&&we(e)});return()=>m.remove()},[e]);let Sr=(0,S.useCallback)(async m=>{var H,he,_e,oe,ht;let A=Cn(m.nativeEvent.data);if(!A){if(f&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(m.nativeEvent.data,{app_id:f,instance_id:e})).catch(L=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,L)})}catch(L){console.warn("[miniapp] onWebEvent l\u1ED7i",f,L)}return}if(A.method==="log"){let{level:L,text:q}=A;Z(`web:${e}`,L!=null?L:"log",q!=null?q:"");return}if(A.method==="pong"){B.current||D(!0);return}if(A.method==="touchAtTop"){i.emit(!!A.at_top);return}if(A.method==="contextApplied"){B.current&&clearTimeout(B.current),B.current=null,D(!0);return}if(A.method==="ready"){y.current=!0,D(!0);let L=(H=K.getState().instances[e])==null?void 0:H.context;L&&((he=g.current)==null||he.injectJavaScript(Rt(L)));return}try{let L=await jn(A,{getHostData:()=>{var q,Q;return(Q=(q=K.getState().instances[e])==null?void 0:q.host_data)!=null?Q:{}},getPermissions:()=>{var q,Q;return f?(Q=(q=C(f))==null?void 0:q.permissions)!=null?Q:[]:[]},getContext:()=>{var q,Q;return(Q=(q=K.getState().instances[e])==null?void 0:q.context)!=null?Q:{}},is_dark:r,close:De,app_id:f!=null?f:"",instance_id:e,options:l,emit:(q,Q)=>{var jt;(jt=g.current)==null||jt.injectJavaScript(In(q,Q))},isActive:()=>K.getState().active_key===e&&E.AppState.currentState!=="background"});A.id&&((_e=g.current)==null||_e.injectJavaScript(Tn(A.id,L)))}catch(L){if(!A.id)return;let q=L==null?void 0:L.code,Q=L instanceof u?L:new u(typeof q=="string"?q:"HOST_ERROR",String((oe=L==null?void 0:L.message)!=null?oe:L));(ht=g.current)==null||ht.injectJavaScript(kn(A.id,Q))}},[e,r,f,i,l]),br=(0,S.useCallback)(()=>{ae(!1),V(m=>m+1),h(m=>m+1)},[]);return(0,R.jsxs)(E.View,{style:[E.StyleSheet.absoluteFill,c&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&te.behind],pointerEvents:t?"auto":"none",children:[(b==null?void 0:b.mode)===ge.continuous&&(0,R.jsx)(Nt,{scanner:b}),w?(0,R.jsx)(wr.default,{ref:g,source:{uri:w.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,allowingReadAccessToURL:`file://${s?Tt():w.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ce,onMessage:Sr,bounces:!1,overScrollMode:"never",onLoadStart:m=>{le(e),we(e),Ee(e),Z(`webview:${e}`,"load start",$t(m.nativeEvent.url)),y.current=!1,D(!1)},onError:m=>{le(e),we(e),Ee(e),Z(`webview:${e}`,"load error",$t(m.nativeEvent.url),m.nativeEvent.description),ae(!0),D(!1)},onLoadEnd:m=>{let A=m.nativeEvent.url;Z(`webview:${e}`,"load end",$t(A)),f&&(d==null||d({app_id:f,instance_id:e,url:A})),j(1500)},onContentProcessDidTerminate:()=>{le(e),we(e),Ee(e),y.current=!1,D(!1),V(m=>m+1)},onRenderProcessGone:()=>(le(e),we(e),Ee(e),y.current=!1,D(!1),V(m=>m+1),!0),style:te.webview},ve):null,(b==null?void 0:b.mode)===ge.once&&(0,R.jsx)(Nt,{scanner:b}),p&&(0,R.jsx)(mo,{visible:!w||!P,interactive:ne,children:(0,R.jsx)(go,{splash:a,app:p.app,is_dark:r,error:ne,has_bundle:!!w,retry:br})})]})}),go=S.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:i})=>{let a=e,l=gt(t.app_id),c=r?"error":!o&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return(0,R.jsx)(a,{app:t,is_dark:n,status:c,progress:c==="downloading"?l==null?void 0:l.progress:void 0,retry:i})}),mo=({visible:e,interactive:t,children:n})=>{let r=(0,S.useRef)(new E.Animated.Value(e?1:0)).current,[o,i]=(0,S.useState)(e);return(0,S.useEffect)(()=>{if(e){i(!0),r.setValue(1);return}let a=E.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:l})=>{l&&i(!1)}),()=>a.stop()},[e,r]),o?(0,R.jsx)(E.Animated.View,{style:[E.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Bt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let i=t?"#FAFAFA":"#18181B";return(0,R.jsxs)(E.View,{style:[te.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,R.jsx)(E.View,{style:[te.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,R.jsx)(E.Image,{source:{uri:e.icon},style:te.splash_icon_image}):(0,R.jsx)(E.Text,{style:te.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,R.jsx)(E.Text,{style:[te.splash_name,{color:i}],children:e.name}),n==="error"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(E.Text,{style:te.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,R.jsx)(E.TouchableOpacity,{activeOpacity:.7,style:[te.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,R.jsx)(E.Text,{style:[te.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(E.ActivityIndicator,{style:te.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,R.jsxs)(E.Text,{style:te.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},yr=(e,t)=>{let n=(0,S.useRef)(t),r=(0,S.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.`))},fo=({container:e,splash:t=Bt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:l})=>{yr("container",e),yr("splash",t);let c=e,s=W(K,b=>b.active_key),d=(0,S.useRef)(s);s&&(d.current=s);let g=W(K,b=>Object.keys(b.instances).join("|")),y=W(K,b=>{var w;return b.active_key?(w=b.instances[b.active_key])==null?void 0:w.app.name:void 0}),p=(0,S.useMemo)(()=>g?g.split("|"):[],[g]),[f,T]=(0,S.useState)({}),v=(0,S.useRef)(po()).current;(0,S.useEffect)(()=>{if(!s||!o)return;let b=E.BackHandler.addEventListener("hardwareBackPress",()=>(De(),!0));return()=>b.remove()},[s,o]);let _=(0,S.useCallback)(()=>{let b=K.getState().active_key;b&&T(w=>({...w,[b]:(w[b]||0)+1}))},[]);return p.length?(0,R.jsx)(c,{visible:!!s,title:y!=null?y:"",is_dark:n,close:De,reload:_,subscribeWebAtTop:v.subscribe,children:p.map(b=>(0,R.jsx)(uo,{instance_key:b,is_active:s===b,is_front:(s!=null?s:d.current)===b,is_dark:n,reload_tick:f[b]||0,web_at_top:v,splash:t,bridge:r,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:l},b))}):null},te=E.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"}}),Ar=S.default.memo(fo);0&&(module.exports={CodeType,DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,ScannerEndReason,ScannerEvent,ScannerMethod,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,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he=e,Et.forEach(t=>t())},O=()=>{if(!he)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return he},Pt=e=>{Et.add(e),he&&e()},H=(...e)=>{he!=null&&he.debug&&console.log("[miniapp]",...e)};var Dn=(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(i=>i.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:r})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>r==null?void 0:r(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Un=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import vt,{useCallback as wt,useEffect as V,useMemo as Qe,useRef as Z,useState as Me}from"react";import{AppState as Rn,ActivityIndicator as Ui,Animated as yt,BackHandler as Ni,Image as Fi,Platform as $i,StyleSheet as St,Text as Le,TouchableOpacity as Bi,View as Mt}from"react-native";import qi from"react-native-webview";import{Linking as en,Platform as si}from"react-native";var Rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Fe,tt=()=>(Fe||(Fe=import("react-native-biometrics").then(({default:e})=>Rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Fe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Fe);import{PermissionsAndroid as ye,Platform as Nn}from"react-native";var Ot=e=>{var n,i,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("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 u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Tt=(e,t=()=>!0)=>new Promise((n,i)=>{let r=!1,o=(a,s)=>{r||(r=!0,clearTimeout(c),a?i(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>r?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(Nn.OS==="android"){let s=ye.PERMISSIONS.ACCESS_FINE_LOCATION,d=ye.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ye.check(s);if(!p())return;let y=g||await ye.check(d);if(!p())return;if(!g&&!y){let l=await ye.requestMultiple([s,d]);if(!p())return;if(l[s]!==ye.RESULTS.GRANTED&&l[d]!==ye.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});import{Platform as Nt}from"react-native";var nt=20,Ct=20,Ft=/^[a-z][a-z0-9_-]{0,31}$/,Fn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,$n=["low","medium","high"],le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),k=e=>new u("INVALID_PARAMS",e),Ee=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,It=(e,t)=>{if(e===void 0)return{};if(!le(e)||Object.keys(e).length>Ct||Object.values(e).some(n=>typeof n!="string"))throw k(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Ct} key)`);return e},$t=e=>{var n,i,r,o;if(e!==void 0&&!le(e))throw k("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ft.test(t.source)))throw k("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Fn.test(c))))throw k("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ee(t.max_count,1,nt))throw k(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${nt}`);if(t.max_size!==void 0&&!Ee(t.max_size,1,Number.MAX_SAFE_INTEGER))throw k("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ee(t.concurrency,1,5))throw k("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:Bn(t.process),target:qn(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Bn=e=>{if(e===void 0)return{};if(!le(e))throw k("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!le(n))throw k("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!Ee(n[i],1,1e4))throw k(`process.image.${i} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw k("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!le(n))throw k("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ee(n.max_duration,1,3600))throw k("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!$n.includes(n.quality))throw k("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},qn=e=>{var n,i,r,o;if(e===void 0)return{target:"host",params:{}};if(!le(e))throw k("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ft.test(t))throw k("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!le(e.params))throw k("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw k("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw k(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:It(e.headers,"upload.headers"),form_data:It(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(o=e.url_field)!=null?o:"url"}},Bt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Vn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=Bt(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===i:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},jn=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},_e,zn=()=>(_e!=null||(_e=import("react-native-image-picker").catch(e=>{throw _e=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),_e),kt=e=>async({accept:t,max_count:n,process:i})=>{var a,s,d,g,y,l,h,E,S;let r=await zn(),o=jn(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=i.image)==null?void 0:a.max_width,maxHeight:(s=i.image)==null?void 0:s.max_height,quality:(g=(d=i.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(y=i.video)==null?void 0:y.quality)!=null?l:"medium",durationLimit:(h=i.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await r.launchCamera({...c,saveToPhotos:!1}):await r.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let _=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(_,(E=p.errorMessage)!=null?E:p.errorCode)}return((S=p.assets)!=null?S:[]).filter(_=>_.uri).map((_,f)=>{var C,Y,N;return{uri:_.uri,name:(C=_.fileName)!=null?C:`file_${f+1}`,mime_type:(Y=_.type)!=null?Y:"application/octet-stream",size:_.fileSize,width:_.width,height:_.height,duration:_.duration,processed:!((N=_.type)!=null&&N.startsWith("video/"))||Nt.OS==="ios"}})},Wn={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Hn={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Jn=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let i=t.map(s=>{var d;return(d=Wn[s])!=null?d:Hn[s]}),r=!t.length||i.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(i)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var E,S,_;return{uri:l.uri,name:(E=l.name)!=null?E:`file_${h+1}`,mime_type:(S=l.type)!=null?S:"application/octet-stream",size:(_=l.size)!=null?_:void 0}});if(Nt.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),y=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=y.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},be,Kn=async e=>(be!=null||(be=import("@react-native-documents/picker").then(t=>Jn(t)).catch(t=>{throw be=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await be)(e)),qt={library:kt("library"),camera:kt("camera"),document:Kn},Lt={type:"image",label:"\u1EA2nh",accept:["image/*"]},Dt={type:"video",label:"Video",accept:["video/*"]},Ut={library:[Lt,Dt,{type:"media",label:"\u1EA2nh + video",accept:["image/*","video/*"]}],camera:[Lt,Dt],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"office",label:"Word / Excel",accept:[".doc",".docx",".xls",".xlsx"]}]},xe,Vt=()=>(xe!=null||(xe=import("react-native-compressor").catch(()=>(xe=void 0,null))),xe),jt=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Yn=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Gn={low:640,medium:1280,high:1920},Qn=async(e,{image:t})=>{var i;if(!t||!Yn.has(e.mime_type.toLowerCase()))return e;let n=await Vt();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(i=t.quality)!=null?i:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await jt(n,r,e.size),processed:!0}}catch{return e}},Xn=async(e,{video:t})=>{var i;let n=await Vt();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Gn[(i=t==null?void 0:t.quality)!=null?i:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await jt(n,r,e.size),processed:!0}}catch{return e}},Zn={image:Qn,video:Xn},ei=(e,t)=>t.split(".").reduce((n,i)=>le(n)?n[i]:void 0,e),zt=({file:e,target:t,onProgress:n,signal:i})=>new Promise((r,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,y])=>a.append(g,y)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();i.addEventListener("abort",s);let d=g=>{i.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,y])=>p.setRequestHeader(g,y)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let y=ei(g,c.url_field);if(typeof y!="string"||!y){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}r({url:y,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Wt=e=>{var i,r;let t={...qt};for(let[o,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[o]=c:delete t[o];let n={url:zt};for(let[o,c]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Ht=e=>{let{sources:t,targets:n}=Wt(e),i=Object.keys(t),r=Object.fromEntries(i.filter(o=>t[o]===qt[o]&&Ut[o]).map(o=>[o,Ut[o]]));return{sources:i,file_types:r,targets:Object.keys(n),max_count:nt}},Be=new Map,Jt=(e,t)=>`${e}:${t}`,ti=0,Kt=(e,t)=>{var n;typeof t=="string"&&((n=Be.get(Jt(e,t)))==null||n.abort())},Ae=e=>{for(let[t,n]of Be)t.startsWith(`${e}:`)&&n.abort()},$e=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),ni=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Yt=async(e,t)=>{var a;let{sources:n,targets:i}=Wt(t.config),r=n[e.source];if(!r)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=i[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=Jt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++ti}`);Be.set(p,c);try{return await ii(e,t,r,o,c.signal)}finally{Be.delete(p)}},ii=async(e,{instance_id:t,app_id:n,getContext:i,task_id:r,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var A,v,j;let g={app_id:n!=null?n:"",instance_id:t,context:{...(A=i==null?void 0:i())!=null?A:{}}},y=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw $e();if(!y.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=y.filter(M=>Vn(M,e.accept)?!0:(l.push({name:M.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${M.mime_type||Bt(M.name)}`}),!1)),E=h.map(()=>0),S=h.map(M=>{var I;return(I=M.size)!=null?I:0}),_=0,f=0,C=(M=!1)=>{if(!c||!r)return;let I=Date.now();if(!M&&I-f<200)return;f=I;let te=S.reduce((R,z)=>R+z,0),F=E.reduce((R,z)=>R+z,0);c("upload.progress",{task_id:r,loaded:F,total:te,percent:te?Math.min(100,Math.round(F/te*100)):0,done_count:_,count:h.length})},Y=[],N=0,ve=async()=>{var M,I,te;for(;N<h.length;){let F=N++,R=h[F];try{if(d.aborted)throw $e();let z=R.mime_type.startsWith("image/")?"image":R.mime_type.startsWith("video/")?"video":void 0,ce=z&&!R.processed?(I=(M=o==null?void 0:o.processors)==null?void 0:M[z])!=null?I:Zn[z]:void 0;if(ce&&(R=await ce(R,e.process),S[F]=(te=R.size)!=null?te:S[F],d.aborted))throw $e();if(e.max_size&&R.size&&R.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${R.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let me=(Ue,Ne)=>{E[F]=Ue,Ne&&(S[F]=Ne),C()},ne=await s({file:R,target:e.target,onProgress:me,signal:d,caller:g});if(typeof(ne==null?void 0:ne.url)!="string"||!ne.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Xe,...ie}=ne;Y[F]={url:Xe,name:R.name,mime_type:R.mime_type,size:R.size,width:R.width,height:R.height,duration:R.duration,...Object.keys(ie).length?{response:"response"in ie?ie.response:ie}:{}},E[F]=S[F]}catch(z){l.push(ni(h[F].name,z))}finally{_++,C(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},ve)),d.aborted)throw $e();let ae=Y.filter(M=>!!M);if(!ae.length){let M=l[0];throw new u((v=M==null?void 0:M.code)!=null?v:"UPLOAD_FAILED",(j=M==null?void 0:M.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ae,failed:l}};import{AppState as Gt,Platform as rt}from"react-native";var J,Qt=()=>rt.OS==="android"&&!!(J!=null&&J.requesting_permission),ri=1500,oi=()=>new Promise(e=>{if(rt.OS!=="android"||Gt.currentState==="active"){e();return}let t=()=>{clearTimeout(n),i.remove(),e()},n=setTimeout(t,ri),i=Gt.addEventListener("change",r=>{r==="active"&&t()})}),it=e=>{var t;if(J===e&&(J=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&rt.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Xt=async(e,t,n,i=()=>!0)=>{var o,c,p,a,s;if(J)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};J=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(r.native=g,r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await g.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await oi(),r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(g.addListener("result",l=>{var h,E;J!==r||r.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(E=(h=l.results[0])==null?void 0:h.transcript)!=null?E:""})}),g.addListener("error",l=>{J===r&&!r.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{J===r&&(it(r),n("speech.end"))})),r.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw it(r),d}},Zt=e=>{let t=J;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},re=e=>{let t=J;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{it(t)}};var Ve=1,u=class extends Error{constructor(n,i){super(i);this.code=n}},tn=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ve&&typeof t.method=="string"?t:null}catch{return null}},Re=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,nn=(e,t)=>Re({id:e,result:t}),rn=(e,t)=>Re({id:e,error:{code:t.code,message:t.message}}),on=(e,t)=>Re({event:e,data:t}),st=e=>Re({event:"context",data:e});var sn=()=>`(function () {
1
+ var pt="https://retion-miniapp-platform.vercel.app",be=null,Wt=new Set,fr=e=>{be=e,Wt.forEach(t=>t())},O=()=>{if(!be)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return be},Jt=e=>{Wt.add(e),be&&e()},G=(...e)=>{be!=null&&be.debug&&console.log("[miniapp]",...e)};var hr=(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:i,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:c})=>o==null?void 0:o(l,c)});return{promise:a.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(i)}}}),yr=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import qt,{useCallback as $t,useEffect as J,useMemo as ct,useRef as oe,useState as xe}from"react";import{AppState as cr,ActivityIndicator as vo,Animated as Ut,BackHandler as _o,Image as xo,Platform as Eo,StyleSheet as Vt,Text as We,TouchableOpacity as Po,View as Bt}from"react-native";import Ro from"react-native-webview";import{Linking as Tn,Platform as zr}from"react-native";var Yt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Ye,ut=()=>(Ye||(Ye=import("react-native-biometrics").then(({default:e})=>Yt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Ye=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Ye);import{PermissionsAndroid as Me,Platform as wr}from"react-native";var Kt=e=>{var n,r,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("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 u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,l]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<a||c>l))throw new u("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${l} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},Gt=(e,t=()=>!0)=>new Promise((n,r)=>{let o=!1,i=(c,s)=>{o||(o=!0,clearTimeout(a),c?r(c):n(s))},a=setTimeout(()=>i(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),l=()=>o?!1:t()?!0:(i(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!l())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(l()){if(wr.OS==="android"){let s=Me.PERMISSIONS.ACCESS_FINE_LOCATION,d=Me.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await Me.check(s);if(!l())return;let y=g||await Me.check(d);if(!l())return;if(!g&&!y){let p=await Me.requestMultiple([s,d]);if(!l())return;if(p[s]!==Me.RESULTS.GRANTED&&p[d]!==Me.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}l()&&c.getCurrentPosition(s=>{l()&&i(void 0,s)},s=>{var g;if(!l())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";i(new u(d,s.message))},e)}})().catch(c=>i(c))});import{Platform as rn}from"react-native";var dt=20,Xt=20,on=/^[a-z][a-z0-9_-]{0,31}$/,Ar=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Sr=["low","medium","high"],de=e=>!!e&&typeof e=="object"&&!Array.isArray(e),L=e=>new u("INVALID_PARAMS",e),Ue=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Qt=(e,t)=>{if(e===void 0)return{};if(!de(e)||Object.keys(e).length>Xt||Object.values(e).some(n=>typeof n!="string"))throw L(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Xt} key)`);return e},sn=e=>{var n,r,o,i;if(e!==void 0&&!de(e))throw L("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!on.test(t.source)))throw L("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!Ar.test(a))))throw L("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ue(t.max_count,1,dt))throw L(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${dt}`);if(t.max_size!==void 0&&!Ue(t.max_size,1,Number.MAX_SAFE_INTEGER))throw L("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ue(t.concurrency,1,5))throw L("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(a=>a.toLowerCase()),max_count:(o=t.max_count)!=null?o:1,max_size:t.max_size,process:br(t.process),target:Mr(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},br=e=>{if(e===void 0)return{};if(!de(e))throw L("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!de(n))throw L("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Ue(n[r],1,1e4))throw L(`process.image.${r} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw L("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!de(n))throw L("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ue(n.max_duration,1,3600))throw L("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Sr.includes(n.quality))throw L("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Mr=e=>{var n,r,o,i;if(e===void 0)return{target:"host",params:{}};if(!de(e))throw L("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!on.test(t))throw L("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!de(e.params))throw L("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw L("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw L(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Qt(e.headers,"upload.headers"),form_data:Qt(e.form_data,"upload.form_data"),field_name:(o=e.field_name)!=null?o:"file",url_field:(i=e.url_field)!=null?i:"url"}},an=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},vr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=an(e.name);return t.some(o=>o==="*/*"?!0:o.startsWith(".")?o===r:o.endsWith("/*")?n.startsWith(o.slice(0,-1)):n===o)},_r=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},Le,xr=()=>(Le!=null||(Le=import("react-native-image-picker").catch(e=>{throw Le=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Le),Zt=e=>async({accept:t,max_count:n,process:r})=>{var c,s,d,g,y,p,f,P,M;let o=await xr(),i=_r(t),a={mediaType:i==="image"?"photo":i,maxWidth:(c=r.image)==null?void 0:c.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(p=(y=r.video)==null?void 0:y.quality)!=null?p:"medium",durationLimit:(f=r.video)==null?void 0:f.max_duration,assetRepresentationMode:"compatible"},l=e==="camera"?await o.launchCamera({...a,saveToPhotos:!1}):await o.launchImageLibrary({...a,selectionLimit:n});if(l.didCancel)return[];if(l.errorCode){let v=l.errorCode==="permission"?"PERMISSION_DENIED":l.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(v,(P=l.errorMessage)!=null?P:l.errorCode)}return((M=l.assets)!=null?M:[]).filter(v=>v.uri).map((v,S)=>{var w,q,Z;return{uri:v.uri,name:(w=v.fileName)!=null?w:`file_${S+1}`,mime_type:(q=v.type)!=null?q:"application/octet-stream",size:v.fileSize,width:v.width,height:v.height,duration:v.duration,processed:!((Z=v.type)!=null&&Z.startsWith("video/"))||rn.OS==="ios"}})},Er={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Pr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Rr=e=>async({accept:t,max_count:n})=>{var i,a,l,c;let r=t.map(s=>{var d;return(d=Er[s])!=null?d:Pr[s]}),o=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:o,allowMultiSelection:n>1,mode:"import"})).filter(p=>p.uri&&!p.error).map((p,f)=>{var P,M,v;return{uri:p.uri,name:(P=p.name)!=null?P:`file_${f+1}`,mime_type:(M=p.type)!=null?M:"application/octet-stream",size:(v=p.size)!=null?v:void 0}});if(rn.OS!=="android"||!e.keepLocalCopy||!d.some(p=>p.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(p=>({uri:p.uri,fileName:p.name})),destination:"cachesDirectory"}),y=new Map(g.map(p=>[p.sourceUri,p.status==="success"?p.localUri:void 0]));return d.map(p=>{var f;return{...p,uri:(f=y.get(p.uri))!=null?f:p.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((c=(l=e.errorCodes)==null?void 0:l.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},De,Or=async e=>(De!=null||(De=import("@react-native-documents/picker").then(t=>Rr(t)).catch(t=>{throw De=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await De)(e)),cn={library:Zt("library"),camera:Zt("camera"),document:Or},en={type:"image",label:"\u1EA2nh",accept:["image/*"]},tn={type:"video",label:"Video",accept:["video/*"]},nn={library:[en,tn],camera:[en,tn],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},Ne,ln=()=>(Ne!=null||(Ne=import("react-native-compressor").catch(()=>(Ne=void 0,null))),Ne),pn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Cr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Tr={low:640,medium:1280,high:1920},kr=async(e,{image:t})=>{var r;if(!t||!Cr.has(e.mime_type.toLowerCase()))return e;let n=await ln();if(!n)return e;try{let o=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:o,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await pn(n,o,e.size),processed:!0}}catch{return e}},Ir=async(e,{video:t})=>{var r;let n=await ln();if(!n)return e;try{let o=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Tr[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:o,mime_type:"video/mp4",size:await pn(n,o,e.size),processed:!0}}catch{return e}},Lr={image:kr,video:Ir},Dr=(e,t)=>t.split(".").reduce((n,r)=>de(n)?n[r]:void 0,e),un=({file:e,target:t,onProgress:n,signal:r})=>new Promise((o,i)=>{if(t.target!=="url"||!("url"in t)){i(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(r.aborted){i(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let l=new XMLHttpRequest,c=new FormData;Object.entries(a.form_data).forEach(([g,y])=>c.append(g,y)),c.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>l.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};l.open("POST",a.url),Object.entries(a.headers).forEach(([g,y])=>l.setRequestHeader(g,y)),l.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),l.onload=()=>d(()=>{let g=l.responseText;try{g=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){i(new u("UPLOAD_FAILED",`HTTP ${l.status}`));return}let y=Dr(g,a.url_field);if(typeof y!="string"||!y){i(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}o({url:y,response:g})}),l.onerror=()=>d(()=>i(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),l.onabort=()=>d(()=>i(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),l.send(c)}),dn=e=>{var r,o;let t={...cn};for(let[i,a]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))a?t[i]=a:delete t[i];let n={url:un};for(let[i,a]of Object.entries((o=e==null?void 0:e.targets)!=null?o:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},gn=e=>{let{sources:t,targets:n}=dn(e),r=Object.keys(t),o=Object.fromEntries(r.filter(i=>t[i]===cn[i]&&nn[i]).map(i=>[i,nn[i]]));return{sources:r,file_types:o,targets:Object.keys(n),max_count:dt}},Ge=new Map,mn=(e,t)=>`${e}:${t}`,Nr=0,fn=(e,t)=>{var n;typeof t=="string"&&((n=Ge.get(mn(e,t)))==null||n.abort())},ve=e=>{for(let[t,n]of Ge)t.startsWith(`${e}:`)&&n.abort()},Ke=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Ur=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},hn=async(e,t)=>{var c;let{sources:n,targets:r}=dn(t.config),o=n[e.source];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=r[e.target.target];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,l=mn(t.instance_id,(c=t.task_id)!=null?c:`auto-${++Nr}`);Ge.set(l,a);try{return await Fr(e,t,o,i,a.signal)}finally{Ge.delete(l)}},Fr=async(e,{instance_id:t,app_id:n,getContext:r,task_id:o,config:i,emit:a,exclusivePick:l=g=>g()},c,s,d)=>{var h,b,$;let g={app_id:n!=null?n:"",instance_id:t,context:{...(h=r==null?void 0:r())!=null?h:{}}},y=(await l(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw Ke();if(!y.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let p=[],f=y.filter(x=>vr(x,e.accept)?!0:(p.push({name:x.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${x.mime_type||an(x.name)}`}),!1)),P=f.map(()=>0),M=f.map(x=>{var k;return(k=x.size)!=null?k:0}),v=0,S=0,w=(x=!1)=>{if(!a||!o)return;let k=Date.now();if(!x&&k-S<200)return;S=k;let N=M.reduce((C,Y)=>C+Y,0),B=P.reduce((C,Y)=>C+Y,0);a("upload.progress",{task_id:o,loaded:B,total:N,percent:N?Math.min(100,Math.round(B/N*100)):0,done_count:v,count:f.length})},q=[],Z=0,ie=async()=>{var x,k,N;for(;Z<f.length;){let B=Z++,C=f[B];try{if(d.aborted)throw Ke();let Y=C.mime_type.startsWith("image/")?"image":C.mime_type.startsWith("video/")?"video":void 0,Te=Y&&!C.processed?(k=(x=i==null?void 0:i.processors)==null?void 0:x[Y])!=null?k:Lr[Y]:void 0;if(Te&&(C=await Te(C,e.process),M[B]=(N=C.size)!=null?N:M[B],d.aborted))throw Ke();if(e.max_size&&C.size&&C.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${C.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let Ae=(Pe,Ie)=>{P[B]=Pe,Ie&&(M[B]=Ie),w()},ee=await s({file:C,target:e.target,onProgress:Ae,signal:d,caller:g});if(typeof(ee==null?void 0:ee.url)!="string"||!ee.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ke,...Ee}=ee;q[B]={url:ke,name:C.name,mime_type:C.mime_type,size:C.size,width:C.width,height:C.height,duration:C.duration,...Object.keys(Ee).length?{response:"response"in Ee?Ee.response:Ee}:{}},P[B]=M[B]}catch(Y){p.push(Ur(f[B].name,Y))}finally{v++,w(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,f.length)},ie)),d.aborted)throw Ke();let we=q.filter(x=>!!x);if(!we.length){let x=p[0];throw new u((b=x==null?void 0:x.code)!=null?b:"UPLOAD_FAILED",($=x==null?void 0:x.message)!=null?$:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:we,failed:p}};import{Platform as Vr}from"react-native";import{AppState as yn,Platform as mt}from"react-native";var X,wn=()=>mt.OS==="android"&&!!(X!=null&&X.requesting_permission),$r=1500,ft=()=>new Promise(e=>{if(mt.OS!=="android"||yn.currentState==="active"){e();return}let t=()=>{clearTimeout(n),r.remove(),e()},n=setTimeout(t,$r),r=yn.addEventListener("change",o=>{o==="active"&&t()})}),gt=e=>{var t;if(X===e&&(X=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&mt.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},An=async(e,t,n,r=()=>!0)=>{var i,a,l,c,s;if(X)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};X=o;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(o.native=g,o.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.requesting_permission=!0;let y;try{y=await g.requestPermissionsAsync()}finally{o.requesting_permission=!1}if(await ft(),o.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("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 u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(g.addListener("result",p=>{var f,P;X!==o||o.cancelled||n(p.isFinal?"speech.final":"speech.partial",{...p,text:(P=(f=p.results[0])==null?void 0:f.transcript)!=null?P:""})}),g.addListener("error",p=>{X===o&&!o.cancelled&&n("speech.error",{...p,code:p.error})}),g.addListener("end",()=>{X===o&&(gt(o),n("speech.end"))})),o.started=!0,g.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(l=t.interimResults)!=null?l:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw gt(o),d}},Sn=e=>{let t=X;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ae=e=>{let t=X;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{gt(t)}};import{useRef as Br,useSyncExternalStore as qr}from"react";var Re=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(i=>i())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=Br(null),o=()=>{let i=e.getState(),a=r.current;if(a&&a.state===i&&a.selector===t)return a.value;let l=t(i),c=a&&n(a.value,l)?a.value:l;return r.current={state:i,selector:t,value:c},c};return qr(e.subscribe,o)};var bn={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},ht={...bn,all:Object.values(bn)},Fe={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},yt={result:"scanner.result",end:"scanner.end"},Oe={user:"user",web:"web",closed:"closed",error:"error"},ce={once:"once",continuous:"continuous"},jr=1500,Mn=6e4,I,se=Re({active:null,last_value:null,hit_tick:0}),vn=()=>Vr.OS==="android"&&!!(I!=null&&I.requesting_permission),wt=e=>{let{types:t,cooldown_ms:n}=e!=null?e:{},r={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(o=>ht.all.includes(o)))throw new u("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");r.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Mn)throw new u("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Mn}`);r.cooldown_ms=n}return r},At=e=>I!==e?!1:(I=void 0,se.setState({active:null,last_value:null}),!0),_n=async(e,t)=>{if(I)throw new u("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");I=e;let n=()=>{if(e.cancelled||!t())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let r;try{r=await import("react-native-vision-camera")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n(),e.requesting_permission=!0;let o;try{o=await r.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await ft(),n(),o!=="granted")throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera");if(!r.Camera.getAvailableCameraDevices().some(i=>i.position==="back"))throw new u("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");se.setState({active:{owner:e.owner,mode:e.mode,types:e.types,vision:r},last_value:null})}catch(r){throw At(e),r}},xn=(e,t,n)=>{var r,o;return{owner:e,mode:t,types:(r=n.types)!=null?r:ht.all,cooldown_ms:(o=n.cooldown_ms)!=null?o:jr,cancelled:!1,requesting_permission:!1,last_seen:new Map}},En=(e,t,n=()=>!0,r)=>new Promise((o,i)=>{let a=xn(e,ce.once,t);a.onHit=r,a.resolve=o,a.reject=i,_n(a,n).catch(i)}),Pn=(e,t,n,r=()=>!0,o)=>{let i=xn(e,ce.continuous,t);return i.emit=n,i.onHit=o,_n(i,r)},Xe=(e,t,n)=>{var r,o;if(!se.getState().active){e.cancelled=!0;return}if(At(e)){if(e.mode===ce.once){(r=e.reject)==null||r.call(e,t===Oe.error?new u("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new u("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(o=e.emit)==null||o.call(e,yt.end,n?{reason:t,message:n}:{reason:t})}},Rn=e=>{(I==null?void 0:I.owner)===e&&Xe(I,Oe.web)},ge=e=>{(I==null?void 0:I.owner)===e&&Xe(I,Oe.closed)},St=()=>{I&&Xe(I,Oe.user)},On=e=>{I&&Xe(I,Oe.error,e)},Cn=(e,t=Date.now())=>{var r,o,i;let n=I;if(!(!n||!se.getState().active))for(let{value:a,type:l}of e){if(!a)continue;let c=n.last_seen.get(a);if(!(c!==void 0&&t-c<n.cooldown_ms)){if(n.last_seen.set(a,t),(r=n.onHit)==null||r.call(n),n.mode===ce.once){At(n),(o=n.resolve)==null||o.call(n,{value:a,type:l});return}se.setState(s=>({last_value:a,hit_tick:s.hit_tick+1})),(i=n.emit)==null||i.call(n,yt.result,{value:a,type:l})}}};var Ze=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},kn=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ze&&typeof t.method=="string"?t:null}catch{return null}},Be=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,In=(e,t)=>Be({id:e,result:t}),Ln=(e,t)=>Be({id:e,error:{code:t.code,message:t.message}}),Dn=(e,t)=>Be({event:e,data:t}),Mt=e=>Be({event:"context",data:e});var Nn=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he
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: ${Ve}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ze}, 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 et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he
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;`,an=()=>`(function () {
22
+ })(); true;`,Un=()=>`(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 et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he
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: ${Ve}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${Ze}, 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,7 +38,7 @@ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he
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;`,cn=()=>`(function () {
41
+ })(); true;`,Fn=()=>`(function () {
42
42
  if (window.__retionSafeAreaFrozen) { return; }
43
43
  window.__retionSafeAreaFrozen = true;
44
44
  var max = {};
@@ -59,8 +59,8 @@ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he
59
59
  },
60
60
  });
61
61
  };
62
- })(); true;`,pn=e=>Re({event:e}),ln=(e,t)=>{let n=un(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${st(e)}`},un=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),dn=(e,t={})=>{let n=un(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ve} };
62
+ })(); true;`,$n=e=>Be({event:e}),Bn=(e,t)=>{let n=qn(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${Mt(e)}`},qn=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Vn=(e,t={})=>{let n=qn(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ze} };
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
66
- true;`},gn={partner:"partner_token",chatbox:"chatbox_token"},mn=(e,t)=>{let n={...e};for(let i of Object.values(gn))t.includes(i)||delete n[i];return n},ot=new Set,Pe=async(e,t)=>{if(ot.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);ot.add(e);try{return await t()}finally{ot.delete(e)}},ai=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),qe=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},fn=async({method:e,params:t},{getHostData:n,getPermissions:i,getContext:r,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var E,S,_,f,C,Y,N,ve,ae;let y=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let A=Ot(t);return Pe(e,()=>Tt(A,g))}case"speech.start":{if(!d)throw h();let A={};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 u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");A.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 u("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);A[v]=t[v]}return Xt(a,A,d,g)}case"speech.stop":return Zt(a);case"uploadFiles":{let{task_id:A,...v}=t!=null?t:{};if(A!==void 0&&(typeof A!="string"||!A))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Yt($t(v),{instance_id:a,app_id:p,getContext:r,task_id:A,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>Pe("uploadFiles.pick",j)})}case"uploadFiles.cancel":Kt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Ht(s==null?void 0:s.upload);case"getBiometricAvailability":return((E=s==null?void 0:s.biometrics)!=null?E:await tt()).getAvailability();case"authenticateBiometric":{let A=qe(t==null?void 0:t.reason,"reason").trim();if(!A||A.length>200)throw new u("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 u("INVALID_PARAMS","Invalid cancelButtonText");return Pe(e,async()=>{var M;return((M=s==null?void 0:s.biometrics)!=null?M:await tt()).authenticate({reason:A,cancelButtonText:v})})}case"requestPayment":{let A=y==null?void 0:y.requestPayment;if(!A)throw h();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:v,currency:qe(t==null?void 0:t.currency,"currency")};return Pe(e,()=>A(j,l))}case"printImage":{let A=y==null?void 0:y.printImage;if(!A)throw h();let v=qe(t==null?void 0:t.image,"image");await Pe(e,()=>A({image:v},l));return}case"openScreen":if(!(y!=null&&y.openScreen))throw h();await y.openScreen({screen:qe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let A=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(A))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(A):en.openURL(A));return}case"openLink":{let A=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(A)||/^(javascript|file|data|about|blob):/i.test(A))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(A):en.openURL(A))}catch(v){throw new u("NOT_SUPPORTED",String((C=(f=v==null?void 0:v.message)!=null?f:v)!=null?C:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(N=s==null?void 0:s.showToast)==null||N.call(s,String((Y=t==null?void 0:t.message)!=null?Y:""));return;case"haptic":{let A=ai.has(t==null?void 0:t.type)?t.type:"selection";(ve=s==null?void 0:s.haptic)==null||ve.call(s,A);return}case"getSystemInfo":return{platform:si.OS==="ios"?"ios":"android",appVersion:(ae=s==null?void 0:s.app_version)!=null?ae:"",theme:o?"dark":"light"};case"getAccessToken":{let A=n().access_token;if(!A)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return A}case"getToken":{let A=t==null?void 0:t.type;if(A==="access"){let M=n().access_token;if(!M)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return M}if(A!=="partner"&&A!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(A)}`);let v=gn[A];if(!i().includes(v))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=A==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return j}case"getUserInfo":{let A=n().user;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return A}case"getPageInfo":{let A=n().page;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return A}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ct=e=>`bundle:${e}`,pt=()=>`${O().file_system.document_dir}/miniapps`,lt=pt,ut=(e,t,n="index.html",i=!1,r=[])=>{let o=`${lt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:i,permissions:r}},at=e=>{var t;O().storage.setString(ct(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ci=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,P=e=>{let t=O().storage.getString(ct(e));if(!t)return null;try{let{version:n,entry:i,context_update:r,permissions:o}=JSON.parse(t);return ut(e,n,i,!!r,Array.isArray(o)?o:[])}catch{return null}},oe=e=>O().file_system.exists(e.entry_uri.replace("file://","")),dt=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await oe(t)},yn=async(e,t)=>{let n=O().file_system,i=`${lt()}/${e}`,r=await n.listDir(i).catch(()=>[]);await Promise.all(r.filter(o=>!t.includes(o)).map(o=>n.remove(`${i}/${o}`).catch(()=>{})))},An=async e=>{var t;await((t=Te[e])==null?void 0:t.catch(()=>{})),O().storage.setString(ct(e),""),await O().file_system.remove(`${lt()}/${e}`).catch(()=>{})},Se=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Te={},wn=(e,t)=>{var o;let i=((o=Te[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),r=i.catch(()=>{});return Te[e]=r,r.then(()=>{Te[e]===r&&delete Te[e]}),i},pi=(e,t)=>{var r,o;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let p=((r=n[c])!=null?r:0)-((o=i[c])!=null?o:0);if(p)return p}return 0},li=({manifest:e,zip_path:t})=>wn(e.app_id,async()=>{var o;let n=O().file_system,i=P(e.app_id);if(i&&pi(i.version,e.version)>=0&&await oe(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=ut(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),at(e),H("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),yn(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),r}),gt=(e,{base_url:t,onProgress:n}={})=>{let i=O().file_system,r=null,o=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new Se},a=async()=>{var g;p();let s=P(e.app_id);if((s==null?void 0:s.version)===e.version&&await i.exists(s.dir))return at(e),P(e.app_id);p();let d=i.download({url:t?ci(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(y,l)=>{var E;let h=l>0?l:(E=e.size)!=null?E:0;h>0&&(n==null||n(Math.min(1,y/h)))}});r=d;try{let{status:y}=await d.promise;if(p(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else H("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ut(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await i.remove(l.dir).catch(()=>{}),await i.mkdir(l.dir),await i.unzip(c,l.dir),at(e),yn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(y){throw o?new Se:y}finally{r=null,i.remove(c).catch(()=>{})}};return{promise:wn(e.app_id,a),cancel:()=>{o=!0,r==null||r.cancel()}}},Oe={},ui=__DEV__?0:60*1e3,hn={},Mn=(e,t)=>{var i,r;let n=P(e);return n&&Date.now()-((i=hn[t])!=null?i:0)<ui?Promise.resolve(n):((r=Oe[e])!=null||(Oe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await gt(c,{base_url:t}).promise;return hn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{Oe[e]=void 0})),Oe[e])};var je=new Map,vn=(e,t)=>(je.set(e,t),()=>{je.get(e)===t&&je.delete(e)}),di=(e,t)=>{let n=je.get(e);return n?n(t):!1};import{useRef as gi,useSyncExternalStore as mi}from"react";var ze=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let r=typeof i=="function"?i(t):i;t={...t,...r},n.forEach(o=>o())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},ee=(e,t,n=Object.is)=>{let i=gi(null),r=()=>{let o=e.getState(),c=i.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return i.current={state:o,selector:t,value:a},a};return mi(e.subscribe,r)};var B=ze({active_key:null,instances:{}}),Sn=({app:e,instance_id:t,context:n={},url_params:i={},host_data:r={}},o)=>{var p;let c=(p=O().keep_alive)==null?void 0:p.max_webviews;B.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:i,host_data:r,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(y=>y!==s).sort((y,l)=>d[y].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(y=>{delete d[y]}),o?{active_key:s,instances:d}:{instances:d}})},fi=e=>Sn(e,!0),hi=e=>Sn(e,!1),Ce=()=>B.setState({active_key:null}),We=e=>{B.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var _n="catalog",yi="paused_apps",Ai="removed_apps",wi=10*1e3,Mi=2,vi=3e3,Si=()=>{var e;try{return JSON.parse((e=O().storage.getString(_n))!=null?e:"{}")}catch{return{}}},x=ze({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),bn=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},Ke=new Set,xn=e=>{let t=new Set,n=()=>O().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let r=JSON.parse((i=O().storage.getString(e))!=null?i:"[]");Array.isArray(r)&&r.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},X=xn(yi),ge=xn(Ai);Pt(()=>{X.load(),ge.load();let e=Si(),t={};Object.keys(e).filter(n=>!ge.has(n)).forEach(n=>{let i=P(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:X.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),x.setState({catalog:e,downloads:t})});var ft=e=>ee(x,t=>e?t.downloads[e]:void 0),_i=()=>ee(x,e=>e.pause_reasons.length>0),Q=(...e)=>H("queue",...e),L=[],se={},b=null,He=new Set,we={},mt=new Set,ue=e=>{mt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},bi=e=>(mt.add(e),()=>{mt.delete(e)}),xi=()=>x.getState().downloads,q=(e,t)=>{let n=!!P(e),i=x.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,o={...i!=null?i:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};x.setState(c=>({downloads:{...c.downloads,[e]:o}})),(i==null?void 0:i.status)!==o.status||(i==null?void 0:i.version)!==o.version||(i==null?void 0:i.has_local)!==o.has_local?ue({type:"status_change",app_id:e,state:o}):i.progress!==o.progress&&ue({type:"progress",app_id:e,progress:o.progress,version:o.version})},Je=(e,t)=>{var n;(n=we[e])==null||n.forEach(i=>i(t)),delete we[e]},Ei=()=>x.getState().pause_reasons.length>0,de=e=>{var p;if(b)return;let t=e?L.indexOf(e):Ei()?-1:L.findIndex(a=>!X.has(a));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),i=x.getState().catalog[n];if(!i){Je(n,P(n)),de();return}let r=Date.now();se[n]=((p=se[n])!=null?p:0)+1,q(n,{status:"downloading",progress:0,version:i.version,error:void 0});let o=0,c=gt(i,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,q(n,{progress:s/100,version:i.version}))}});b={app_id:n,handle:c,forced:!!e},Q("start",n,i.version,e?"(forced)":""),c.promise.then(a=>{Q("installed",n,i.version,`${Date.now()-r}ms`),q(n,{status:"installed",progress:1,version:i.version}),Je(n,a)}).catch(a=>{var d;if(a instanceof Se){if(He.has(n))return;Q("paused",n),se[n]-=1,L.unshift(n),q(n,{status:X.has(n)?"paused":"queued",progress:0,version:i.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),se[n]<Mi){q(n,{status:"queued",progress:0,version:i.version,error:s}),setTimeout(()=>{var g;L.includes(n)||(b==null?void 0:b.app_id)===n||(L.push(n),de((g=we[n])!=null&&g.length?n:void 0))},vi);return}q(n,{status:"failed",progress:0,version:i.version,error:s}),Je(n,P(n))}).finally(()=>{b=null;let a=L.find(s=>{var d;return(d=we[s])==null?void 0:d.length});de(a)})},Ye=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},Pi=async e=>{let{host_id:t,client_token:n}=O(),i=new AbortController,r=setTimeout(()=>i.abort(),wi);try{let o=`${et}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(r)}},Ie=null,ht=()=>(Ie!=null||(Ie=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(Pi)),i={};[...n].reverse().flat().forEach(a=>{i[a.app_id]=a});let r=Object.keys(x.getState().catalog).filter(a=>!i[a]);O().storage.setString(_n,JSON.stringify(i)),x.setState({catalog:i}),await Promise.all(r.map(a=>En(a,{by_user:!1}))),r.forEach(a=>ge.delete(a));let o=Object.keys(i).filter(a=>!ge.has(a)),c=[],p={};for(let a of o.map(s=>i[s])){if(await dt(a)){q(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=P(a.app_id);if(bn(a.app_id)&&!Ke.has(a.app_id)&&s&&await oe(s)){q(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return x.setState({updates:p}),c.forEach(a=>{se[a.app_id]=0,q(a.app_id,{status:X.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),Ye(a.app_id)}),Q("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",r,`${Date.now()-e}ms`),ue({type:"sync_complete",app_ids:o,removed:r}),Object.values(p).forEach(a=>ue({type:"update_available",...a})),de(),{ok:!0,app_ids:o,removed:r}}catch(n){let i=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",i),ue({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{Ie=null}})()),Ie),En=async(e,{by_user:t})=>{var r,o,c,p;if(t&&ge.add(e),He.has(e))return;He.add(e),X.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let i=(p=(c=(r=x.getState().downloads[e])==null?void 0:r.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?p:"";q(e,{status:"uninstalling",progress:0,version:i}),await An(e),We(e),x.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete se[e],He.delete(e),Je(e,null),Q("uninstalled",e,t?"(user)":"(not in list)"),ue({type:"uninstalled",app_id:e})},Ri=e=>En(e,{by_user:!0}),Oi=e=>{let t=ke(e);return t?(ge.delete(e),(b==null?void 0:b.app_id)===e||L.includes(e)||(se[e]=0,q(e,{status:X.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ye(e),de(),Q("restore",e)),!0):!1},Ti=e=>{if(X.has(e))return;if(X.add(e),Q("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=x.getState().downloads[e];L.includes(e)&&t&&q(e,{status:"paused",progress:0,version:t.version})},Ci=e=>{if(!X.delete(e))return;Q("resume app",e);let t=x.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&ke(e)&&(se[e]=0,Ye(e)),L.includes(e)&&t&&q(e,{status:"queued",progress:0,version:t.version}),de()},Ii=e=>{let{pause_reasons:t}=x.getState();t.includes(e)||(x.setState({pause_reasons:[...t,e]}),Q("pause",e),t.length===0&&ue({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},ki=e=>{let{pause_reasons:t}=x.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);x.setState({pause_reasons:n}),Q("resume",e),n.length===0&&ue({type:"pause_change",paused:!1,reasons:n}),de()},Pn=e=>x.getState().updates[e],Li=async e=>{var n,i;let t=Pn(e);Ke.add(e);try{let r=await Ge(e),o=(i=t==null?void 0:t.next_version)!=null?i:(n=ke(e))==null?void 0:n.version;return!r||!o||r.version!==o?!1:(x.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),Q("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Ke.delete(e)}},Di=()=>Object.values(x.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:ge.has(e.app_id)})),ke=e=>x.getState().catalog[e],Ge=async e=>{let t=ke(e);if(!t)return;if(X.delete(e),ge.delete(e),await dt(t))return P(e);let n=P(e);if(bn(e)&&!Ke.has(e)&&n&&await oe(n))return n;let i=new Promise(r=>{var o;((o=we[e])!=null?o:we[e]=[]).push(r)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(se[e]=0,Ye(e,{front:!0}),b&&!b.forced?b.handle.cancel():de(e)),i};import{Fragment as Cn,jsx as U,jsxs as De}from"react/jsx-runtime";var At=e=>(e!=null?e:"").replace(/\?[^#]*/,""),On=0,Vi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},ji=vt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:r,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=Z(null),y=Z(!1),l=ee(B,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,E=l==null?void 0:l.app.manifest_url,S=l==null?void 0:l.context,_=l==null?void 0:l.url_params,[f,C]=Me(()=>h?P(h):null),[Y,N]=Me(!1),[ve,ae]=Me(0),[A,v]=Me(0),[j,M]=Me(!1),I=Z(null),te=m=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,M(!0)},m)};V(()=>()=>{I.current&&clearTimeout(I.current)},[]),V(()=>{if(!h||!t&&f)return;let m=!0;return N(!1),(async()=>{let w=P(h),$=w?await oe(w):!1;if(!m||(C($?G=>!G||G.version!==w.version||G.permissions.join(",")!==w.permissions.join(",")?w:G:null),__DEV__&&Date.now()-On>1e4&&(On=Date.now(),await ht()),!m))return;let pe=await Ge(h),fe=pe!==void 0?pe:E?await Mn(h,E):P(h);if(m){if(!fe){N(!0);return}C(G=>G!=null?G:fe)}})(),()=>{m=!1}},[t,h,E,ve]),V(()=>vn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let F=ee(x,m=>{let w=h?m.downloads[h]:void 0;return(w==null?void 0:w.status)==="installed"?w.version:void 0});V(()=>{if(t||!h||!f)return;let m=P(h);if(!m||m.version===f.version)return;let w=!0;return oe(m).then($=>{!w||!$||(H(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),C(m))}),()=>{w=!1}},[t,h,F,f==null?void 0:f.version]);let R=ee(x,m=>{var w;return h&&(w=m.apply_ticks[h])!=null?w:0});V(()=>{if(!R||!h)return;let m=P(h);if(!m||m.version===(f==null?void 0:f.version))return;let w=!0;return oe(m).then($=>{!w||!$||(H(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),M(!1),C(m))}),()=>{w=!1}},[R]),V(()=>{var $;let m=($=O().keep_alive)==null?void 0:$.idle_close_ms;if(t||!m||m<=0)return;let w=setTimeout(()=>{We(e)},m);return()=>clearTimeout(w)},[t,e]),V(()=>{r>0&&(N(!1),M(!1),v(m=>m+1),ae(m=>m+1))},[r]);let z=Z(t);V(()=>{var m;z.current!==t&&(z.current=t,y.current&&((m=g.current)==null||m.injectJavaScript(pn(t?"resumed":"paused"))))},[t]);let ce=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${A}`,me=Qe(()=>JSON.stringify([S!=null?S:{},_!=null?_:{}]),[S,_]),ne=Qe(()=>{var m;return mn(_!=null?_:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[me,f==null?void 0:f.permissions]),Xe=Qe(()=>dn(S!=null?S:{},ne)+an()+($i.OS==="android"?cn():"")+(O().debug?sn():""),[ne]),ie=Z(null),Ue=Z(null);V(()=>{var w,$,pe;if(!f)return;if(Ue.current!==ce){Ue.current=ce,ie.current=me;return}if(ie.current===me)return;let m=(($=JSON.parse((w=ie.current)!=null?w:"[]")[0])!=null?$:{}).org_id;if(ie.current=me,m===(S==null?void 0:S.org_id)&&y.current){M(!1),te(1500),(pe=g.current)==null||pe.injectJavaScript(ln(S!=null?S:{},ne));return}M(!1),v(fe=>fe+1)},[me,f,ce]),V(()=>(t||(re(e),Ae(e)),()=>{re(e),Ae(e)}),[t,e,ce,r]),V(()=>{let m=Rn.addEventListener("change",w=>{w==="background"&&!Qt()&&re(e)});return()=>m.remove()},[e]);let Ne=wt(async m=>{var $,pe,fe,G,Ze;let w=tn(m.nativeEvent.data);if(!w){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(T=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)})}catch(T){console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)}return}if(w.method==="log"){let{level:T,text:D}=w;H(`web:${e}`,T!=null?T:"log",D!=null?D:"");return}if(w.method==="pong"){I.current||M(!0);return}if(w.method==="touchAtTop"){o.emit(!!w.at_top);return}if(w.method==="contextApplied"){I.current&&clearTimeout(I.current),I.current=null,M(!0);return}if(w.method==="ready"){y.current=!0,M(!0);let T=($=B.getState().instances[e])==null?void 0:$.context;T&&((pe=g.current)==null||pe.injectJavaScript(st(T)));return}try{let T=await fn(w,{getHostData:()=>{var D,W;return(W=(D=B.getState().instances[e])==null?void 0:D.host_data)!=null?W:{}},getPermissions:()=>{var D,W;return h?(W=(D=P(h))==null?void 0:D.permissions)!=null?W:[]:[]},getContext:()=>{var D,W;return(W=(D=B.getState().instances[e])==null?void 0:D.context)!=null?W:{}},is_dark:i,close:Ce,app_id:h!=null?h:"",instance_id:e,options:p,emit:(D,W)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(on(D,W))},isActive:()=>B.getState().active_key===e&&Rn.currentState!=="background"});w.id&&((fe=g.current)==null||fe.injectJavaScript(nn(w.id,T)))}catch(T){if(!w.id)return;let D=T==null?void 0:T.code,W=T instanceof u?T:new u(typeof D=="string"?D:"HOST_ERROR",String((G=T==null?void 0:T.message)!=null?G:T));(Ze=g.current)==null||Ze.injectJavaScript(rn(w.id,W))}},[e,i,h,o,p]),kn=wt(()=>{N(!1),v(m=>m+1),ae(m=>m+1)},[]);return De(Mt,{style:[St.absoluteFill,a&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&K.behind],pointerEvents:t?"auto":"none",children:[f?U(qi,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,allowingReadAccessToURL:`file://${s?pt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Xe,onMessage:Ne,bounces:!1,overScrollMode:"never",onLoadStart:m=>{re(e),Ae(e),H(`webview:${e}`,"load start",At(m.nativeEvent.url)),y.current=!1,M(!1)},onError:m=>{re(e),Ae(e),H(`webview:${e}`,"load error",At(m.nativeEvent.url),m.nativeEvent.description),N(!0),M(!1)},onLoadEnd:m=>{let w=m.nativeEvent.url;H(`webview:${e}`,"load end",At(w)),h&&(d==null||d({app_id:h,instance_id:e,url:w})),te(1500)},onContentProcessDidTerminate:()=>{re(e),Ae(e),y.current=!1,M(!1),v(m=>m+1)},onRenderProcessGone:()=>(re(e),Ae(e),y.current=!1,M(!1),v(m=>m+1),!0),style:K.webview},ce):null,l&&U(Wi,{visible:!f||!j,interactive:Y,children:U(zi,{splash:c,app:l.app,is_dark:i,error:Y,has_bundle:!!f,retry:kn})})]})}),zi=vt.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:r,retry:o})=>{let c=e,p=ft(t.app_id),a=i?"error":!r&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return U(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Wi=({visible:e,interactive:t,children:n})=>{let i=Z(new yt.Value(e?1:0)).current,[r,o]=Me(e);return V(()=>{if(e){o(!0),i.setValue(1);return}let c=yt.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,i]),r?U(yt.View,{style:[St.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},In=({app:e,is_dark:t,status:n,progress:i,retry:r})=>{let o=t?"#FAFAFA":"#18181B";return De(Mt,{style:[K.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[U(Mt,{style:[K.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?U(Fi,{source:{uri:e.icon},style:K.splash_icon_image}):U(Le,{style:K.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),U(Le,{style:[K.splash_name,{color:o}],children:e.name}),n==="error"?De(Cn,{children:[U(Le,{style:K.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),U(Bi,{activeOpacity:.7,style:[K.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:U(Le,{style:[K.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):De(Cn,{children:[U(Ui,{style:K.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&De(Le,{style:K.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},Tn=(e,t)=>{let n=Z(t),i=Z(!1);__DEV__&&!i.current&&n.current!==t&&(i.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.`))},Hi=({container:e,splash:t=In,is_dark:n=!1,bridge:i,close_on_back:r=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Tn("container",e),Tn("splash",t);let a=e,s=ee(B,f=>f.active_key),d=Z(s);s&&(d.current=s);let g=ee(B,f=>Object.keys(f.instances).join("|")),y=ee(B,f=>{var C;return f.active_key?(C=f.instances[f.active_key])==null?void 0:C.app.name:void 0}),l=Qe(()=>g?g.split("|"):[],[g]),[h,E]=Me({}),S=Z(Vi()).current;V(()=>{if(!s||!r)return;let f=Ni.addEventListener("hardwareBackPress",()=>(Ce(),!0));return()=>f.remove()},[s,r]);let _=wt(()=>{let f=B.getState().active_key;f&&E(C=>({...C,[f]:(C[f]||0)+1}))},[]);return l.length?U(a,{visible:!!s,title:y!=null?y:"",is_dark:n,close:Ce,reload:_,subscribeWebAtTop:S.subscribe,children:l.map(f=>U(ji,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:S,splash:t,bridge:i,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},K=St.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"}}),Ji=vt.memo(Hi);export{In as DefaultMiniAppSplash,et as MINIAPP_PLATFORM_URL,Ji as MiniAppHost,u as MiniAppHostError,Ce as closeMiniApp,Ln as configureMiniApp,Un as createMmkvStorage,Rt as createReactNativeBiometrics,Dn as createRnfsFileSystem,Ge as ensureMiniApp,P as getLocalMiniApp,Di as getMiniAppCatalog,ke as getMiniAppCatalogEntry,xi as getMiniAppStatuses,Pn as getMiniAppUpdate,li as installBundledMiniApp,bi as onMiniAppEvent,fi as openMiniApp,Ti as pauseMiniApp,Ii as pauseMiniAppDownloads,hi as preloadMiniApp,re as releaseSpeechFor,Oi as restoreMiniApp,Ci as resumeMiniApp,ki as resumeMiniAppDownloads,di as sendEventToWeb,ht as syncMiniAppCatalog,Ri as uninstallMiniApp,Li as updateMiniApp,zt as uploadToUrl,ft as useMiniAppDownload,_i as useMiniAppDownloadsPaused};
66
+ true;`},jn={partner:"partner_token",chatbox:"chatbox_token"},zn=(e,t)=>{let n={...e};for(let r of Object.values(jn))t.includes(r)||delete n[r];return n},bt=new Set,$e=async(e,t)=>{if(bt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);bt.add(e);try{return await t()}finally{bt.delete(e)}},Hr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Qe=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Hn=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:o,is_dark:i,close:a,app_id:l,instance_id:c,options:s,emit:d,isActive:g})=>{var P,M,v,S,w,q,Z,ie,we;let y=s==null?void 0:s.handlers,p={app_id:l,instance_id:c,close:a},f=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Kt(t);return $e(e,()=>Gt(h,g))}case"speech.start":{if(!d)throw f();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 u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let b of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[b])!==void 0){if(typeof t[b]!="boolean")throw new u("INVALID_PARAMS",`${b} ph\u1EA3i l\xE0 boolean`);h[b]=t[b]}return An(c,h,d,g)}case"speech.stop":return Sn(c);case Fe.scan:return En(c,wt(t),g,()=>{var h;return(h=s==null?void 0:s.haptic)==null?void 0:h.call(s,"notificationSuccess")});case Fe.start:{if(!d)throw f();return Pn(c,wt(t),d,g,()=>{var h;return(h=s==null?void 0:s.haptic)==null?void 0:h.call(s,"notificationSuccess")})}case Fe.stop:return Rn(c);case"uploadFiles":{let{task_id:h,...b}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return hn(sn(b),{instance_id:c,app_id:l,getContext:o,task_id:h,config:s==null?void 0:s.upload,emit:d,exclusivePick:$=>$e("uploadFiles.pick",$)})}case"uploadFiles.cancel":fn(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return gn(s==null?void 0:s.upload);case"getBiometricAvailability":return((P=s==null?void 0:s.biometrics)!=null?P:await ut()).getAvailability();case"authenticateBiometric":{let h=Qe(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let b=t==null?void 0:t.cancelButtonText;if(b!==void 0&&(typeof b!="string"||!b.trim()||b.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return $e(e,async()=>{var x;return((x=s==null?void 0:s.biometrics)!=null?x:await ut()).authenticate({reason:h,cancelButtonText:b})})}case"requestPayment":{let h=y==null?void 0:y.requestPayment;if(!h)throw f();let b=t==null?void 0:t.amount;if(typeof b!="number"||!Number.isFinite(b)||b<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let $={...t,amount:b,currency:Qe(t==null?void 0:t.currency,"currency")};return $e(e,()=>h($,p))}case"printImage":{let h=y==null?void 0:y.printImage;if(!h)throw f();let b=Qe(t==null?void 0:t.image,"image");await $e(e,()=>h({image:b},p));return}case"openScreen":if(!(y!=null&&y.openScreen))throw f();await y.openScreen({screen:Qe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},p);return;case"closeApp":a();return;case"openWebview":{let h=String((M=t==null?void 0:t.url)!=null?M:"");if(!/^https?:\/\//i.test(h))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(h):Tn.openURL(h));return}case"openLink":{let h=String((v=t==null?void 0:t.url)!=null?v:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(h):Tn.openURL(h))}catch(b){throw new u("NOT_SUPPORTED",String((w=(S=b==null?void 0:b.message)!=null?S:b)!=null?w:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(Z=s==null?void 0:s.showToast)==null||Z.call(s,String((q=t==null?void 0:t.message)!=null?q:""));return;case"haptic":{let h=Hr.has(t==null?void 0:t.type)?t.type:"selection";(ie=s==null?void 0:s.haptic)==null||ie.call(s,h);return}case"getSystemInfo":return{platform:zr.OS==="ios"?"ios":"android",appVersion:(we=s==null?void 0:s.app_version)!=null?we:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new u("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 x=n().access_token;if(!x)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return x}if(h!=="partner"&&h!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let b=jn[h];if(!r().includes(b))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${b} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let $=h==="partner"?n().partner_token:n().chatbox_token;if(!$)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${b}`);return $}case"getUserInfo":{let h=n().user;if(!h)throw new u("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 u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var _t=e=>`bundle:${e}`,xt=()=>`${O().file_system.document_dir}/miniapps`,Et=xt,Pt=(e,t,n="index.html",r=!1,o=[])=>{let i=`${Et()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:r,permissions:o}},vt=e=>{var t;O().storage.setString(_t(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Wr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,R=e=>{let t=O().storage.getString(_t(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:i}=JSON.parse(t);return Pt(e,n,r,!!o,Array.isArray(i)?i:[])}catch{return null}},le=e=>O().file_system.exists(e.entry_uri.replace("file://","")),Rt=async e=>{let t=R(e.app_id);return(t==null?void 0:t.version)===e.version&&await le(t)},Jn=async(e,t)=>{let n=O().file_system,r=`${Et()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(i=>!t.includes(i)).map(i=>n.remove(`${r}/${i}`).catch(()=>{})))},Yn=async e=>{var t;await((t=Ve[e])==null?void 0:t.catch(()=>{})),O().storage.setString(_t(e),""),await O().file_system.remove(`${Et()}/${e}`).catch(()=>{})},Ce=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Ve={},Kn=(e,t)=>{var i;let r=((i=Ve[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return Ve[e]=o,o.then(()=>{Ve[e]===o&&delete Ve[e]}),r},Jr=(e,t)=>{var o,i;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 l=((o=n[a])!=null?o:0)-((i=r[a])!=null?i:0);if(l)return l}return 0},Yr=({manifest:e,zip_path:t})=>Kn(e.app_id,async()=>{var i;let n=O().file_system,r=R(e.app_id);if(r&&Jr(r.version,e.version)>=0&&await le(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=Pt(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),vt(e),G("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Jn(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Ot=(e,{base_url:t,onProgress:n}={})=>{let r=O().file_system,o=null,i=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(i)throw new Ce},c=async()=>{var g;l();let s=R(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return vt(e),R(e.app_id);l();let d=r.download({url:t?Wr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,p)=>{var P;let f=p>0?p:(P=e.size)!=null?P:0;f>0&&(n==null||n(Math.min(1,y/f)))}});o=d;try{let{status:y}=await d.promise;if(l(),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 G("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let p=Pt(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(p.dir).catch(()=>{}),await r.mkdir(p.dir),await r.unzip(a,p.dir),vt(e),Jn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),p}catch(y){throw i?new Ce:y}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Kn(e.app_id,c),cancel:()=>{i=!0,o==null||o.cancel()}}},qe={},Kr=__DEV__?0:60*1e3,Wn={},Gn=(e,t)=>{var r,o;let n=R(e);return n&&Date.now()-((r=Wn[t])!=null?r:0)<Kr?Promise.resolve(n):((o=qe[e])!=null||(qe[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),l=await Ot(a,{base_url:t}).promise;return Wn[t]=Date.now(),l})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),R(e))).finally(()=>{qe[e]=void 0})),qe[e])};var et=new Map,Xn=(e,t)=>(et.set(e,t),()=>{et.get(e)===t&&et.delete(e)}),Gr=(e,t)=>{let n=et.get(e);return n?n(t):!1};import{useCallback as Xr,useEffect as Qn,useRef as Zn,useState as Qr}from"react";import{Animated as Ct,BackHandler as Zr,StyleSheet as tr,Text as Tt,TouchableOpacity as er,View as tt}from"react-native";import{jsx as me,jsxs as kt}from"react/jsx-runtime";var eo="#22C55E",It=({scanner:e})=>{let{vision:t,types:n,mode:r}=e,o=t.useCameraDevice("back"),[i,a]=Qr(!1),l=j(se,p=>p.last_value),c=j(se,p=>p.hit_tick),s=Zn(new Ct.Value(0)).current,d=t.useCodeScanner({codeTypes:n,onCodeScanned:Xr(p=>Cn(p),[])});Qn(()=>{let p=Zr.addEventListener("hardwareBackPress",()=>(St(),!0));return()=>p.remove()},[]);let g=Zn(c);Qn(()=>{if(c===g.current)return;s.setValue(1);let p=Ct.timing(s,{toValue:0,duration:350,useNativeDriver:!0});return p.start(),()=>p.stop()},[c,s]);let y=!!(o!=null&&o.hasTorch);return kt(tt,{style:r===ce.continuous?z.continuous:z.once,children:[o&&me(t.Camera,{style:tr.absoluteFill,device:o,isActive:!0,codeScanner:d,torch:i&&y?"on":"off",onError:p=>On(p.message)}),kt(tt,{style:z.frame_wrap,pointerEvents:"none",children:[me(tt,{style:z.frame}),me(Ct.View,{style:[z.frame,z.frame_hit,{opacity:s}]})]}),kt(tt,{style:z.footer,children:[me(er,{activeOpacity:.7,style:z.button,onPress:St,accessibilityRole:"button",children:me(Tt,{style:z.button_text,children:"\u0110\xF3ng"})}),me(Tt,{style:z.last_value,numberOfLines:1,children:l!=null?l:""}),y&&me(er,{activeOpacity:.7,style:[z.button,i&&z.button_on],onPress:()=>a(p=>!p),accessibilityRole:"button",children:me(Tt,{style:[z.button_text,i&&z.button_text_on],children:"\u0110\xE8n"})})]})]})},z=tr.create({continuous:{height:"38%",backgroundColor:"#000000",overflow:"hidden"},once:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},frame_wrap:{position:"absolute",top:0,left:0,right:0,bottom:0,alignItems:"center",justifyContent:"center"},frame:{width:"70%",aspectRatio:1.6,maxHeight:"60%",borderRadius:12,borderWidth:2,borderColor:"rgba(255,255,255,0.8)"},frame_hit:{position:"absolute",borderWidth:4,borderColor:eo},footer:{position:"absolute",left:12,right:12,bottom:12,flexDirection:"row",alignItems:"center",gap:8},last_value:{flex:1,textAlign:"center",color:"#FFFFFF",fontWeight:"600"},button:{paddingHorizontal:14,paddingVertical:8,borderRadius:999,backgroundColor:"rgba(0,0,0,0.6)"},button_on:{backgroundColor:"#FFFFFF"},button_text:{color:"#FFFFFF",fontWeight:"600"},button_text_on:{color:"#18181B"}});var H=Re({active_key:null,instances:{}}),nr=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},i)=>{var l;let a=(l=O().keep_alive)==null?void 0:l.max_webviews;H.setState(c=>{let s=t!=null?t:e.app_id,d={...c.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},g=Object.keys(d);return a&&a>0&&g.length>a&&g.filter(y=>y!==s).sort((y,p)=>d[y].last_used_at-d[p].last_used_at).slice(0,g.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},to=e=>nr(e,!0),no=e=>nr(e,!1),je=()=>H.setState({active_key:null}),nt=e=>{H.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var rr="catalog",ro="paused_apps",oo="removed_apps",io=10*1e3,so=2,ao=3e3,co=()=>{var e;try{return JSON.parse((e=O().storage.getString(rr))!=null?e:"{}")}catch{return{}}},E=Re({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),or=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},it=new Set,ir=e=>{let t=new Set,n=()=>O().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=O().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},re=ir(ro),ye=ir(oo);Jt(()=>{re.load(),ye.load();let e=co(),t={};Object.keys(e).filter(n=>!ye.has(n)).forEach(n=>{let r=R(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:re.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),E.setState({catalog:e,downloads:t})});var Dt=e=>j(E,t=>e?t.downloads[e]:void 0),lo=()=>j(E,e=>e.pause_reasons.length>0),ne=(...e)=>G("queue",...e),D=[],pe={},_=null,rt=new Set,_e={},Lt=new Set,fe=e=>{Lt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},po=e=>(Lt.add(e),()=>{Lt.delete(e)}),uo=()=>E.getState().downloads,W=(e,t)=>{let n=!!R(e),r=E.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,i={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};E.setState(a=>({downloads:{...a.downloads,[e]:i}})),(r==null?void 0:r.status)!==i.status||(r==null?void 0:r.version)!==i.version||(r==null?void 0:r.has_local)!==i.has_local?fe({type:"status_change",app_id:e,state:i}):r.progress!==i.progress&&fe({type:"progress",app_id:e,progress:i.progress,version:i.version})},ot=(e,t)=>{var n;(n=_e[e])==null||n.forEach(r=>r(t)),delete _e[e]},go=()=>E.getState().pause_reasons.length>0,he=e=>{var l;if(_)return;let t=e?D.indexOf(e):go()?-1:D.findIndex(c=>!re.has(c));if(t<0||t>=D.length)return;let[n]=D.splice(t,1),r=E.getState().catalog[n];if(!r){ot(n,R(n)),he();return}let o=Date.now();pe[n]=((l=pe[n])!=null?l:0)+1,W(n,{status:"downloading",progress:0,version:r.version,error:void 0});let i=0,a=Ot(r,{onProgress:c=>{let s=Math.floor(c*100);s!==i&&(i=s,W(n,{progress:s/100,version:r.version}))}});_={app_id:n,handle:a,forced:!!e},ne("start",n,r.version,e?"(forced)":""),a.promise.then(c=>{ne("installed",n,r.version,`${Date.now()-o}ms`),W(n,{status:"installed",progress:1,version:r.version}),ot(n,c)}).catch(c=>{var d;if(c instanceof Ce){if(rt.has(n))return;ne("paused",n),pe[n]-=1,D.unshift(n),W(n,{status:re.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=c==null?void 0:c.message)!=null?d:c);if(console.warn("[miniapp-queue] failed",n,s),pe[n]<so){W(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;D.includes(n)||(_==null?void 0:_.app_id)===n||(D.push(n),he((g=_e[n])!=null&&g.length?n:void 0))},ao);return}W(n,{status:"failed",progress:0,version:r.version,error:s}),ot(n,R(n))}).finally(()=>{_=null;let c=D.find(s=>{var d;return(d=_e[s])==null?void 0:d.length});he(c)})},st=(e,{front:t=!1}={})=>{if((_==null?void 0:_.app_id)===e)return;let n=D.indexOf(e);if(n>=0){if(!t)return;D.splice(n,1)}t?D.unshift(e):D.push(e)},mo=async e=>{let{host_id:t,client_token:n}=O(),r=new AbortController,o=setTimeout(()=>r.abort(),io);try{let i=`${pt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{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(c=>({...c,channel:e}))}finally{clearTimeout(o)}},ze=null,Nt=()=>(ze!=null||(ze=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(mo)),r={};[...n].reverse().flat().forEach(c=>{r[c.app_id]=c});let o=Object.keys(E.getState().catalog).filter(c=>!r[c]);O().storage.setString(rr,JSON.stringify(r)),E.setState({catalog:r}),await Promise.all(o.map(c=>sr(c,{by_user:!1}))),o.forEach(c=>ye.delete(c));let i=Object.keys(r).filter(c=>!ye.has(c)),a=[],l={};for(let c of i.map(s=>r[s])){if(await Rt(c)){W(c.app_id,{status:"installed",progress:1,version:c.version});continue}let s=R(c.app_id);if(or(c.app_id)&&!it.has(c.app_id)&&s&&await le(s)){W(c.app_id,{status:"installed",progress:1,version:s.version}),l[c.app_id]={app_id:c.app_id,current_version:s.version,next_version:c.version};continue}a.push(c)}return E.setState({updates:l}),a.forEach(c=>{pe[c.app_id]=0,W(c.app_id,{status:re.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),st(c.app_id)}),ne("catalog",i.length,"apps, outdated",a.map(c=>c.app_id),"removed",o,`${Date.now()-e}ms`),fe({type:"sync_complete",app_ids:i,removed:o}),Object.values(l).forEach(c=>fe({type:"update_available",...c})),he(),{ok:!0,app_ids:i,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),fe({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ze=null}})()),ze),sr=async(e,{by_user:t})=>{var o,i,a,l;if(t&&ye.add(e),rt.has(e))return;rt.add(e),re.delete(e);let n=D.indexOf(e);n>=0&&D.splice(n,1),(_==null?void 0:_.app_id)===e&&_.handle.cancel();let r=(l=(a=(o=E.getState().downloads[e])==null?void 0:o.version)!=null?a:(i=R(e))==null?void 0:i.version)!=null?l:"";W(e,{status:"uninstalling",progress:0,version:r}),await Yn(e),nt(e),E.setState(c=>{let s={...c.downloads};return delete s[e],{downloads:s}}),delete pe[e],rt.delete(e),ot(e,null),ne("uninstalled",e,t?"(user)":"(not in list)"),fe({type:"uninstalled",app_id:e})},fo=e=>sr(e,{by_user:!0}),ho=e=>{let t=He(e);return t?(ye.delete(e),(_==null?void 0:_.app_id)===e||D.includes(e)||(pe[e]=0,W(e,{status:re.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),st(e),he(),ne("restore",e)),!0):!1},yo=e=>{if(re.has(e))return;if(re.add(e),ne("pause app",e),(_==null?void 0:_.app_id)===e&&!_.forced){_.handle.cancel();return}let t=E.getState().downloads[e];D.includes(e)&&t&&W(e,{status:"paused",progress:0,version:t.version})},wo=e=>{if(!re.delete(e))return;ne("resume app",e);let t=E.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!D.includes(e)&&He(e)&&(pe[e]=0,st(e)),D.includes(e)&&t&&W(e,{status:"queued",progress:0,version:t.version}),he()},Ao=e=>{let{pause_reasons:t}=E.getState();t.includes(e)||(E.setState({pause_reasons:[...t,e]}),ne("pause",e),t.length===0&&fe({type:"pause_change",paused:!0,reasons:[e]}),_&&!_.forced&&_.handle.cancel())},So=e=>{let{pause_reasons:t}=E.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);E.setState({pause_reasons:n}),ne("resume",e),n.length===0&&fe({type:"pause_change",paused:!1,reasons:n}),he()},ar=e=>E.getState().updates[e],bo=async e=>{var n,r;let t=ar(e);it.add(e);try{let o=await at(e),i=(r=t==null?void 0:t.next_version)!=null?r:(n=He(e))==null?void 0:n.version;return!o||!i||o.version!==i?!1:(E.setState(a=>{var c;let l={...a.updates};return delete l[e],{updates:l,apply_ticks:{...a.apply_ticks,[e]:((c=a.apply_ticks[e])!=null?c:0)+1}}}),ne("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{it.delete(e)}},Mo=()=>Object.values(E.getState().catalog).map(e=>({...e,installed:!!R(e.app_id),removed_by_user:ye.has(e.app_id)})),He=e=>E.getState().catalog[e],at=async e=>{let t=He(e);if(!t)return;if(re.delete(e),ye.delete(e),await Rt(t))return R(e);let n=R(e);if(or(e)&&!it.has(e)&&n&&await le(n))return n;let r=new Promise(o=>{var i;((i=_e[e])!=null?i:_e[e]=[]).push(o)});return(_==null?void 0:_.app_id)===e?_.forced=!0:(pe[e]=0,st(e,{front:!0}),_&&!_.forced?_.handle.cancel():he(e)),r};import{Fragment as ur,jsx as F,jsxs as Je}from"react/jsx-runtime";var Ft=e=>(e!=null?e:"").replace(/\?[^#]*/,""),lr=0,Oo=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Co=qt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:i,splash:a,bridge:l,opaque_background:c,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var jt,zt;let g=oe(null),y=oe(!1),p=j(H,m=>m.instances[e]),f=p==null?void 0:p.app.app_id,P=p==null?void 0:p.app.manifest_url,M=p==null?void 0:p.context,v=p==null?void 0:p.url_params,S=j(se,m=>{var A;return((A=m.active)==null?void 0:A.owner)===e?m.active:null}),[w,q]=xe(()=>f?R(f):null),[Z,ie]=xe(!1),[we,h]=xe(0),[b,$]=xe(0),[x,k]=xe(!1),N=oe(null),B=m=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{N.current=null,k(!0)},m)};J(()=>()=>{N.current&&clearTimeout(N.current)},[]),J(()=>{if(!f||!t&&w)return;let m=!0;return ie(!1),(async()=>{let A=R(f),V=A?await le(A):!1;if(!m||(q(V?te=>!te||te.version!==A.version||te.permissions.join(",")!==A.permissions.join(",")?A:te:null),__DEV__&&Date.now()-lr>1e4&&(lr=Date.now(),await Nt()),!m))return;let ue=await at(f),Se=ue!==void 0?ue:P?await Gn(f,P):R(f);if(m){if(!Se){ie(!0);return}q(te=>te!=null?te:Se)}})(),()=>{m=!1}},[t,f,P,we]),J(()=>Xn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let C=j(E,m=>{let A=f?m.downloads[f]:void 0;return(A==null?void 0:A.status)==="installed"?A.version:void 0});J(()=>{if(t||!f||!w)return;let m=R(f);if(!m||m.version===w.version)return;let A=!0;return le(m).then(V=>{!A||!V||(G(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",w.version,"\u2192",m.version),q(m))}),()=>{A=!1}},[t,f,C,w==null?void 0:w.version]);let Y=j(E,m=>{var A;return f&&(A=m.apply_ticks[f])!=null?A:0});J(()=>{if(!Y||!f)return;let m=R(f);if(!m||m.version===(w==null?void 0:w.version))return;let A=!0;return le(m).then(V=>{!A||!V||(G(`webview:${e}`,"c\u1EADp nh\u1EADt",w==null?void 0:w.version,"\u2192",m.version),k(!1),q(m))}),()=>{A=!1}},[Y]),J(()=>{var V;let m=(V=O().keep_alive)==null?void 0:V.idle_close_ms;if(t||!m||m<=0)return;let A=setTimeout(()=>{nt(e)},m);return()=>clearTimeout(A)},[t,e]),J(()=>{o>0&&(ie(!1),k(!1),$(m=>m+1),h(m=>m+1))},[o]);let Te=oe(t);J(()=>{var m;Te.current!==t&&(Te.current=t,y.current&&((m=g.current)==null||m.injectJavaScript($n(t?"resumed":"paused"))))},[t]);let Ae=`${(jt=w==null?void 0:w.version)!=null?jt:"none"}:${(zt=w==null?void 0:w.permissions.join(","))!=null?zt:""}:${b}`,ee=ct(()=>JSON.stringify([M!=null?M:{},v!=null?v:{}]),[M,v]),ke=ct(()=>{var m;return zn(v!=null?v:{},(m=w==null?void 0:w.permissions)!=null?m:[])},[ee,w==null?void 0:w.permissions]),Ee=ct(()=>Vn(M!=null?M:{},ke)+Un()+(Eo.OS==="android"?Fn():"")+(O().debug?Nn():""),[ke]),Pe=oe(null),Ie=oe(null);J(()=>{var A,V,ue;if(!w)return;if(Ie.current!==Ae){Ie.current=Ae,Pe.current=ee;return}if(Pe.current===ee)return;let m=((V=JSON.parse((A=Pe.current)!=null?A:"[]")[0])!=null?V:{}).org_id;if(Pe.current=ee,m===(M==null?void 0:M.org_id)&&y.current){k(!1),B(1500),(ue=g.current)==null||ue.injectJavaScript(Bn(M!=null?M:{},ke));return}k(!1),$(Se=>Se+1)},[ee,w,Ae]),J(()=>(t||(ae(e),ge(e),ve(e)),()=>{ae(e),ge(e),ve(e)}),[t,e,Ae,o]),J(()=>{let m=cr.addEventListener("change",A=>{A==="background"&&!wn()&&ae(e),A==="background"&&!vn()&&ge(e)});return()=>m.remove()},[e]);let gr=$t(async m=>{var V,ue,Se,te,lt;let A=kn(m.nativeEvent.data);if(!A){if(f&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(m.nativeEvent.data,{app_id:f,instance_id:e})).catch(T=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,T)})}catch(T){console.warn("[miniapp] onWebEvent l\u1ED7i",f,T)}return}if(A.method==="log"){let{level:T,text:U}=A;G(`web:${e}`,T!=null?T:"log",U!=null?U:"");return}if(A.method==="pong"){N.current||k(!0);return}if(A.method==="touchAtTop"){i.emit(!!A.at_top);return}if(A.method==="contextApplied"){N.current&&clearTimeout(N.current),N.current=null,k(!0);return}if(A.method==="ready"){y.current=!0,k(!0);let T=(V=H.getState().instances[e])==null?void 0:V.context;T&&((ue=g.current)==null||ue.injectJavaScript(Mt(T)));return}try{let T=await Hn(A,{getHostData:()=>{var U,K;return(K=(U=H.getState().instances[e])==null?void 0:U.host_data)!=null?K:{}},getPermissions:()=>{var U,K;return f?(K=(U=R(f))==null?void 0:U.permissions)!=null?K:[]:[]},getContext:()=>{var U,K;return(K=(U=H.getState().instances[e])==null?void 0:U.context)!=null?K:{}},is_dark:r,close:je,app_id:f!=null?f:"",instance_id:e,options:l,emit:(U,K)=>{var Ht;(Ht=g.current)==null||Ht.injectJavaScript(Dn(U,K))},isActive:()=>H.getState().active_key===e&&cr.currentState!=="background"});A.id&&((Se=g.current)==null||Se.injectJavaScript(In(A.id,T)))}catch(T){if(!A.id)return;let U=T==null?void 0:T.code,K=T instanceof u?T:new u(typeof U=="string"?U:"HOST_ERROR",String((te=T==null?void 0:T.message)!=null?te:T));(lt=g.current)==null||lt.injectJavaScript(Ln(A.id,K))}},[e,r,f,i,l]),mr=$t(()=>{ie(!1),$(m=>m+1),h(m=>m+1)},[]);return Je(Bt,{style:[Vt.absoluteFill,c&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&Q.behind],pointerEvents:t?"auto":"none",children:[(S==null?void 0:S.mode)===ce.continuous&&F(It,{scanner:S}),w?F(Ro,{ref:g,source:{uri:w.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,allowingReadAccessToURL:`file://${s?xt():w.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ee,onMessage:gr,bounces:!1,overScrollMode:"never",onLoadStart:m=>{ae(e),ge(e),ve(e),G(`webview:${e}`,"load start",Ft(m.nativeEvent.url)),y.current=!1,k(!1)},onError:m=>{ae(e),ge(e),ve(e),G(`webview:${e}`,"load error",Ft(m.nativeEvent.url),m.nativeEvent.description),ie(!0),k(!1)},onLoadEnd:m=>{let A=m.nativeEvent.url;G(`webview:${e}`,"load end",Ft(A)),f&&(d==null||d({app_id:f,instance_id:e,url:A})),B(1500)},onContentProcessDidTerminate:()=>{ae(e),ge(e),ve(e),y.current=!1,k(!1),$(m=>m+1)},onRenderProcessGone:()=>(ae(e),ge(e),ve(e),y.current=!1,k(!1),$(m=>m+1),!0),style:Q.webview},Ae):null,(S==null?void 0:S.mode)===ce.once&&F(It,{scanner:S}),p&&F(ko,{visible:!w||!x,interactive:Z,children:F(To,{splash:a,app:p.app,is_dark:r,error:Z,has_bundle:!!w,retry:mr})})]})}),To=qt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:i})=>{let a=e,l=Dt(t.app_id),c=r?"error":!o&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return F(a,{app:t,is_dark:n,status:c,progress:c==="downloading"?l==null?void 0:l.progress:void 0,retry:i})}),ko=({visible:e,interactive:t,children:n})=>{let r=oe(new Ut.Value(e?1:0)).current,[o,i]=xe(e);return J(()=>{if(e){i(!0),r.setValue(1);return}let a=Ut.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:l})=>{l&&i(!1)}),()=>a.stop()},[e,r]),o?F(Ut.View,{style:[Vt.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},dr=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let i=t?"#FAFAFA":"#18181B";return Je(Bt,{style:[Q.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[F(Bt,{style:[Q.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?F(xo,{source:{uri:e.icon},style:Q.splash_icon_image}):F(We,{style:Q.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),F(We,{style:[Q.splash_name,{color:i}],children:e.name}),n==="error"?Je(ur,{children:[F(We,{style:Q.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),F(Po,{activeOpacity:.7,style:[Q.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:F(We,{style:[Q.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):Je(ur,{children:[F(vo,{style:Q.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Je(We,{style:Q.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},pr=(e,t)=>{let n=oe(t),r=oe(!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.`))},Io=({container:e,splash:t=dr,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:l})=>{pr("container",e),pr("splash",t);let c=e,s=j(H,S=>S.active_key),d=oe(s);s&&(d.current=s);let g=j(H,S=>Object.keys(S.instances).join("|")),y=j(H,S=>{var w;return S.active_key?(w=S.instances[S.active_key])==null?void 0:w.app.name:void 0}),p=ct(()=>g?g.split("|"):[],[g]),[f,P]=xe({}),M=oe(Oo()).current;J(()=>{if(!s||!o)return;let S=_o.addEventListener("hardwareBackPress",()=>(je(),!0));return()=>S.remove()},[s,o]);let v=$t(()=>{let S=H.getState().active_key;S&&P(w=>({...w,[S]:(w[S]||0)+1}))},[]);return p.length?F(c,{visible:!!s,title:y!=null?y:"",is_dark:n,close:je,reload:v,subscribeWebAtTop:M.subscribe,children:p.map(S=>F(Co,{instance_key:S,is_active:s===S,is_front:(s!=null?s:d.current)===S,is_dark:n,reload_tick:f[S]||0,web_at_top:M,splash:t,bridge:r,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:l},S))}):null},Q=Vt.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"}}),Lo=qt.memo(Io);export{ht as CodeType,dr as DefaultMiniAppSplash,pt as MINIAPP_PLATFORM_URL,Lo as MiniAppHost,u as MiniAppHostError,Oe as ScannerEndReason,yt as ScannerEvent,Fe as ScannerMethod,je as closeMiniApp,fr as configureMiniApp,yr as createMmkvStorage,Yt as createReactNativeBiometrics,hr as createRnfsFileSystem,at as ensureMiniApp,R as getLocalMiniApp,Mo as getMiniAppCatalog,He as getMiniAppCatalogEntry,uo as getMiniAppStatuses,ar as getMiniAppUpdate,Yr as installBundledMiniApp,po as onMiniAppEvent,to as openMiniApp,yo as pauseMiniApp,Ao as pauseMiniAppDownloads,no as preloadMiniApp,ae as releaseSpeechFor,ho as restoreMiniApp,wo as resumeMiniApp,So as resumeMiniAppDownloads,Gr as sendEventToWeb,Nt as syncMiniAppCatalog,fo as uninstallMiniApp,bo as updateMiniApp,un as uploadToUrl,Dt as useMiniAppDownload,lo as useMiniAppDownloadsPaused};
@@ -256,6 +256,62 @@ Kết quả: `{ coords: { latitude, longitude, accuracy, altitude, altitudeAccur
256
256
 
257
257
  Web chờ tối đa khoảng 2 phút + `timeout` (gồm thời gian người dùng trả lời hộp xin quyền).
258
258
 
259
+ ### Quét mã QR / barcode
260
+
261
+ Cần `@retion-miniapp/react-native` và `@retion-miniapp/sdk` từ **0.11.0**.
262
+
263
+ **Luồng:** web gọi API → host giữ phiên, xin quyền camera → host hiện camera → mã trả về web. App chủ không phải viết handler hay UI.
264
+
265
+ ```ts
266
+ import { scanCode, startScanner, stopScanner, onScanner, CodeType, ScannerEvent, ScannerEndReason } from '@retion-miniapp/sdk';
267
+
268
+ // Quét một lần: có mã thì tự đóng camera
269
+ try {
270
+ const { value, type } = await scanCode({ types: [CodeType.qr] });
271
+ } catch (error) {
272
+ // error.code === 'CANCELLED' khi người dùng đóng camera
273
+ }
274
+
275
+ // Quét liên tiếp: đăng ký event trước khi mở camera
276
+ const off_result = onScanner(ScannerEvent.result, ({ value, type }) => addToCart(value));
277
+ const off_end = onScanner(ScannerEvent.end, ({ reason, message }) => {
278
+ off_result();
279
+ off_end();
280
+ if (reason === ScannerEndReason.error) console.error(message);
281
+ });
282
+ await startScanner({ types: CodeType.all, cooldown_ms: 1500 });
283
+ // Đóng từ web nếu cần; người dùng cũng có nút Đóng trên camera
284
+ await stopScanner();
285
+ ```
286
+
287
+ - `scanCode`: camera phủ kín vùng mini app, trả một mã rồi tự đóng.
288
+ - `startScanner`: camera chiếm khoảng 38% phía trên, web thu lại ở phần dưới và vẫn thao tác được, phù hợp quầy thu ngân cần thấy giỏ hàng cập nhật. Camera mở đến khi người dùng bấm Đóng hoặc web gọi `stopScanner()`.
289
+ - Camera có nút Đóng, đèn pin (nếu máy có) và nháy khung xanh khi nhận mã. Nút Back Android đóng camera trước, chưa đóng mini app.
290
+ - Rung khi nhận mã dùng `bridge.haptic` với `notificationSuccess`; app chưa truyền `bridge.haptic` thì không rung.
291
+ - `scanCode` chờ tối đa 10 phút phía web. Hết thời gian chờ không tự đóng camera; gọi `stopScanner()` nếu không còn cần.
292
+
293
+ | Hằng | Giá trị |
294
+ | --- | --- |
295
+ | `CodeType` | `qr`, `ean13`, `ean8`, `upcA`, `upcE`, `code128`, `code39`, `code93`, `codabar`, `itf`, `pdf417`, `aztec`, `dataMatrix`; `CodeType.all` là mảng gồm tất cả, cũng là mặc định khi bỏ trống `types` |
296
+ | `ScannerEvent` | `result`: `{ value, type }`; `end`: `{ reason, message? }` |
297
+ | `ScannerEndReason` | `user`: người dùng đóng; `web`: web gọi `stopScanner()`; `closed`: mini app đóng/ẩn, reload hoặc app xuống nền; `error`: lỗi camera, có `message` |
298
+
299
+ | Tuỳ chọn | Mặc định | Ý nghĩa |
300
+ | --- | --- | --- |
301
+ | `types` | `CodeType.all` | Loại mã cần quét; quét ít loại hơn thì nhanh và ít nhận nhầm hơn |
302
+ | `cooldown_ms` | `1500` | Chỉ `startScanner`, 0–60000 ms: thời gian trước khi nhận lại **cùng một mã**. Mã khác nhận ngay. Giữ nguyên mã trước camera thì được tính thêm một lần sau mỗi cooldown |
303
+
304
+ | Mã lỗi | Ý nghĩa |
305
+ | --- | --- |
306
+ | `CANCELLED` | Đóng camera trước khi có mã (`scanCode`), hoặc mini app đóng lúc đang xin quyền |
307
+ | `PERMISSION_DENIED` | Chưa cấp quyền camera; hướng dẫn bật lại trong Cài đặt |
308
+ | `BUSY` | Đang có phiên quét khác; cả máy chỉ có một phiên |
309
+ | `NOT_SUPPORTED` | Binary thiếu module camera, hoặc thiết bị không có camera sau |
310
+ | `INVALID_PARAMS` | `types` hoặc `cooldown_ms` không hợp lệ |
311
+ | `HOST_ERROR` | Lỗi camera trong lúc `scanCode` |
312
+
313
+ **Native:** package dùng `react-native-vision-camera` 4.7.3. Plugin Expo tự thêm quyền `CAMERA` và nhúng sẵn model quét mã Android (khoảng 2,4 MB). Mô tả quyền iOS tuỳ chỉnh qua `cameraPermission`. React Native thuần cần thêm `VisionCamera_enableCodeScanner=true` vào `android/gradle.properties`, quyền `android.permission.CAMERA` vào manifest, `NSCameraUsageDescription` vào `Info.plist`, và bổ sung `react-native-vision-camera` vào `react-native.config.js` nếu CLI chỉ dò dependency trực tiếp. Tính năng này phải build lại native, không cập nhật được qua OTA.
314
+
259
315
  ### Chức năng native: thanh toán, in, mở màn hình
260
316
 
261
317
  Web gọi qua `@retion-miniapp/sdk` (`requestPayment`, `printImage`, `openScreen`), ứng dụng cài
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.10.4",
3
+ "version": "0.11.1",
4
4
  "description": "React Native host for Retion Mini Apps with built-in biometric authentication",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -93,6 +93,7 @@
93
93
  "expo-speech-recognition": "1.1.1",
94
94
  "react-native-biometrics": "3.0.1",
95
95
  "react-native-compressor": "1.13.0",
96
- "react-native-image-picker": "8.2.1"
96
+ "react-native-image-picker": "8.2.1",
97
+ "react-native-vision-camera": "4.7.3"
97
98
  }
98
99
  }