@retion-miniapp/react-native 0.7.5 → 0.7.7

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 ADDED
@@ -0,0 +1,20 @@
1
+ // Expo prebuild plugin. Bare React Native hosts set NSFaceIDUsageDescription in Info.plist.
2
+ const { withInfoPlist, withAndroidManifest } = require('expo/config-plugins');
3
+
4
+ module.exports = function withMiniApp(config, options = {}) {
5
+ config = withInfoPlist(config, config => {
6
+ config.modResults.NSFaceIDUsageDescription = options.faceIDPermission
7
+ || config.modResults.NSFaceIDUsageDescription
8
+ || 'Allow this app to use Face ID to verify your identity.';
9
+ return config;
10
+ });
11
+ return withAndroidManifest(config, config => {
12
+ const manifest = config.modResults.manifest;
13
+ const permissions = manifest['uses-permission'] || [];
14
+ if (!permissions.some(item => item.$?.['android:name'] === 'android.permission.USE_BIOMETRIC')) {
15
+ permissions.push({ $: { 'android:name': 'android.permission.USE_BIOMETRIC' } });
16
+ }
17
+ manifest['uses-permission'] = permissions;
18
+ return config;
19
+ });
20
+ };
package/dist/index.d.mts CHANGED
@@ -159,6 +159,8 @@ interface MiniAppNativeHandlers {
159
159
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
160
  /** Hành vi bridge phụ thuộc ứng dụng. */
161
161
  interface MiniAppBridgeOptions {
162
+ /** Optional override. Omit to use the built-in biometric implementation. */
163
+ biometrics?: MiniAppBiometrics;
162
164
  /** Web gọi showToast(). Không truyền → bỏ qua. */
163
165
  showToast?: (message: string) => void;
164
166
  /** Web gọi haptic(type) (lệnh 1 chiều). Không truyền → bỏ qua. */
@@ -178,6 +180,22 @@ interface MiniAppBridgeOptions {
178
180
  instance_id: string;
179
181
  }) => void | Promise<void>;
180
182
  }
183
+ /** Biometric verification on this device; does not issue a backend login token. */
184
+ type MiniAppBiometryType = 'FaceID' | 'TouchID' | 'Biometrics';
185
+ interface MiniAppBiometricAvailability {
186
+ available: boolean;
187
+ biometryType?: MiniAppBiometryType;
188
+ }
189
+ interface MiniAppBiometricRequest {
190
+ reason: string;
191
+ cancelButtonText?: string;
192
+ }
193
+ interface MiniAppBiometrics {
194
+ getAvailability: () => Promise<MiniAppBiometricAvailability>;
195
+ authenticate: (request: MiniAppBiometricRequest) => Promise<{
196
+ success: true;
197
+ }>;
198
+ }
181
199
 
182
200
  /** Giới hạn WebView sống — không truyền thì giữ mọi WebView (mở lại tức thì, tốn RAM hơn). */
183
201
  interface MiniAppKeepAlive {
@@ -500,4 +518,23 @@ declare class BridgeError extends Error {
500
518
  constructor(code: string, message: string);
501
519
  }
502
520
 
503
- export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, closeMiniApp, configureMiniApp, createMmkvStorage, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
521
+ /** Pass a react-native-biometrics instance created with allowDeviceCredentials: false. */
522
+ interface ReactNativeBiometricsLike {
523
+ isSensorAvailable(): Promise<{
524
+ available: boolean;
525
+ biometryType?: string;
526
+ error?: string;
527
+ }>;
528
+ simplePrompt(options: {
529
+ promptMessage: string;
530
+ cancelButtonText?: string;
531
+ fallbackPromptMessage: string;
532
+ }): Promise<{
533
+ success: boolean;
534
+ error?: string;
535
+ }>;
536
+ }
537
+ /** Native-module injection keeps the host package independent of the app's native dependencies. */
538
+ declare const createReactNativeBiometrics: (native: ReactNativeBiometricsLike) => MiniAppBiometrics;
539
+
540
+ export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.d.ts CHANGED
@@ -159,6 +159,8 @@ interface MiniAppNativeHandlers {
159
159
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
160
  /** Hành vi bridge phụ thuộc ứng dụng. */
161
161
  interface MiniAppBridgeOptions {
162
+ /** Optional override. Omit to use the built-in biometric implementation. */
163
+ biometrics?: MiniAppBiometrics;
162
164
  /** Web gọi showToast(). Không truyền → bỏ qua. */
163
165
  showToast?: (message: string) => void;
164
166
  /** Web gọi haptic(type) (lệnh 1 chiều). Không truyền → bỏ qua. */
@@ -178,6 +180,22 @@ interface MiniAppBridgeOptions {
178
180
  instance_id: string;
179
181
  }) => void | Promise<void>;
180
182
  }
183
+ /** Biometric verification on this device; does not issue a backend login token. */
184
+ type MiniAppBiometryType = 'FaceID' | 'TouchID' | 'Biometrics';
185
+ interface MiniAppBiometricAvailability {
186
+ available: boolean;
187
+ biometryType?: MiniAppBiometryType;
188
+ }
189
+ interface MiniAppBiometricRequest {
190
+ reason: string;
191
+ cancelButtonText?: string;
192
+ }
193
+ interface MiniAppBiometrics {
194
+ getAvailability: () => Promise<MiniAppBiometricAvailability>;
195
+ authenticate: (request: MiniAppBiometricRequest) => Promise<{
196
+ success: true;
197
+ }>;
198
+ }
181
199
 
182
200
  /** Giới hạn WebView sống — không truyền thì giữ mọi WebView (mở lại tức thì, tốn RAM hơn). */
183
201
  interface MiniAppKeepAlive {
@@ -500,4 +518,23 @@ declare class BridgeError extends Error {
500
518
  constructor(code: string, message: string);
501
519
  }
502
520
 
503
- export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, closeMiniApp, configureMiniApp, createMmkvStorage, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
521
+ /** Pass a react-native-biometrics instance created with allowDeviceCredentials: false. */
522
+ interface ReactNativeBiometricsLike {
523
+ isSensorAvailable(): Promise<{
524
+ available: boolean;
525
+ biometryType?: string;
526
+ error?: string;
527
+ }>;
528
+ simplePrompt(options: {
529
+ promptMessage: string;
530
+ cancelButtonText?: string;
531
+ fallbackPromptMessage: string;
532
+ }): Promise<{
533
+ success: boolean;
534
+ error?: string;
535
+ }>;
536
+ }
537
+ /** Native-module injection keeps the host package independent of the app's native dependencies. */
538
+ declare const createReactNativeBiometrics: (native: ReactNativeBiometricsLike) => MiniAppBiometrics;
539
+
540
+ export { DefaultMiniAppSplash, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, useMiniAppDownload, useMiniAppDownloadsPaused };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var en=Object.create;var Ae=Object.defineProperty;var tn=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var rn=Object.getPrototypeOf,on=Object.prototype.hasOwnProperty;var sn=(e,t)=>{for(var n in t)Ae(e,n,{get:t[n],enumerable:!0})},Xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nn(t))!on.call(e,s)&&s!==n&&Ae(e,s,{get:()=>t[s],enumerable:!(r=tn(t,s))||r.enumerable});return e};var Ze=(e,t,n)=>(n=e!=null?en(rn(e)):{},Xe(t||!e||!e.__esModule?Ae(n,"default",{value:e,enumerable:!0}):n,e)),an=e=>Xe(Ae({},"__esModule",{value:!0}),e);var xn={};sn(xn,{DefaultMiniAppSplash:()=>je,MINIAPP_PLATFORM_URL:()=>me,MiniAppHost:()=>Kt,MiniAppHostError:()=>E,closeMiniApp:()=>ie,configureMiniApp:()=>tt,createMmkvStorage:()=>it,createRnfsFileSystem:()=>rt,ensureMiniApp:()=>ge,getLocalMiniApp:()=>S,getMiniAppCatalog:()=>Ht,getMiniAppCatalogEntry:()=>oe,getMiniAppStatuses:()=>Dt,getMiniAppUpdate:()=>He,installBundledMiniApp:()=>_t,onMiniAppEvent:()=>It,openMiniApp:()=>Rt,pauseMiniApp:()=>Bt,pauseMiniAppDownloads:()=>Jt,preloadMiniApp:()=>Tt,restoreMiniApp:()=>Nt,resumeMiniApp:()=>Ft,resumeMiniAppDownloads:()=>Ut,sendEventToWeb:()=>xt,syncMiniAppCatalog:()=>Pe,uninstallMiniApp:()=>$t,updateMiniApp:()=>Vt,useMiniAppDownload:()=>Re,useMiniAppDownloadsPaused:()=>Ot});module.exports=an(xn);var me="https://retion-miniapp-platform.vercel.app",ee=null,et=new Set,tt=e=>{ee=e,et.forEach(t=>t())},x=()=>{if(!ee)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ee},nt=e=>{et.add(e),ee&&e()},N=(...e)=>{ee!=null&&ee.debug&&console.log("[miniapp]",...e)};var rt=(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(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),it=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=Ze(require("react")),_=require("react-native"),qt=Ze(require("react-native-webview"));var ce=require("react-native"),Me=1,E=class extends Error{constructor(n,r){super(r);this.code=n}},st=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Me&&typeof t.method=="string"?t:null}catch{return null}},ye=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,at=(e,t)=>ye({id:e,result:t}),pt=(e,t)=>ye({id:e,error:{code:t.code,message:t.message}}),De=e=>ye({event:"context",data:e});var ct=()=>`(function () {
1
+ "use strict";var rn=Object.create;var Ae=Object.defineProperty;var on=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var pn=(e,t)=>{for(var n in t)Ae(e,n,{get:t[n],enumerable:!0})},it=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of sn(t))!cn.call(e,s)&&s!==n&&Ae(e,s,{get:()=>t[s],enumerable:!(r=on(t,s))||r.enumerable});return e};var Le=(e,t,n)=>(n=e!=null?rn(an(e)):{},it(t||!e||!e.__esModule?Ae(n,"default",{value:e,enumerable:!0}):n,e)),ln=e=>it(Ae({},"__esModule",{value:!0}),e);var Pn={};pn(Pn,{DefaultMiniAppSplash:()=>Ge,MINIAPP_PLATFORM_URL:()=>Me,MiniAppHost:()=>Gt,MiniAppHostError:()=>m,closeMiniApp:()=>oe,configureMiniApp:()=>st,createMmkvStorage:()=>pt,createReactNativeBiometrics:()=>Be,createRnfsFileSystem:()=>ct,ensureMiniApp:()=>fe,getLocalMiniApp:()=>b,getMiniAppCatalog:()=>Kt,getMiniAppCatalogEntry:()=>se,getMiniAppStatuses:()=>$t,getMiniAppUpdate:()=>Ye,installBundledMiniApp:()=>Et,onMiniAppEvent:()=>Nt,openMiniApp:()=>Ct,pauseMiniApp:()=>Jt,pauseMiniAppDownloads:()=>Wt,preloadMiniApp:()=>Ot,restoreMiniApp:()=>Vt,resumeMiniApp:()=>Ht,resumeMiniAppDownloads:()=>jt,sendEventToWeb:()=>Rt,syncMiniAppCatalog:()=>Oe,uninstallMiniApp:()=>Ut,updateMiniApp:()=>qt,useMiniAppDownload:()=>ke,useMiniAppDownloadsPaused:()=>Bt});module.exports=ln(Pn);var Me="https://retion-miniapp-platform.vercel.app",ne=null,ot=new Set,st=e=>{ne=e,ot.forEach(t=>t())},T=()=>{if(!ne)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ne},at=e=>{ot.add(e),ne&&e()},N=(...e)=>{ne!=null&&ne.debug&&console.log("[miniapp]",...e)};var ct=(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(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),pt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var d=Le(require("react")),S=require("react-native"),Qt=Le(require("react-native-webview"));var le=require("react-native");var Be=e=>({getAvailability:async()=>{var r;let t=await e.isSensorAvailable(),n=["FaceID","TouchID","Biometrics"].includes((r=t.biometryType)!=null?r:"")?t.biometryType:void 0;return{available:t.available,...n?{biometryType:n}:{}}},authenticate:async({reason:t,cancelButtonText:n})=>{try{let{available:r}=await e.isSensorAvailable();if(!r)throw new m("BIOMETRIC_UNAVAILABLE","Biometrics unavailable, not enrolled or permission denied");let s=await e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""});if(!s.success)throw new m("CANCELLED",s.error||"Biometric authentication cancelled");return{success:!0}}catch(r){throw r instanceof m?r:new m("AUTHENTICATION_FAILED",r instanceof Error?r.message:String(r))}}}),ye,Ne=()=>(ye||(ye=import("react-native-biometrics").then(({default:e})=>Be(new e({allowDeviceCredentials:!1}))).catch(e=>{throw ye=void 0,new m("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),ye);var ve=1,m=class extends Error{constructor(n,r){super(r);this.code=n}},lt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===ve&&typeof t.method=="string"?t:null}catch{return null}},_e=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,ut=(e,t)=>_e({id:e,result:t}),dt=(e,t)=>_e({id:e,error:{code:t.code,message:t.message}}),Ue=e=>_e({event:"context",data:e});var gt=()=>`(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: ${Me}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${ve}, 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;`,lt=()=>`(function () {
22
+ })(); true;`,ft=()=>`(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: ${Me}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${ve}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,8 @@
38
38
  var el = e.target === document ? document.documentElement : e.target;
39
39
  if (el && el.scrollTop > 0) { report(false); }
40
40
  }, { capture: true, passive: true });
41
- })(); true;`,ut=e=>ye({event:e}),dt=(e,t)=>{let n=gt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${De(e)}`},gt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ft=(e,t={})=>{let n=gt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Me} };
41
+ })(); true;`,ht=e=>_e({event:e}),mt=(e,t)=>{let n=At(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
+ ${Ue(e)}`},At=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Mt=(e,t={})=>{let n=At(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${ve} };
43
43
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
44
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},ht={partner:"partner_token",chatbox:"chatbox_token"},At=(e,t)=>{let n={...e};for(let r of Object.values(ht))t.includes(r)||delete n[r];return n},Oe=new Set,ot=async(e,t)=>{if(Oe.has(e))throw new E("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Oe.add(e);try{return await t()}finally{Oe.delete(e)}},pn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Ie=(e,t)=>{if(typeof e!="string"||!e)throw new E("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},mt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var w,m,f,F,P,D,l,C;let c=i==null?void 0:i.handlers,M={app_id:a,instance_id:u,close:o},y=()=>new E("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let h=c==null?void 0:c.requestPayment;if(!h)throw y();let T=t==null?void 0:t.amount;if(typeof T!="number"||!Number.isFinite(T)||T<=0)throw new E("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let ne={...t,amount:T,currency:Ie(t==null?void 0:t.currency,"currency")};return ot(e,()=>h(ne,M))}case"printImage":{let h=c==null?void 0:c.printImage;if(!h)throw y();let T=Ie(t==null?void 0:t.image,"image");await ot(e,()=>h({image:T},M));return}case"openScreen":if(!(c!=null&&c.openScreen))throw y();await c.openScreen({screen:Ie(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},M);return;case"closeApp":o();return;case"openWebview":{let h=String((w=t==null?void 0:t.url)!=null?w:"");if(!/^https?:\/\//i.test(h))throw new E("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(h):ce.Linking.openURL(h));return}case"openLink":{let h=String((m=t==null?void 0:t.url)!=null?m:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new E("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(h):ce.Linking.openURL(h))}catch(T){throw new E("NOT_SUPPORTED",String((F=(f=T==null?void 0:T.message)!=null?f:T)!=null?F:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(D=i==null?void 0:i.showToast)==null||D.call(i,String((P=t==null?void 0:t.message)!=null?P:""));return;case"haptic":{let h=pn.has(t==null?void 0:t.type)?t.type:"selection";(l=i==null?void 0:i.haptic)==null||l.call(i,h);return}case"getSystemInfo":return{platform:ce.Platform.OS==="ios"?"ios":"android",appVersion:(C=i==null?void 0:i.app_version)!=null?C:"",theme:s?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new E("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 se=n().access_token;if(!se)throw new E("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return se}if(h!=="partner"&&h!=="chatbox")throw new E("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let T=ht[h];if(!r().includes(T))throw new E("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${T} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let ne=h==="partner"?n().partner_token:n().chatbox_token;if(!ne)throw new E("HOST_ERROR",`Kh\xF4ng c\xF3 ${T}`);return ne}case"getUserInfo":{let h=n().user;if(!h)throw new E("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 E("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new E("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new E("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var $e=e=>`bundle:${e}`,Ne=()=>`${x().file_system.document_dir}/miniapps`,Be=Ne,Fe=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Be()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Le=e=>{var t;x().storage.setString($e(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},cn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,S=e=>{let t=x().storage.getString($e(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Fe(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>x().file_system.exists(e.entry_uri.replace("file://","")),Je=async e=>{let t=S(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},yt=async(e,t)=>{let n=x().file_system,r=`${Be()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},wt=async e=>{var t;await((t=ue[e])==null?void 0:t.catch(()=>{})),x().storage.setString($e(e),""),await x().file_system.remove(`${Be()}/${e}`).catch(()=>{})},re=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ue={},vt=(e,t)=>{var o;let r=((o=ue[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return ue[e]=s,s.then(()=>{ue[e]===s&&delete ue[e]}),r},ln=(e,t)=>{var s,o;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 u=((s=n[a])!=null?s:0)-((o=r[a])!=null?o:0);if(u)return u}return 0},_t=({manifest:e,zip_path:t})=>vt(e.app_id,async()=>{var o;let n=x().file_system,r=S(e.app_id);if(r&&ln(r.version,e.version)>=0&&await q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=Fe(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),Le(e),N("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),yt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Ue=(e,{base_url:t,onProgress:n}={})=>{let r=x().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new re},i=async()=>{var y;u();let c=S(e.app_id);if((c==null?void 0:c.version)===e.version&&await r.exists(c.dir))return Le(e),S(e.app_id);u();let M=r.download({url:t?cn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(w,m)=>{var F;let f=m>0?m:(F=e.size)!=null?F:0;f>0&&(n==null||n(Math.min(1,w/f)))}});s=M;try{let{status:w}=await M.promise;if(u(),w!==200)throw new Error(`bundle ${w}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else N("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let m=Fe(e.app_id,e.version,e.entry,!!e.context_update,(y=e.permissions)!=null?y:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),Le(e),yt(e.app_id,[e.version,c==null?void 0:c.version].filter(Boolean)),m}catch(w){throw o?new re:w}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:vt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},le={},un=__DEV__?0:60*1e3,Mt={},St=(e,t)=>{var r,s;let n=S(e);return n&&Date.now()-((r=Mt[t])!=null?r:0)<un?Promise.resolve(n):((s=le[e])!=null||(le[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let a=await o.json(),u=await Ue(a,{base_url:t}).promise;return Mt[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),S(e))).finally(()=>{le[e]=void 0})),le[e])};var we=new Map,bt=(e,t)=>(we.set(e,t),()=>{we.get(e)===t&&we.delete(e)}),xt=(e,t)=>{let n=we.get(e);return n?n(t):!1};var ve=require("react"),_e=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=(0,ve.useRef)(null),s=()=>{let o=e.getState(),a=r.current;if(a&&a.state===o&&a.selector===t)return a.value;let u=t(o),i=a&&n(a.value,u)?a.value:u;return r.current={state:o,selector:t,value:i},i};return(0,ve.useSyncExternalStore)(e.subscribe,s)};var U=_e({active_key:null,instances:{}}),Et=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=x().keep_alive)==null?void 0:u.max_webviews;U.setState(i=>{let c=t!=null?t:e.app_id,M={...i.instances,[c]:{key:c,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},y=Object.keys(M);return a&&a>0&&y.length>a&&y.filter(w=>w!==c).sort((w,m)=>M[w].last_used_at-M[m].last_used_at).slice(0,y.length-a).forEach(w=>{delete M[w]}),o?{active_key:c,instances:M}:{instances:M}})},Rt=e=>Et(e,!0),Tt=e=>Et(e,!1),ie=()=>U.setState({active_key:null}),Se=e=>{U.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Pt="catalog",dn="paused_apps",gn="removed_apps",fn=10*1e3,hn=2,An=3e3,mn=()=>{var e;try{return JSON.parse((e=x().storage.getString(Pt))!=null?e:"{}")}catch{return{}}},v=_e({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),kt=e=>{var t;return!!((t=x().manual_update)!=null&&t.includes(e))},Ee=new Set,Ct=e=>{let t=new Set,n=()=>x().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 s=JSON.parse((r=x().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},H=Ct(dn),G=Ct(gn);nt(()=>{H.load(),G.load();let e=mn(),t={};Object.keys(e).filter(n=>!G.has(n)).forEach(n=>{let r=S(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),v.setState({catalog:e,downloads:t})});var Re=e=>j(v,t=>e?t.downloads[e]:void 0),Ot=()=>j(v,e=>e.pause_reasons.length>0),V=(...e)=>N("queue",...e),k=[],K={},A=null,be=new Set,te={},Ve=new Set,Y=e=>{Ve.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},It=e=>(Ve.add(e),()=>{Ve.delete(e)}),Dt=()=>v.getState().downloads,I=(e,t)=>{let n=!!S(e),r=v.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};v.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Y({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Y({type:"progress",app_id:e,progress:o.progress,version:o.version})},xe=(e,t)=>{var n;(n=te[e])==null||n.forEach(r=>r(t)),delete te[e]},Mn=()=>v.getState().pause_reasons.length>0,Q=e=>{var u;if(A)return;let t=e?k.indexOf(e):Mn()?-1:k.findIndex(i=>!H.has(i));if(t<0||t>=k.length)return;let[n]=k.splice(t,1),r=v.getState().catalog[n];if(!r){xe(n,S(n)),Q();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,I(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=Ue(r,{onProgress:i=>{let c=Math.floor(i*100);c!==o&&(o=c,I(n,{progress:c/100,version:r.version}))}});A={app_id:n,handle:a,forced:!!e},V("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{V("installed",n,r.version,`${Date.now()-s}ms`),I(n,{status:"installed",progress:1,version:r.version}),xe(n,i)}).catch(i=>{var M;if(i instanceof re){if(be.has(n))return;V("paused",n),K[n]-=1,k.unshift(n),I(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let c=String((M=i==null?void 0:i.message)!=null?M:i);if(console.warn("[miniapp-queue] failed",n,c),K[n]<hn){I(n,{status:"queued",progress:0,version:r.version,error:c}),setTimeout(()=>{var y;k.includes(n)||(A==null?void 0:A.app_id)===n||(k.push(n),Q((y=te[n])!=null&&y.length?n:void 0))},An);return}I(n,{status:"failed",progress:0,version:r.version,error:c}),xe(n,S(n))}).finally(()=>{A=null;let i=k.find(c=>{var M;return(M=te[c])==null?void 0:M.length});Q(i)})},Te=(e,{front:t=!1}={})=>{if((A==null?void 0:A.app_id)===e)return;let n=k.indexOf(e);if(n>=0){if(!t)return;k.splice(n,1)}t?k.unshift(e):k.push(e)},yn=async e=>{let{host_id:t,client_token:n}=x(),r=new AbortController,s=setTimeout(()=>r.abort(),fn);try{let o=`${me}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},de=null,Pe=()=>(de!=null||(de=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(x().channels.map(yn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(v.getState().catalog).filter(i=>!r[i]);x().storage.setString(Pt,JSON.stringify(r)),v.setState({catalog:r}),await Promise.all(s.map(i=>Lt(i,{by_user:!1}))),s.forEach(i=>G.delete(i));let o=Object.keys(r).filter(i=>!G.has(i)),a=[],u={};for(let i of o.map(c=>r[c])){if(await Je(i)){I(i.app_id,{status:"installed",progress:1,version:i.version});continue}let c=S(i.app_id);if(kt(i.app_id)&&!Ee.has(i.app_id)&&c&&await q(c)){I(i.app_id,{status:"installed",progress:1,version:c.version}),u[i.app_id]={app_id:i.app_id,current_version:c.version,next_version:i.version};continue}a.push(i)}return v.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,I(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Te(i.app_id)}),V("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Y({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Y({type:"update_available",...i})),Q(),{ok:!0,app_ids:o,removed:s}}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),Y({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{de=null}})()),de),Lt=async(e,{by_user:t})=>{var s,o,a,u;if(t&&G.add(e),be.has(e))return;be.add(e),H.delete(e);let n=k.indexOf(e);n>=0&&k.splice(n,1),(A==null?void 0:A.app_id)===e&&A.handle.cancel();let r=(u=(a=(s=v.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=S(e))==null?void 0:o.version)!=null?u:"";I(e,{status:"uninstalling",progress:0,version:r}),await wt(e),Se(e),v.setState(i=>{let c={...i.downloads};return delete c[e],{downloads:c}}),delete K[e],be.delete(e),xe(e,null),V("uninstalled",e,t?"(user)":"(not in list)"),Y({type:"uninstalled",app_id:e})},$t=e=>Lt(e,{by_user:!0}),Nt=e=>{let t=oe(e);return t?(G.delete(e),(A==null?void 0:A.app_id)===e||k.includes(e)||(K[e]=0,I(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Te(e),Q(),V("restore",e)),!0):!1},Bt=e=>{if(H.has(e))return;if(H.add(e),V("pause app",e),(A==null?void 0:A.app_id)===e&&!A.forced){A.handle.cancel();return}let t=v.getState().downloads[e];k.includes(e)&&t&&I(e,{status:"paused",progress:0,version:t.version})},Ft=e=>{if(!H.delete(e))return;V("resume app",e);let t=v.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!k.includes(e)&&oe(e)&&(K[e]=0,Te(e)),k.includes(e)&&t&&I(e,{status:"queued",progress:0,version:t.version}),Q()},Jt=e=>{let{pause_reasons:t}=v.getState();t.includes(e)||(v.setState({pause_reasons:[...t,e]}),V("pause",e),t.length===0&&Y({type:"pause_change",paused:!0,reasons:[e]}),A&&!A.forced&&A.handle.cancel())},Ut=e=>{let{pause_reasons:t}=v.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);v.setState({pause_reasons:n}),V("resume",e),n.length===0&&Y({type:"pause_change",paused:!1,reasons:n}),Q()},He=e=>v.getState().updates[e],Vt=async e=>{var n,r;let t=He(e);Ee.add(e);try{let s=await ge(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=oe(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(v.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),V("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Ee.delete(e)}},Ht=()=>Object.values(v.getState().catalog).map(e=>({...e,installed:!!S(e.app_id),removed_by_user:G.has(e.app_id)})),oe=e=>v.getState().catalog[e],ge=async e=>{let t=oe(e);if(!t)return;if(H.delete(e),G.delete(e),await Je(t))return S(e);let n=S(e);if(kt(e)&&!Ee.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=te[e])!=null?o:te[e]=[]).push(s)});return(A==null?void 0:A.app_id)===e?A.forced=!0:(K[e]=0,Te(e,{front:!0}),A&&!A.forced?A.handle.cancel():Q(e)),r};var b=require("react/jsx-runtime"),We=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Wt=0,wn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},vn=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:c,onWebLoadEnd:M})=>{var Qe,Ge;let y=(0,d.useRef)(null),w=(0,d.useRef)(!1),m=j(U,p=>p.instances[e]),f=m==null?void 0:m.app.app_id,F=m==null?void 0:m.app.manifest_url,P=m==null?void 0:m.context,D=m==null?void 0:m.url_params,[l,C]=(0,d.useState)(()=>f?S(f):null),[h,T]=(0,d.useState)(!1),[ne,se]=(0,d.useState)(0),[zt,ae]=(0,d.useState)(0),[Yt,L]=(0,d.useState)(!1),W=(0,d.useRef)(null),qe=p=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,L(!0)},p)};(0,d.useEffect)(()=>()=>{W.current&&clearTimeout(W.current)},[]),(0,d.useEffect)(()=>{if(!f||!t&&l)return;let p=!0;return T(!1),(async()=>{let g=S(f),O=g?await q(g):!1;if(!p||(C(O?J=>!J||J.version!==g.version||J.permissions.join(",")!==g.permissions.join(",")?g:J:null),__DEV__&&Date.now()-Wt>1e4&&(Wt=Date.now(),await Pe()),!p))return;let z=await ge(f),X=z!==void 0?z:F?await St(f,F):S(f);if(p){if(!X){T(!0);return}C(J=>J!=null?J:X)}})(),()=>{p=!1}},[t,f,F,ne]),(0,d.useEffect)(()=>bt(e,p=>y.current?(y.current.postMessage(p),!0):!1),[e]);let Qt=j(v,p=>{let g=f?p.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});(0,d.useEffect)(()=>{if(t||!f||!l)return;let p=S(f);if(!p||p.version===l.version)return;let g=!0;return q(p).then(O=>{!g||!O||(N(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",p.version),C(p))}),()=>{g=!1}},[t,f,Qt,l==null?void 0:l.version]);let Ke=j(v,p=>{var g;return f&&(g=p.apply_ticks[f])!=null?g:0});(0,d.useEffect)(()=>{if(!Ke||!f)return;let p=S(f);if(!p||p.version===(l==null?void 0:l.version))return;let g=!0;return q(p).then(O=>{!g||!O||(N(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",p.version),L(!1),C(p))}),()=>{g=!1}},[Ke]),(0,d.useEffect)(()=>{var O;let p=(O=x().keep_alive)==null?void 0:O.idle_close_ms;if(t||!p||p<=0)return;let g=setTimeout(()=>{Se(e)},p);return()=>clearTimeout(g)},[t,e]),(0,d.useEffect)(()=>{s>0&&(T(!1),L(!1),ae(p=>p+1),se(p=>p+1))},[s]);let ze=(0,d.useRef)(t);(0,d.useEffect)(()=>{var p;ze.current!==t&&(ze.current=t,w.current&&((p=y.current)==null||p.injectJavaScript(ut(t?"resumed":"paused"))))},[t]);let fe=`${(Qe=l==null?void 0:l.version)!=null?Qe:"none"}:${(Ge=l==null?void 0:l.permissions.join(","))!=null?Ge:""}:${zt}`,pe=(0,d.useMemo)(()=>JSON.stringify([P!=null?P:{},D!=null?D:{}]),[P,D]),ke=(0,d.useMemo)(()=>{var p;return At(D!=null?D:{},(p=l==null?void 0:l.permissions)!=null?p:[])},[pe,l==null?void 0:l.permissions]),Gt=(0,d.useMemo)(()=>ft(P!=null?P:{},ke)+lt()+(x().debug?ct():""),[ke]),he=(0,d.useRef)(null),Ye=(0,d.useRef)(null);(0,d.useEffect)(()=>{var g,O,z;if(!l)return;if(Ye.current!==fe){Ye.current=fe,he.current=pe;return}if(he.current===pe)return;let p=((O=JSON.parse((g=he.current)!=null?g:"[]")[0])!=null?O:{}).org_id;if(he.current=pe,p===(P==null?void 0:P.org_id)&&w.current){L(!1),qe(1500),(z=y.current)==null||z.injectJavaScript(dt(P!=null?P:{},ke));return}L(!1),ae(X=>X+1)},[pe,l,fe]);let Xt=(0,d.useCallback)(async p=>{var O,z,X,J,Ce;let g=st(p.nativeEvent.data);if(!g){if(f&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(p.nativeEvent.data,{app_id:f,instance_id:e})).catch(R=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,R)})}catch(R){console.warn("[miniapp] onWebEvent l\u1ED7i",f,R)}return}if(g.method==="log"){let{level:R,text:$}=g;N(`web:${e}`,R!=null?R:"log",$!=null?$:"");return}if(g.method==="pong"){W.current||L(!0);return}if(g.method==="touchAtTop"){o.emit(!!g.at_top);return}if(g.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,L(!0);return}if(g.method==="ready"){w.current=!0,L(!0);let R=(O=U.getState().instances[e])==null?void 0:O.context;R&&((z=y.current)==null||z.injectJavaScript(De(R)));return}try{let R=await mt(g,{getHostData:()=>{var $,Z;return(Z=($=U.getState().instances[e])==null?void 0:$.host_data)!=null?Z:{}},getPermissions:()=>{var $,Z;return f?(Z=($=S(f))==null?void 0:$.permissions)!=null?Z:[]:[]},is_dark:r,close:ie,app_id:f!=null?f:"",instance_id:e,options:u});g.id&&((X=y.current)==null||X.injectJavaScript(at(g.id,R)))}catch(R){if(!g.id)return;let $=R==null?void 0:R.code,Z=R instanceof E?R:new E(typeof $=="string"?$:"HOST_ERROR",String((J=R==null?void 0:R.message)!=null?J:R));(Ce=y.current)==null||Ce.injectJavaScript(pt(g.id,Z))}},[e,r,f,o,u]),Zt=(0,d.useCallback)(()=>{T(!1),ae(p=>p+1),se(p=>p+1)},[]);return(0,b.jsxs)(_.View,{style:[_.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&B.behind],pointerEvents:t?"auto":"none",children:[l?(0,b.jsx)(qt.default,{ref:y,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${c?Ne():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Gt,onMessage:Xt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{N(`webview:${e}`,"load start",We(p.nativeEvent.url)),w.current=!1,L(!1)},onError:p=>{N(`webview:${e}`,"load error",We(p.nativeEvent.url),p.nativeEvent.description),T(!0),L(!1)},onLoadEnd:p=>{let g=p.nativeEvent.url;N(`webview:${e}`,"load end",We(g)),f&&(M==null||M({app_id:f,instance_id:e,url:g})),qe(1500)},onContentProcessDidTerminate:()=>{w.current=!1,L(!1),ae(p=>p+1)},onRenderProcessGone:()=>(w.current=!1,L(!1),ae(p=>p+1),!0),style:B.webview},fe):null,m&&(0,b.jsx)(Sn,{visible:!l||!Yt,interactive:h,children:(0,b.jsx)(_n,{splash:a,app:m.app,is_dark:r,error:h,has_bundle:!!l,retry:Zt})})]})}),_n=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=Re(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return(0,b.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Sn=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new _.Animated.Value(e?1:0)).current,[s,o]=(0,d.useState)(e);return(0,d.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let a=_.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?(0,b.jsx)(_.Animated.View,{style:[_.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},je=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,b.jsxs)(_.View,{style:[B.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,b.jsx)(_.View,{style:[B.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,b.jsx)(_.Image,{source:{uri:e.icon},style:B.splash_icon_image}):(0,b.jsx)(_.Text,{style:B.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,b.jsx)(_.Text,{style:[B.splash_name,{color:o}],children:e.name}),n==="error"?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(_.Text,{style:B.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,b.jsx)(_.TouchableOpacity,{activeOpacity:.7,style:[B.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,b.jsx)(_.Text,{style:[B.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(_.ActivityIndicator,{style:B.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,b.jsxs)(_.Text,{style:B.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},jt=(e,t)=>{let n=(0,d.useRef)(t),r=(0,d.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},bn=({container:e,splash:t=je,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{jt("container",e),jt("splash",t);let i=e,c=j(U,l=>l.active_key),M=(0,d.useRef)(c);c&&(M.current=c);let y=j(U,l=>Object.keys(l.instances).join("|")),w=j(U,l=>{var C;return l.active_key?(C=l.instances[l.active_key])==null?void 0:C.app.name:void 0}),m=(0,d.useMemo)(()=>y?y.split("|"):[],[y]),[f,F]=(0,d.useState)({}),P=(0,d.useRef)(wn()).current;(0,d.useEffect)(()=>{if(!c||!s)return;let l=_.BackHandler.addEventListener("hardwareBackPress",()=>(ie(),!0));return()=>l.remove()},[c,s]);let D=(0,d.useCallback)(()=>{let l=U.getState().active_key;l&&F(C=>({...C,[l]:(C[l]||0)+1}))},[]);return m.length?(0,b.jsx)(i,{visible:!!c,title:w!=null?w:"",is_dark:n,close:ie,reload:D,subscribeWebAtTop:P.subscribe,children:m.map(l=>(0,b.jsx)(vn,{instance_key:l,is_active:c===l,is_front:(c!=null?c:M.current)===l,is_dark:n,reload_tick:f[l]||0,web_at_top:P,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},B=_.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Kt=d.default.memo(bn);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
45
+ true;`},yt={partner:"partner_token",chatbox:"chatbox_token"},wt=(e,t)=>{let n={...e};for(let r of Object.values(yt))t.includes(r)||delete n[r];return n},$e=new Set,Fe=async(e,t)=>{if($e.has(e))throw new m("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);$e.add(e);try{return await t()}finally{$e.delete(e)}},un=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),we=(e,t)=>{if(typeof e!="string"||!e)throw new m("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},vt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var v,M,h,F,R,D,l,C,ae;let p=i==null?void 0:i.handlers,y={app_id:a,instance_id:u,close:o},w=()=>new m("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getBiometricAvailability":return((v=i==null?void 0:i.biometrics)!=null?v:await Ne()).getAvailability();case"authenticateBiometric":{let g=we(t==null?void 0:t.reason,"reason").trim();if(!g||g.length>200)throw new m("INVALID_PARAMS","reason must contain 1\u2013200 characters");let E=t==null?void 0:t.cancelButtonText;if(E!==void 0&&(typeof E!="string"||!E.trim()||E.length>80))throw new m("INVALID_PARAMS","Invalid cancelButtonText");return Fe(e,async()=>{var Z;return((Z=i==null?void 0:i.biometrics)!=null?Z:await Ne()).authenticate({reason:g,cancelButtonText:E})})}case"requestPayment":{let g=p==null?void 0:p.requestPayment;if(!g)throw w();let E=t==null?void 0:t.amount;if(typeof E!="number"||!Number.isFinite(E)||E<=0)throw new m("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:E,currency:we(t==null?void 0:t.currency,"currency")};return Fe(e,()=>g(z,y))}case"printImage":{let g=p==null?void 0:p.printImage;if(!g)throw w();let E=we(t==null?void 0:t.image,"image");await Fe(e,()=>g({image:E},y));return}case"openScreen":if(!(p!=null&&p.openScreen))throw w();await p.openScreen({screen:we(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":o();return;case"openWebview":{let g=String((M=t==null?void 0:t.url)!=null?M:"");if(!/^https?:\/\//i.test(g))throw new m("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(g):le.Linking.openURL(g));return}case"openLink":{let g=String((h=t==null?void 0:t.url)!=null?h:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(g)||/^(javascript|file|data|about|blob):/i.test(g))throw new m("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(g):le.Linking.openURL(g))}catch(E){throw new m("NOT_SUPPORTED",String((R=(F=E==null?void 0:E.message)!=null?F:E)!=null?R:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(l=i==null?void 0:i.showToast)==null||l.call(i,String((D=t==null?void 0:t.message)!=null?D:""));return;case"haptic":{let g=un.has(t==null?void 0:t.type)?t.type:"selection";(C=i==null?void 0:i.haptic)==null||C.call(i,g);return}case"getSystemInfo":return{platform:le.Platform.OS==="ios"?"ios":"android",appVersion:(ae=i==null?void 0:i.app_version)!=null?ae:"",theme:s?"dark":"light"};case"getAccessToken":{let g=n().access_token;if(!g)throw new m("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return g}case"getToken":{let g=t==null?void 0:t.type;if(g==="access"){let Z=n().access_token;if(!Z)throw new m("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return Z}if(g!=="partner"&&g!=="chatbox")throw new m("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(g)}`);let E=yt[g];if(!r().includes(E))throw new m("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${E} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=g==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new m("HOST_ERROR",`Kh\xF4ng c\xF3 ${E}`);return z}case"getUserInfo":{let g=n().user;if(!g)throw new m("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return g}case"getPageInfo":{let g=n().page;if(!g)throw new m("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return g}case"sendMessage":case"insertText":throw new m("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new m("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Je=e=>`bundle:${e}`,He=()=>`${T().file_system.document_dir}/miniapps`,We=He,je=(e,t,n="index.html",r=!1,s=[])=>{let o=`${We()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},Ve=e=>{var t;T().storage.setString(Je(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},dn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,b=e=>{let t=T().storage.getString(Je(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return je(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>T().file_system.exists(e.entry_uri.replace("file://","")),qe=async e=>{let t=b(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},St=async(e,t)=>{let n=T().file_system,r=`${We()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},bt=async e=>{var t;await((t=de[e])==null?void 0:t.catch(()=>{})),T().storage.setString(Je(e),""),await T().file_system.remove(`${We()}/${e}`).catch(()=>{})},ie=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},de={},xt=(e,t)=>{var o;let r=((o=de[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return de[e]=s,s.then(()=>{de[e]===s&&delete de[e]}),r},gn=(e,t)=>{var s,o;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 u=((s=n[a])!=null?s:0)-((o=r[a])!=null?o:0);if(u)return u}return 0},Et=({manifest:e,zip_path:t})=>xt(e.app_id,async()=>{var o;let n=T().file_system,r=b(e.app_id);if(r&&gn(r.version,e.version)>=0&&await q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=je(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),Ve(e),N("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),St(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Ke=(e,{base_url:t,onProgress:n}={})=>{let r=T().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new ie},i=async()=>{var w;u();let p=b(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return Ve(e),b(e.app_id);u();let y=r.download({url:t?dn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(v,M)=>{var F;let h=M>0?M:(F=e.size)!=null?F:0;h>0&&(n==null||n(Math.min(1,v/h)))}});s=y;try{let{status:v}=await y.promise;if(u(),v!==200)throw new Error(`bundle ${v}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else N("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let M=je(e.app_id,e.version,e.entry,!!e.context_update,(w=e.permissions)!=null?w:[]);return await r.remove(M.dir).catch(()=>{}),await r.mkdir(M.dir),await r.unzip(a,M.dir),Ve(e),St(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),M}catch(v){throw o?new ie:v}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:xt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},ue={},fn=__DEV__?0:60*1e3,_t={},Tt=(e,t)=>{var r,s;let n=b(e);return n&&Date.now()-((r=_t[t])!=null?r:0)<fn?Promise.resolve(n):((s=ue[e])!=null||(ue[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let a=await o.json(),u=await Ke(a,{base_url:t}).promise;return _t[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),b(e))).finally(()=>{ue[e]=void 0})),ue[e])};var Se=new Map,Pt=(e,t)=>(Se.set(e,t),()=>{Se.get(e)===t&&Se.delete(e)}),Rt=(e,t)=>{let n=Se.get(e);return n?n(t):!1};var be=require("react"),xe=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=(0,be.useRef)(null),s=()=>{let o=e.getState(),a=r.current;if(a&&a.state===o&&a.selector===t)return a.value;let u=t(o),i=a&&n(a.value,u)?a.value:u;return r.current={state:o,selector:t,value:i},i};return(0,be.useSyncExternalStore)(e.subscribe,s)};var V=xe({active_key:null,instances:{}}),kt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=T().keep_alive)==null?void 0:u.max_webviews;V.setState(i=>{let p=t!=null?t:e.app_id,y={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},w=Object.keys(y);return a&&a>0&&w.length>a&&w.filter(v=>v!==p).sort((v,M)=>y[v].last_used_at-y[M].last_used_at).slice(0,w.length-a).forEach(v=>{delete y[v]}),o?{active_key:p,instances:y}:{instances:y}})},Ct=e=>kt(e,!0),Ot=e=>kt(e,!1),oe=()=>V.setState({active_key:null}),Ee=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var It="catalog",hn="paused_apps",mn="removed_apps",An=10*1e3,Mn=2,yn=3e3,wn=()=>{var e;try{return JSON.parse((e=T().storage.getString(It))!=null?e:"{}")}catch{return{}}},_=xe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Dt=e=>{var t;return!!((t=T().manual_update)!=null&&t.includes(e))},Re=new Set,Lt=e=>{let t=new Set,n=()=>T().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 s=JSON.parse((r=T().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},H=Lt(hn),X=Lt(mn);at(()=>{H.load(),X.load();let e=wn(),t={};Object.keys(e).filter(n=>!X.has(n)).forEach(n=>{let r=b(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var ke=e=>j(_,t=>e?t.downloads[e]:void 0),Bt=()=>j(_,e=>e.pause_reasons.length>0),J=(...e)=>N("queue",...e),k=[],K={},A=null,Te=new Set,re={},ze=new Set,Q=e=>{ze.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Nt=e=>(ze.add(e),()=>{ze.delete(e)}),$t=()=>_.getState().downloads,I=(e,t)=>{let n=!!b(e),r=_.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Q({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Q({type:"progress",app_id:e,progress:o.progress,version:o.version})},Pe=(e,t)=>{var n;(n=re[e])==null||n.forEach(r=>r(t)),delete re[e]},vn=()=>_.getState().pause_reasons.length>0,G=e=>{var u;if(A)return;let t=e?k.indexOf(e):vn()?-1:k.findIndex(i=>!H.has(i));if(t<0||t>=k.length)return;let[n]=k.splice(t,1),r=_.getState().catalog[n];if(!r){Pe(n,b(n)),G();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,I(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=Ke(r,{onProgress:i=>{let p=Math.floor(i*100);p!==o&&(o=p,I(n,{progress:p/100,version:r.version}))}});A={app_id:n,handle:a,forced:!!e},J("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{J("installed",n,r.version,`${Date.now()-s}ms`),I(n,{status:"installed",progress:1,version:r.version}),Pe(n,i)}).catch(i=>{var y;if(i instanceof ie){if(Te.has(n))return;J("paused",n),K[n]-=1,k.unshift(n),I(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((y=i==null?void 0:i.message)!=null?y:i);if(console.warn("[miniapp-queue] failed",n,p),K[n]<Mn){I(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var w;k.includes(n)||(A==null?void 0:A.app_id)===n||(k.push(n),G((w=re[n])!=null&&w.length?n:void 0))},yn);return}I(n,{status:"failed",progress:0,version:r.version,error:p}),Pe(n,b(n))}).finally(()=>{A=null;let i=k.find(p=>{var y;return(y=re[p])==null?void 0:y.length});G(i)})},Ce=(e,{front:t=!1}={})=>{if((A==null?void 0:A.app_id)===e)return;let n=k.indexOf(e);if(n>=0){if(!t)return;k.splice(n,1)}t?k.unshift(e):k.push(e)},_n=async e=>{let{host_id:t,client_token:n}=T(),r=new AbortController,s=setTimeout(()=>r.abort(),An);try{let o=`${Me}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},ge=null,Oe=()=>(ge!=null||(ge=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(T().channels.map(_n)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(_.getState().catalog).filter(i=>!r[i]);T().storage.setString(It,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(s.map(i=>Ft(i,{by_user:!1}))),s.forEach(i=>X.delete(i));let o=Object.keys(r).filter(i=>!X.has(i)),a=[],u={};for(let i of o.map(p=>r[p])){if(await qe(i)){I(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=b(i.app_id);if(Dt(i.app_id)&&!Re.has(i.app_id)&&p&&await q(p)){I(i.app_id,{status:"installed",progress:1,version:p.version}),u[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,I(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Ce(i.app_id)}),J("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Q({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Q({type:"update_available",...i})),G(),{ok:!0,app_ids:o,removed:s}}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),Q({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ge=null}})()),ge),Ft=async(e,{by_user:t})=>{var s,o,a,u;if(t&&X.add(e),Te.has(e))return;Te.add(e),H.delete(e);let n=k.indexOf(e);n>=0&&k.splice(n,1),(A==null?void 0:A.app_id)===e&&A.handle.cancel();let r=(u=(a=(s=_.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=b(e))==null?void 0:o.version)!=null?u:"";I(e,{status:"uninstalling",progress:0,version:r}),await bt(e),Ee(e),_.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete K[e],Te.delete(e),Pe(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),Q({type:"uninstalled",app_id:e})},Ut=e=>Ft(e,{by_user:!0}),Vt=e=>{let t=se(e);return t?(X.delete(e),(A==null?void 0:A.app_id)===e||k.includes(e)||(K[e]=0,I(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ce(e),G(),J("restore",e)),!0):!1},Jt=e=>{if(H.has(e))return;if(H.add(e),J("pause app",e),(A==null?void 0:A.app_id)===e&&!A.forced){A.handle.cancel();return}let t=_.getState().downloads[e];k.includes(e)&&t&&I(e,{status:"paused",progress:0,version:t.version})},Ht=e=>{if(!H.delete(e))return;J("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!k.includes(e)&&se(e)&&(K[e]=0,Ce(e)),k.includes(e)&&t&&I(e,{status:"queued",progress:0,version:t.version}),G()},Wt=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&Q({type:"pause_change",paused:!0,reasons:[e]}),A&&!A.forced&&A.handle.cancel())},jt=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),J("resume",e),n.length===0&&Q({type:"pause_change",paused:!1,reasons:n}),G()},Ye=e=>_.getState().updates[e],qt=async e=>{var n,r;let t=Ye(e);Re.add(e);try{let s=await fe(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=se(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(_.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),J("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Re.delete(e)}},Kt=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!b(e.app_id),removed_by_user:X.has(e.app_id)})),se=e=>_.getState().catalog[e],fe=async e=>{let t=se(e);if(!t)return;if(H.delete(e),X.delete(e),await qe(t))return b(e);let n=b(e);if(Dt(e)&&!Re.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=re[e])!=null?o:re[e]=[]).push(s)});return(A==null?void 0:A.app_id)===e?A.forced=!0:(K[e]=0,Ce(e,{front:!0}),A&&!A.forced?A.handle.cancel():G(e)),r};var x=require("react/jsx-runtime"),Qe=e=>(e!=null?e:"").replace(/\?[^#]*/,""),zt=0,Sn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},bn=d.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:y})=>{var nt,rt;let w=(0,d.useRef)(null),v=(0,d.useRef)(!1),M=j(V,c=>c.instances[e]),h=M==null?void 0:M.app.app_id,F=M==null?void 0:M.app.manifest_url,R=M==null?void 0:M.context,D=M==null?void 0:M.url_params,[l,C]=(0,d.useState)(()=>h?b(h):null),[ae,g]=(0,d.useState)(!1),[E,z]=(0,d.useState)(0),[Z,ce]=(0,d.useState)(0),[Xt,L]=(0,d.useState)(!1),W=(0,d.useRef)(null),Xe=c=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,L(!0)},c)};(0,d.useEffect)(()=>()=>{W.current&&clearTimeout(W.current)},[]),(0,d.useEffect)(()=>{if(!h||!t&&l)return;let c=!0;return g(!1),(async()=>{let f=b(h),O=f?await q(f):!1;if(!c||(C(O?U=>!U||U.version!==f.version||U.permissions.join(",")!==f.permissions.join(",")?f:U:null),__DEV__&&Date.now()-zt>1e4&&(zt=Date.now(),await Oe()),!c))return;let Y=await fe(h),ee=Y!==void 0?Y:F?await Tt(h,F):b(h);if(c){if(!ee){g(!0);return}C(U=>U!=null?U:ee)}})(),()=>{c=!1}},[t,h,F,E]),(0,d.useEffect)(()=>Pt(e,c=>w.current?(w.current.postMessage(c),!0):!1),[e]);let Zt=j(_,c=>{let f=h?c.downloads[h]:void 0;return(f==null?void 0:f.status)==="installed"?f.version:void 0});(0,d.useEffect)(()=>{if(t||!h||!l)return;let c=b(h);if(!c||c.version===l.version)return;let f=!0;return q(c).then(O=>{!f||!O||(N(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),C(c))}),()=>{f=!1}},[t,h,Zt,l==null?void 0:l.version]);let Ze=j(_,c=>{var f;return h&&(f=c.apply_ticks[h])!=null?f:0});(0,d.useEffect)(()=>{if(!Ze||!h)return;let c=b(h);if(!c||c.version===(l==null?void 0:l.version))return;let f=!0;return q(c).then(O=>{!f||!O||(N(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),L(!1),C(c))}),()=>{f=!1}},[Ze]),(0,d.useEffect)(()=>{var O;let c=(O=T().keep_alive)==null?void 0:O.idle_close_ms;if(t||!c||c<=0)return;let f=setTimeout(()=>{Ee(e)},c);return()=>clearTimeout(f)},[t,e]),(0,d.useEffect)(()=>{s>0&&(g(!1),L(!1),ce(c=>c+1),z(c=>c+1))},[s]);let et=(0,d.useRef)(t);(0,d.useEffect)(()=>{var c;et.current!==t&&(et.current=t,v.current&&((c=w.current)==null||c.injectJavaScript(ht(t?"resumed":"paused"))))},[t]);let he=`${(nt=l==null?void 0:l.version)!=null?nt:"none"}:${(rt=l==null?void 0:l.permissions.join(","))!=null?rt:""}:${Z}`,pe=(0,d.useMemo)(()=>JSON.stringify([R!=null?R:{},D!=null?D:{}]),[R,D]),Ie=(0,d.useMemo)(()=>{var c;return wt(D!=null?D:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[pe,l==null?void 0:l.permissions]),en=(0,d.useMemo)(()=>Mt(R!=null?R:{},Ie)+ft()+(T().debug?gt():""),[Ie]),me=(0,d.useRef)(null),tt=(0,d.useRef)(null);(0,d.useEffect)(()=>{var f,O,Y;if(!l)return;if(tt.current!==he){tt.current=he,me.current=pe;return}if(me.current===pe)return;let c=((O=JSON.parse((f=me.current)!=null?f:"[]")[0])!=null?O:{}).org_id;if(me.current=pe,c===(R==null?void 0:R.org_id)&&v.current){L(!1),Xe(1500),(Y=w.current)==null||Y.injectJavaScript(mt(R!=null?R:{},Ie));return}L(!1),ce(ee=>ee+1)},[pe,l,he]);let tn=(0,d.useCallback)(async c=>{var O,Y,ee,U,De;let f=lt(c.nativeEvent.data);if(!f){if(h&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:h,instance_id:e})).catch(P=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,P)})}catch(P){console.warn("[miniapp] onWebEvent l\u1ED7i",h,P)}return}if(f.method==="log"){let{level:P,text:B}=f;N(`web:${e}`,P!=null?P:"log",B!=null?B:"");return}if(f.method==="pong"){W.current||L(!0);return}if(f.method==="touchAtTop"){o.emit(!!f.at_top);return}if(f.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,L(!0);return}if(f.method==="ready"){v.current=!0,L(!0);let P=(O=V.getState().instances[e])==null?void 0:O.context;P&&((Y=w.current)==null||Y.injectJavaScript(Ue(P)));return}try{let P=await vt(f,{getHostData:()=>{var B,te;return(te=(B=V.getState().instances[e])==null?void 0:B.host_data)!=null?te:{}},getPermissions:()=>{var B,te;return h?(te=(B=b(h))==null?void 0:B.permissions)!=null?te:[]:[]},is_dark:r,close:oe,app_id:h!=null?h:"",instance_id:e,options:u});f.id&&((ee=w.current)==null||ee.injectJavaScript(ut(f.id,P)))}catch(P){if(!f.id)return;let B=P==null?void 0:P.code,te=P instanceof m?P:new m(typeof B=="string"?B:"HOST_ERROR",String((U=P==null?void 0:P.message)!=null?U:P));(De=w.current)==null||De.injectJavaScript(dt(f.id,te))}},[e,r,h,o,u]),nn=(0,d.useCallback)(()=>{g(!1),ce(c=>c+1),z(c=>c+1)},[]);return(0,x.jsxs)(S.View,{style:[S.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&$.behind],pointerEvents:t?"auto":"none",children:[l?(0,x.jsx)(Qt.default,{ref:w,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?He():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:en,onMessage:tn,bounces:!1,overScrollMode:"never",onLoadStart:c=>{N(`webview:${e}`,"load start",Qe(c.nativeEvent.url)),v.current=!1,L(!1)},onError:c=>{N(`webview:${e}`,"load error",Qe(c.nativeEvent.url),c.nativeEvent.description),g(!0),L(!1)},onLoadEnd:c=>{let f=c.nativeEvent.url;N(`webview:${e}`,"load end",Qe(f)),h&&(y==null||y({app_id:h,instance_id:e,url:f})),Xe(1500)},onContentProcessDidTerminate:()=>{v.current=!1,L(!1),ce(c=>c+1)},onRenderProcessGone:()=>(v.current=!1,L(!1),ce(c=>c+1),!0),style:$.webview},he):null,M&&(0,x.jsx)(En,{visible:!l||!Xt,interactive:ae,children:(0,x.jsx)(xn,{splash:a,app:M.app,is_dark:r,error:ae,has_bundle:!!l,retry:nn})})]})}),xn=d.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=ke(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return(0,x.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),En=({visible:e,interactive:t,children:n})=>{let r=(0,d.useRef)(new S.Animated.Value(e?1:0)).current,[s,o]=(0,d.useState)(e);return(0,d.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let a=S.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?(0,x.jsx)(S.Animated.View,{style:[S.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Ge=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return(0,x.jsxs)(S.View,{style:[$.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,x.jsx)(S.View,{style:[$.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,x.jsx)(S.Image,{source:{uri:e.icon},style:$.splash_icon_image}):(0,x.jsx)(S.Text,{style:$.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,x.jsx)(S.Text,{style:[$.splash_name,{color:o}],children:e.name}),n==="error"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(S.Text,{style:$.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,x.jsx)(S.TouchableOpacity,{activeOpacity:.7,style:[$.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:(0,x.jsx)(S.Text,{style:[$.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(S.ActivityIndicator,{style:$.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,x.jsxs)(S.Text,{style:$.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Yt=(e,t)=>{let n=(0,d.useRef)(t),r=(0,d.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Tn=({container:e,splash:t=Ge,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{Yt("container",e),Yt("splash",t);let i=e,p=j(V,l=>l.active_key),y=(0,d.useRef)(p);p&&(y.current=p);let w=j(V,l=>Object.keys(l.instances).join("|")),v=j(V,l=>{var C;return l.active_key?(C=l.instances[l.active_key])==null?void 0:C.app.name:void 0}),M=(0,d.useMemo)(()=>w?w.split("|"):[],[w]),[h,F]=(0,d.useState)({}),R=(0,d.useRef)(Sn()).current;(0,d.useEffect)(()=>{if(!p||!s)return;let l=S.BackHandler.addEventListener("hardwareBackPress",()=>(oe(),!0));return()=>l.remove()},[p,s]);let D=(0,d.useCallback)(()=>{let l=V.getState().active_key;l&&F(C=>({...C,[l]:(C[l]||0)+1}))},[]);return M.length?(0,x.jsx)(i,{visible:!!p,title:v!=null?v:"",is_dark:n,close:oe,reload:D,subscribeWebAtTop:R.subscribe,children:M.map(l=>(0,x.jsx)(bn,{instance_key:l,is_active:p===l,is_front:(p!=null?p:y.current)===l,is_dark:n,reload_tick:h[l]||0,web_at_top:R,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},$=S.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"}}),Gt=d.default.memo(Tn);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,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var ke="https://retion-miniapp-platform.vercel.app",ee=null,nt=new Set,Jt=e=>{ee=e,nt.forEach(t=>t())},_=()=>{if(!ee)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ee},rt=e=>{nt.add(e),ee&&e()},L=(...e)=>{ee!=null&&ee.debug&&console.log("[miniapp]",...e)};var Ut=(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(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),Vt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import ze,{useCallback as qe,useEffect as V,useMemo as Re,useRef as H,useState as ne}from"react";import{ActivityIndicator as wn,Animated as We,BackHandler as vn,Image as _n,StyleSheet as Ye,Text as ge,TouchableOpacity as Sn,View as Ke}from"react-native";import bn from"react-native-webview";import{Linking as it,Platform as Ht}from"react-native";var me=1,b=class extends Error{constructor(n,r){super(r);this.code=n}},st=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===me&&typeof t.method=="string"?t:null}catch{return null}},Me=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,at=(e,t)=>Me({id:e,result:t}),pt=(e,t)=>Me({id:e,error:{code:t.code,message:t.message}}),Ie=e=>Me({event:"context",data:e});var ct=()=>`(function () {
1
+ var Ie="https://retion-miniapp-platform.vercel.app",ne=null,st=new Set,Ht=e=>{ne=e,st.forEach(t=>t())},b=()=>{if(!ne)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ne},at=e=>{st.add(e),ne&&e()},L=(...e)=>{ne!=null&&ne.debug&&console.log("[miniapp]",...e)};var Wt=(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(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:s})=>{let{jobId:o,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:u,contentLength:i})=>s==null?void 0:s(u,i)});return{promise:a.then(({statusCode:u})=>({status:u})),cancel:()=>e.stopDownload(o)}}}),jt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Xe,{useCallback as Qe,useEffect as J,useMemo as ke,useRef as H,useState as ie}from"react";import{ActivityIndicator as Sn,Animated as ze,BackHandler as bn,Image as xn,StyleSheet as Ze,Text as fe,TouchableOpacity as En,View as Ge}from"react-native";import Tn from"react-native-webview";import{Linking as pt,Platform as qt}from"react-native";var ct=e=>({getAvailability:async()=>{var r;let t=await e.isSensorAvailable(),n=["FaceID","TouchID","Biometrics"].includes((r=t.biometryType)!=null?r:"")?t.biometryType:void 0;return{available:t.available,...n?{biometryType:n}:{}}},authenticate:async({reason:t,cancelButtonText:n})=>{try{let{available:r}=await e.isSensorAvailable();if(!r)throw new A("BIOMETRIC_UNAVAILABLE","Biometrics unavailable, not enrolled or permission denied");let s=await e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""});if(!s.success)throw new A("CANCELLED",s.error||"Biometric authentication cancelled");return{success:!0}}catch(r){throw r instanceof A?r:new A("AUTHENTICATION_FAILED",r instanceof Error?r.message:String(r))}}}),Me,De=()=>(Me||(Me=import("react-native-biometrics").then(({default:e})=>ct(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Me=void 0,new A("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Me);var we=1,A=class extends Error{constructor(n,r){super(r);this.code=n}},lt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===we&&typeof t.method=="string"?t:null}catch{return null}},ve=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,ut=(e,t)=>ve({id:e,result:t}),dt=(e,t)=>ve({id:e,error:{code:t.code,message:t.message}}),Ne=e=>ve({event:"context",data:e});var gt=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@ var ke="https://retion-miniapp-platform.vercel.app",ee=null,nt=new Set,Jt=e=>{ee
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: ${me}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${we}, 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 ke="https://retion-miniapp-platform.vercel.app",ee=null,nt=new Set,Jt=e=>{ee
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;`,lt=()=>`(function () {
22
+ })(); true;`,ft=()=>`(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 ke="https://retion-miniapp-platform.vercel.app",ee=null,nt=new Set,Jt=e=>{ee
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: ${me}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${we}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -38,8 +38,8 @@ var ke="https://retion-miniapp-platform.vercel.app",ee=null,nt=new Set,Jt=e=>{ee
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;`,ut=e=>Me({event:e}),dt=(e,t)=>{let n=gt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${Ie(e)}`},gt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ft=(e,t={})=>{let n=gt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${me} };
41
+ })(); true;`,ht=e=>ve({event:e}),mt=(e,t)=>{let n=At(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
+ ${Ne(e)}`},At=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Mt=(e,t={})=>{let n=At(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${we} };
43
43
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
44
44
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
45
- true;`},ht={partner:"partner_token",chatbox:"chatbox_token"},At=(e,t)=>{let n={...e};for(let r of Object.values(ht))t.includes(r)||delete n[r];return n},Ce=new Set,ot=async(e,t)=>{if(Ce.has(e))throw new b("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ce.add(e);try{return await t()}finally{Ce.delete(e)}},Wt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Oe=(e,t)=>{if(typeof e!="string"||!e)throw new b("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},mt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var y,A,g,N,E,O,l,P;let c=i==null?void 0:i.handlers,m={app_id:a,instance_id:u,close:o},M=()=>new b("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"requestPayment":{let f=c==null?void 0:c.requestPayment;if(!f)throw M();let x=t==null?void 0:t.amount;if(typeof x!="number"||!Number.isFinite(x)||x<=0)throw new b("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let re={...t,amount:x,currency:Oe(t==null?void 0:t.currency,"currency")};return ot(e,()=>f(re,m))}case"printImage":{let f=c==null?void 0:c.printImage;if(!f)throw M();let x=Oe(t==null?void 0:t.image,"image");await ot(e,()=>f({image:x},m));return}case"openScreen":if(!(c!=null&&c.openScreen))throw M();await c.openScreen({screen:Oe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},m);return;case"closeApp":o();return;case"openWebview":{let f=String((y=t==null?void 0:t.url)!=null?y:"");if(!/^https?:\/\//i.test(f))throw new b("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(f):it.openURL(f));return}case"openLink":{let f=String((A=t==null?void 0:t.url)!=null?A:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new b("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(f):it.openURL(f))}catch(x){throw new b("NOT_SUPPORTED",String((N=(g=x==null?void 0:x.message)!=null?g:x)!=null?N:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(O=i==null?void 0:i.showToast)==null||O.call(i,String((E=t==null?void 0:t.message)!=null?E:""));return;case"haptic":{let f=Wt.has(t==null?void 0:t.type)?t.type:"selection";(l=i==null?void 0:i.haptic)==null||l.call(i,f);return}case"getSystemInfo":return{platform:Ht.OS==="ios"?"ios":"android",appVersion:(P=i==null?void 0:i.app_version)!=null?P:"",theme:s?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new b("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let oe=n().access_token;if(!oe)throw new b("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return oe}if(f!=="partner"&&f!=="chatbox")throw new b("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let x=ht[f];if(!r().includes(x))throw new b("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${x} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let re=f==="partner"?n().partner_token:n().chatbox_token;if(!re)throw new b("HOST_ERROR",`Kh\xF4ng c\xF3 ${x}`);return re}case"getUserInfo":{let f=n().user;if(!f)throw new b("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new b("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new b("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new b("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Le=e=>`bundle:${e}`,$e=()=>`${_().file_system.document_dir}/miniapps`,Ne=$e,Be=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Ne()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},De=e=>{var t;_().storage.setString(Le(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},jt=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,v=e=>{let t=_().storage.getString(Le(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Be(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>_().file_system.exists(e.entry_uri.replace("file://","")),Fe=async e=>{let t=v(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},yt=async(e,t)=>{let n=_().file_system,r=`${Ne()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},wt=async e=>{var t;await((t=ce[e])==null?void 0:t.catch(()=>{})),_().storage.setString(Le(e),""),await _().file_system.remove(`${Ne()}/${e}`).catch(()=>{})},ie=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},ce={},vt=(e,t)=>{var o;let r=((o=ce[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return ce[e]=s,s.then(()=>{ce[e]===s&&delete ce[e]}),r},qt=(e,t)=>{var s,o;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 u=((s=n[a])!=null?s:0)-((o=r[a])!=null?o:0);if(u)return u}return 0},Kt=({manifest:e,zip_path:t})=>vt(e.app_id,async()=>{var o;let n=_().file_system,r=v(e.app_id);if(r&&qt(r.version,e.version)>=0&&await q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=Be(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),De(e),L("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),yt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),Je=(e,{base_url:t,onProgress:n}={})=>{let r=_().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new ie},i=async()=>{var M;u();let c=v(e.app_id);if((c==null?void 0:c.version)===e.version&&await r.exists(c.dir))return De(e),v(e.app_id);u();let m=r.download({url:t?jt(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,A)=>{var N;let g=A>0?A:(N=e.size)!=null?N:0;g>0&&(n==null||n(Math.min(1,y/g)))}});s=m;try{let{status:y}=await m.promise;if(u(),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 L("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let A=Be(e.app_id,e.version,e.entry,!!e.context_update,(M=e.permissions)!=null?M:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),De(e),yt(e.app_id,[e.version,c==null?void 0:c.version].filter(Boolean)),A}catch(y){throw o?new ie:y}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:vt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},pe={},zt=__DEV__?0:60*1e3,Mt={},_t=(e,t)=>{var r,s;let n=v(e);return n&&Date.now()-((r=Mt[t])!=null?r:0)<zt?Promise.resolve(n):((s=pe[e])!=null||(pe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let a=await o.json(),u=await Je(a,{base_url:t}).promise;return Mt[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),v(e))).finally(()=>{pe[e]=void 0})),pe[e])};var ye=new Map,St=(e,t)=>(ye.set(e,t),()=>{ye.get(e)===t&&ye.delete(e)}),Yt=(e,t)=>{let n=ye.get(e);return n?n(t):!1};import{useRef as Qt,useSyncExternalStore as Gt}from"react";var we=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=Qt(null),s=()=>{let o=e.getState(),a=r.current;if(a&&a.state===o&&a.selector===t)return a.value;let u=t(o),i=a&&n(a.value,u)?a.value:u;return r.current={state:o,selector:t,value:i},i};return Gt(e.subscribe,s)};var F=we({active_key:null,instances:{}}),bt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=_().keep_alive)==null?void 0:u.max_webviews;F.setState(i=>{let c=t!=null?t:e.app_id,m={...i.instances,[c]:{key:c,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},M=Object.keys(m);return a&&a>0&&M.length>a&&M.filter(y=>y!==c).sort((y,A)=>m[y].last_used_at-m[A].last_used_at).slice(0,M.length-a).forEach(y=>{delete m[y]}),o?{active_key:c,instances:m}:{instances:m}})},Xt=e=>bt(e,!0),Zt=e=>bt(e,!1),le=()=>F.setState({active_key:null}),ve=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var xt="catalog",en="paused_apps",tn="removed_apps",nn=10*1e3,rn=2,on=3e3,sn=()=>{var e;try{return JSON.parse((e=_().storage.getString(xt))!=null?e:"{}")}catch{return{}}},w=we({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Et=e=>{var t;return!!((t=_().manual_update)!=null&&t.includes(e))},be=new Set,Rt=e=>{let t=new Set,n=()=>_().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let s=JSON.parse((r=_().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},U=Rt(en),G=Rt(tn);rt(()=>{U.load(),G.load();let e=sn(),t={};Object.keys(e).filter(n=>!G.has(n)).forEach(n=>{let r=v(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:U.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),w.setState({catalog:e,downloads:t})});var Ve=e=>j(w,t=>e?t.downloads[e]:void 0),an=()=>j(w,e=>e.pause_reasons.length>0),J=(...e)=>L("queue",...e),R=[],K={},h=null,_e=new Set,te={},Ue=new Set,Y=e=>{Ue.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},pn=e=>(Ue.add(e),()=>{Ue.delete(e)}),cn=()=>w.getState().downloads,C=(e,t)=>{let n=!!v(e),r=w.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};w.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Y({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Y({type:"progress",app_id:e,progress:o.progress,version:o.version})},Se=(e,t)=>{var n;(n=te[e])==null||n.forEach(r=>r(t)),delete te[e]},ln=()=>w.getState().pause_reasons.length>0,Q=e=>{var u;if(h)return;let t=e?R.indexOf(e):ln()?-1:R.findIndex(i=>!U.has(i));if(t<0||t>=R.length)return;let[n]=R.splice(t,1),r=w.getState().catalog[n];if(!r){Se(n,v(n)),Q();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,C(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=Je(r,{onProgress:i=>{let c=Math.floor(i*100);c!==o&&(o=c,C(n,{progress:c/100,version:r.version}))}});h={app_id:n,handle:a,forced:!!e},J("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{J("installed",n,r.version,`${Date.now()-s}ms`),C(n,{status:"installed",progress:1,version:r.version}),Se(n,i)}).catch(i=>{var m;if(i instanceof ie){if(_e.has(n))return;J("paused",n),K[n]-=1,R.unshift(n),C(n,{status:U.has(n)?"paused":"queued",progress:0,version:r.version});return}let c=String((m=i==null?void 0:i.message)!=null?m:i);if(console.warn("[miniapp-queue] failed",n,c),K[n]<rn){C(n,{status:"queued",progress:0,version:r.version,error:c}),setTimeout(()=>{var M;R.includes(n)||(h==null?void 0:h.app_id)===n||(R.push(n),Q((M=te[n])!=null&&M.length?n:void 0))},on);return}C(n,{status:"failed",progress:0,version:r.version,error:c}),Se(n,v(n))}).finally(()=>{h=null;let i=R.find(c=>{var m;return(m=te[c])==null?void 0:m.length});Q(i)})},xe=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=R.indexOf(e);if(n>=0){if(!t)return;R.splice(n,1)}t?R.unshift(e):R.push(e)},un=async e=>{let{host_id:t,client_token:n}=_(),r=new AbortController,s=setTimeout(()=>r.abort(),nn);try{let o=`${ke}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},ue=null,He=()=>(ue!=null||(ue=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(_().channels.map(un)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(w.getState().catalog).filter(i=>!r[i]);_().storage.setString(xt,JSON.stringify(r)),w.setState({catalog:r}),await Promise.all(s.map(i=>Tt(i,{by_user:!1}))),s.forEach(i=>G.delete(i));let o=Object.keys(r).filter(i=>!G.has(i)),a=[],u={};for(let i of o.map(c=>r[c])){if(await Fe(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let c=v(i.app_id);if(Et(i.app_id)&&!be.has(i.app_id)&&c&&await q(c)){C(i.app_id,{status:"installed",progress:1,version:c.version}),u[i.app_id]={app_id:i.app_id,current_version:c.version,next_version:i.version};continue}a.push(i)}return w.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,C(i.app_id,{status:U.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),xe(i.app_id)}),J("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Y({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Y({type:"update_available",...i})),Q(),{ok:!0,app_ids:o,removed:s}}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),Y({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ue=null}})()),ue),Tt=async(e,{by_user:t})=>{var s,o,a,u;if(t&&G.add(e),_e.has(e))return;_e.add(e),U.delete(e);let n=R.indexOf(e);n>=0&&R.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(u=(a=(s=w.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=v(e))==null?void 0:o.version)!=null?u:"";C(e,{status:"uninstalling",progress:0,version:r}),await wt(e),ve(e),w.setState(i=>{let c={...i.downloads};return delete c[e],{downloads:c}}),delete K[e],_e.delete(e),Se(e,null),J("uninstalled",e,t?"(user)":"(not in list)"),Y({type:"uninstalled",app_id:e})},dn=e=>Tt(e,{by_user:!0}),gn=e=>{let t=de(e);return t?(G.delete(e),(h==null?void 0:h.app_id)===e||R.includes(e)||(K[e]=0,C(e,{status:U.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),xe(e),Q(),J("restore",e)),!0):!1},fn=e=>{if(U.has(e))return;if(U.add(e),J("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=w.getState().downloads[e];R.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},hn=e=>{if(!U.delete(e))return;J("resume app",e);let t=w.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!R.includes(e)&&de(e)&&(K[e]=0,xe(e)),R.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),Q()},An=e=>{let{pause_reasons:t}=w.getState();t.includes(e)||(w.setState({pause_reasons:[...t,e]}),J("pause",e),t.length===0&&Y({type:"pause_change",paused:!0,reasons:[e]}),h&&!h.forced&&h.handle.cancel())},mn=e=>{let{pause_reasons:t}=w.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);w.setState({pause_reasons:n}),J("resume",e),n.length===0&&Y({type:"pause_change",paused:!1,reasons:n}),Q()},Pt=e=>w.getState().updates[e],Mn=async e=>{var n,r;let t=Pt(e);be.add(e);try{let s=await Ee(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=de(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(w.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),J("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{be.delete(e)}},yn=()=>Object.values(w.getState().catalog).map(e=>({...e,installed:!!v(e.app_id),removed_by_user:G.has(e.app_id)})),de=e=>w.getState().catalog[e],Ee=async e=>{let t=de(e);if(!t)return;if(U.delete(e),G.delete(e),await Fe(t))return v(e);let n=v(e);if(Et(e)&&!be.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=te[e])!=null?o:te[e]=[]).push(s)});return(h==null?void 0:h.app_id)===e?h.forced=!0:(K[e]=0,xe(e,{front:!0}),h&&!h.forced?h.handle.cancel():Q(e)),r};import{Fragment as Ot,jsx as T,jsxs as fe}from"react/jsx-runtime";var je=e=>(e!=null?e:"").replace(/\?[^#]*/,""),kt=0,xn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},En=ze.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:c,onWebLoadEnd:m})=>{var et,tt;let M=H(null),y=H(!1),A=j(F,p=>p.instances[e]),g=A==null?void 0:A.app.app_id,N=A==null?void 0:A.app.manifest_url,E=A==null?void 0:A.context,O=A==null?void 0:A.url_params,[l,P]=ne(()=>g?v(g):null),[f,x]=ne(!1),[re,oe]=ne(0),[Dt,se]=ne(0),[Lt,I]=ne(!1),W=H(null),Qe=p=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,I(!0)},p)};V(()=>()=>{W.current&&clearTimeout(W.current)},[]),V(()=>{if(!g||!t&&l)return;let p=!0;return x(!1),(async()=>{let d=v(g),k=d?await q(d):!1;if(!p||(P(k?B=>!B||B.version!==d.version||B.permissions.join(",")!==d.permissions.join(",")?d:B:null),__DEV__&&Date.now()-kt>1e4&&(kt=Date.now(),await He()),!p))return;let z=await Ee(g),X=z!==void 0?z:N?await _t(g,N):v(g);if(p){if(!X){x(!0);return}P(B=>B!=null?B:X)}})(),()=>{p=!1}},[t,g,N,re]),V(()=>St(e,p=>M.current?(M.current.postMessage(p),!0):!1),[e]);let $t=j(w,p=>{let d=g?p.downloads[g]:void 0;return(d==null?void 0:d.status)==="installed"?d.version:void 0});V(()=>{if(t||!g||!l)return;let p=v(g);if(!p||p.version===l.version)return;let d=!0;return q(p).then(k=>{!d||!k||(L(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",p.version),P(p))}),()=>{d=!1}},[t,g,$t,l==null?void 0:l.version]);let Ge=j(w,p=>{var d;return g&&(d=p.apply_ticks[g])!=null?d:0});V(()=>{if(!Ge||!g)return;let p=v(g);if(!p||p.version===(l==null?void 0:l.version))return;let d=!0;return q(p).then(k=>{!d||!k||(L(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",p.version),I(!1),P(p))}),()=>{d=!1}},[Ge]),V(()=>{var k;let p=(k=_().keep_alive)==null?void 0:k.idle_close_ms;if(t||!p||p<=0)return;let d=setTimeout(()=>{ve(e)},p);return()=>clearTimeout(d)},[t,e]),V(()=>{s>0&&(x(!1),I(!1),se(p=>p+1),oe(p=>p+1))},[s]);let Xe=H(t);V(()=>{var p;Xe.current!==t&&(Xe.current=t,y.current&&((p=M.current)==null||p.injectJavaScript(ut(t?"resumed":"paused"))))},[t]);let he=`${(et=l==null?void 0:l.version)!=null?et:"none"}:${(tt=l==null?void 0:l.permissions.join(","))!=null?tt:""}:${Dt}`,ae=Re(()=>JSON.stringify([E!=null?E:{},O!=null?O:{}]),[E,O]),Te=Re(()=>{var p;return At(O!=null?O:{},(p=l==null?void 0:l.permissions)!=null?p:[])},[ae,l==null?void 0:l.permissions]),Nt=Re(()=>ft(E!=null?E:{},Te)+lt()+(_().debug?ct():""),[Te]),Ae=H(null),Ze=H(null);V(()=>{var d,k,z;if(!l)return;if(Ze.current!==he){Ze.current=he,Ae.current=ae;return}if(Ae.current===ae)return;let p=((k=JSON.parse((d=Ae.current)!=null?d:"[]")[0])!=null?k:{}).org_id;if(Ae.current=ae,p===(E==null?void 0:E.org_id)&&y.current){I(!1),Qe(1500),(z=M.current)==null||z.injectJavaScript(dt(E!=null?E:{},Te));return}I(!1),se(X=>X+1)},[ae,l,he]);let Bt=qe(async p=>{var k,z,X,B,Pe;let d=st(p.nativeEvent.data);if(!d){if(g&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(p.nativeEvent.data,{app_id:g,instance_id:e})).catch(S=>{console.warn("[miniapp] onWebEvent l\u1ED7i",g,S)})}catch(S){console.warn("[miniapp] onWebEvent l\u1ED7i",g,S)}return}if(d.method==="log"){let{level:S,text:D}=d;L(`web:${e}`,S!=null?S:"log",D!=null?D:"");return}if(d.method==="pong"){W.current||I(!0);return}if(d.method==="touchAtTop"){o.emit(!!d.at_top);return}if(d.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,I(!0);return}if(d.method==="ready"){y.current=!0,I(!0);let S=(k=F.getState().instances[e])==null?void 0:k.context;S&&((z=M.current)==null||z.injectJavaScript(Ie(S)));return}try{let S=await mt(d,{getHostData:()=>{var D,Z;return(Z=(D=F.getState().instances[e])==null?void 0:D.host_data)!=null?Z:{}},getPermissions:()=>{var D,Z;return g?(Z=(D=v(g))==null?void 0:D.permissions)!=null?Z:[]:[]},is_dark:r,close:le,app_id:g!=null?g:"",instance_id:e,options:u});d.id&&((X=M.current)==null||X.injectJavaScript(at(d.id,S)))}catch(S){if(!d.id)return;let D=S==null?void 0:S.code,Z=S instanceof b?S:new b(typeof D=="string"?D:"HOST_ERROR",String((B=S==null?void 0:S.message)!=null?B:S));(Pe=M.current)==null||Pe.injectJavaScript(pt(d.id,Z))}},[e,r,g,o,u]),Ft=qe(()=>{x(!1),se(p=>p+1),oe(p=>p+1)},[]);return fe(Ke,{style:[Ye.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&$.behind],pointerEvents:t?"auto":"none",children:[l?T(bn,{ref:M,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${c?$e():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Nt,onMessage:Bt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{L(`webview:${e}`,"load start",je(p.nativeEvent.url)),y.current=!1,I(!1)},onError:p=>{L(`webview:${e}`,"load error",je(p.nativeEvent.url),p.nativeEvent.description),x(!0),I(!1)},onLoadEnd:p=>{let d=p.nativeEvent.url;L(`webview:${e}`,"load end",je(d)),g&&(m==null||m({app_id:g,instance_id:e,url:d})),Qe(1500)},onContentProcessDidTerminate:()=>{y.current=!1,I(!1),se(p=>p+1)},onRenderProcessGone:()=>(y.current=!1,I(!1),se(p=>p+1),!0),style:$.webview},he):null,A&&T(Tn,{visible:!l||!Lt,interactive:f,children:T(Rn,{splash:a,app:A.app,is_dark:r,error:f,has_bundle:!!l,retry:Ft})})]})}),Rn=ze.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=Ve(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return T(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Tn=({visible:e,interactive:t,children:n})=>{let r=H(new We.Value(e?1:0)).current,[s,o]=ne(e);return V(()=>{if(e){o(!0),r.setValue(1);return}let a=We.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?T(We.View,{style:[Ye.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},It=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return fe(Ke,{style:[$.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[T(Ke,{style:[$.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?T(_n,{source:{uri:e.icon},style:$.splash_icon_image}):T(ge,{style:$.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),T(ge,{style:[$.splash_name,{color:o}],children:e.name}),n==="error"?fe(Ot,{children:[T(ge,{style:$.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),T(Sn,{activeOpacity:.7,style:[$.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:T(ge,{style:[$.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):fe(Ot,{children:[T(wn,{style:$.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&fe(ge,{style:$.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Ct=(e,t)=>{let n=H(t),r=H(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Pn=({container:e,splash:t=It,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{Ct("container",e),Ct("splash",t);let i=e,c=j(F,l=>l.active_key),m=H(c);c&&(m.current=c);let M=j(F,l=>Object.keys(l.instances).join("|")),y=j(F,l=>{var P;return l.active_key?(P=l.instances[l.active_key])==null?void 0:P.app.name:void 0}),A=Re(()=>M?M.split("|"):[],[M]),[g,N]=ne({}),E=H(xn()).current;V(()=>{if(!c||!s)return;let l=vn.addEventListener("hardwareBackPress",()=>(le(),!0));return()=>l.remove()},[c,s]);let O=qe(()=>{let l=F.getState().active_key;l&&N(P=>({...P,[l]:(P[l]||0)+1}))},[]);return A.length?T(i,{visible:!!c,title:y!=null?y:"",is_dark:n,close:le,reload:O,subscribeWebAtTop:E.subscribe,children:A.map(l=>T(En,{instance_key:l,is_active:c===l,is_front:(c!=null?c:m.current)===l,is_dark:n,reload_tick:g[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},$=Ye.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"}}),kn=ze.memo(Pn);export{It as DefaultMiniAppSplash,ke as MINIAPP_PLATFORM_URL,kn as MiniAppHost,b as MiniAppHostError,le as closeMiniApp,Jt as configureMiniApp,Vt as createMmkvStorage,Ut as createRnfsFileSystem,Ee as ensureMiniApp,v as getLocalMiniApp,yn as getMiniAppCatalog,de as getMiniAppCatalogEntry,cn as getMiniAppStatuses,Pt as getMiniAppUpdate,Kt as installBundledMiniApp,pn as onMiniAppEvent,Xt as openMiniApp,fn as pauseMiniApp,An as pauseMiniAppDownloads,Zt as preloadMiniApp,gn as restoreMiniApp,hn as resumeMiniApp,mn as resumeMiniAppDownloads,Yt as sendEventToWeb,He as syncMiniAppCatalog,dn as uninstallMiniApp,Mn as updateMiniApp,Ve as useMiniAppDownload,an as useMiniAppDownloadsPaused};
45
+ true;`},yt={partner:"partner_token",chatbox:"chatbox_token"},wt=(e,t)=>{let n={...e};for(let r of Object.values(yt))t.includes(r)||delete n[r];return n},Le=new Set,Be=async(e,t)=>{if(Le.has(e))throw new A("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Le.add(e);try{return await t()}finally{Le.delete(e)}},Kt=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ye=(e,t)=>{if(typeof e!="string"||!e)throw new A("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},vt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:s,close:o,app_id:a,instance_id:u,options:i})=>{var w,m,f,N,E,O,l,R,se;let p=i==null?void 0:i.handlers,M={app_id:a,instance_id:u,close:o},y=()=>new A("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getBiometricAvailability":return((w=i==null?void 0:i.biometrics)!=null?w:await De()).getAvailability();case"authenticateBiometric":{let d=ye(t==null?void 0:t.reason,"reason").trim();if(!d||d.length>200)throw new A("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new A("INVALID_PARAMS","Invalid cancelButtonText");return Be(e,async()=>{var Z;return((Z=i==null?void 0:i.biometrics)!=null?Z:await De()).authenticate({reason:d,cancelButtonText:S})})}case"requestPayment":{let d=p==null?void 0:p.requestPayment;if(!d)throw y();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new A("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:ye(t==null?void 0:t.currency,"currency")};return Be(e,()=>d(z,M))}case"printImage":{let d=p==null?void 0:p.printImage;if(!d)throw y();let S=ye(t==null?void 0:t.image,"image");await Be(e,()=>d({image:S},M));return}case"openScreen":if(!(p!=null&&p.openScreen))throw y();await p.openScreen({screen:ye(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},M);return;case"closeApp":o();return;case"openWebview":{let d=String((m=t==null?void 0:t.url)!=null?m:"");if(!/^https?:\/\//i.test(d))throw new A("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(d):pt.openURL(d));return}case"openLink":{let d=String((f=t==null?void 0:t.url)!=null?f:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(d)||/^(javascript|file|data|about|blob):/i.test(d))throw new A("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(d):pt.openURL(d))}catch(S){throw new A("NOT_SUPPORTED",String((E=(N=S==null?void 0:S.message)!=null?N:S)!=null?E:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(l=i==null?void 0:i.showToast)==null||l.call(i,String((O=t==null?void 0:t.message)!=null?O:""));return;case"haptic":{let d=Kt.has(t==null?void 0:t.type)?t.type:"selection";(R=i==null?void 0:i.haptic)==null||R.call(i,d);return}case"getSystemInfo":return{platform:qt.OS==="ios"?"ios":"android",appVersion:(se=i==null?void 0:i.app_version)!=null?se:"",theme:s?"dark":"light"};case"getAccessToken":{let d=n().access_token;if(!d)throw new A("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return d}case"getToken":{let d=t==null?void 0:t.type;if(d==="access"){let Z=n().access_token;if(!Z)throw new A("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return Z}if(d!=="partner"&&d!=="chatbox")throw new A("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(d)}`);let S=yt[d];if(!r().includes(S))throw new A("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=d==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new A("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let d=n().user;if(!d)throw new A("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return d}case"getPageInfo":{let d=n().page;if(!d)throw new A("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return d}case"sendMessage":case"insertText":throw new A("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new A("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Fe=e=>`bundle:${e}`,Ue=()=>`${b().file_system.document_dir}/miniapps`,Ve=Ue,Je=(e,t,n="index.html",r=!1,s=[])=>{let o=`${Ve()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:s}},$e=e=>{var t;b().storage.setString(Fe(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},zt=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,_=e=>{let t=b().storage.getString(Fe(e));if(!t)return null;try{let{version:n,entry:r,context_update:s,permissions:o}=JSON.parse(t);return Je(e,n,r,!!s,Array.isArray(o)?o:[])}catch{return null}},q=e=>b().file_system.exists(e.entry_uri.replace("file://","")),He=async e=>{let t=_(e.app_id);return(t==null?void 0:t.version)===e.version&&await q(t)},St=async(e,t)=>{let n=b().file_system,r=`${Ve()}/${e}`,s=await n.listDir(r).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},bt=async e=>{var t;await((t=le[e])==null?void 0:t.catch(()=>{})),b().storage.setString(Fe(e),""),await b().file_system.remove(`${Ve()}/${e}`).catch(()=>{})},oe=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},le={},xt=(e,t)=>{var o;let r=((o=le[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=r.catch(()=>{});return le[e]=s,s.then(()=>{le[e]===s&&delete le[e]}),r},Yt=(e,t)=>{var s,o;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 u=((s=n[a])!=null?s:0)-((o=r[a])!=null?o:0);if(u)return u}return 0},Qt=({manifest:e,zip_path:t})=>xt(e.app_id,async()=>{var o;let n=b().file_system,r=_(e.app_id);if(r&&Yt(r.version,e.version)>=0&&await q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=Je(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),$e(e),L("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),St(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),s}),We=(e,{base_url:t,onProgress:n}={})=>{let r=b().file_system,s=null,o=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,u=()=>{if(o)throw new oe},i=async()=>{var y;u();let p=_(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return $e(e),_(e.app_id);u();let M=r.download({url:t?zt(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(w,m)=>{var N;let f=m>0?m:(N=e.size)!=null?N:0;f>0&&(n==null||n(Math.min(1,w/f)))}});s=M;try{let{status:w}=await M.promise;if(u(),w!==200)throw new Error(`bundle ${w}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else L("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);u();let m=Je(e.app_id,e.version,e.entry,!!e.context_update,(y=e.permissions)!=null?y:[]);return await r.remove(m.dir).catch(()=>{}),await r.mkdir(m.dir),await r.unzip(a,m.dir),$e(e),St(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),m}catch(w){throw o?new oe:w}finally{s=null,r.remove(a).catch(()=>{})}};return{promise:xt(e.app_id,i),cancel:()=>{o=!0,s==null||s.cancel()}}},pe={},Gt=__DEV__?0:60*1e3,_t={},Et=(e,t)=>{var r,s;let n=_(e);return n&&Date.now()-((r=_t[t])!=null?r:0)<Gt?Promise.resolve(n):((s=pe[e])!=null||(pe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let a=await o.json(),u=await We(a,{base_url:t}).promise;return _t[t]=Date.now(),u})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),_(e))).finally(()=>{pe[e]=void 0})),pe[e])};var _e=new Map,Tt=(e,t)=>(_e.set(e,t),()=>{_e.get(e)===t&&_e.delete(e)}),Xt=(e,t)=>{let n=_e.get(e);return n?n(t):!1};import{useRef as Zt,useSyncExternalStore as en}from"react";var Se=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let s=typeof r=="function"?r(t):r;t={...t,...s},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},j=(e,t,n=Object.is)=>{let r=Zt(null),s=()=>{let o=e.getState(),a=r.current;if(a&&a.state===o&&a.selector===t)return a.value;let u=t(o),i=a&&n(a.value,u)?a.value:u;return r.current={state:o,selector:t,value:i},i};return en(e.subscribe,s)};var F=Se({active_key:null,instances:{}}),Pt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:s={}},o)=>{var u;let a=(u=b().keep_alive)==null?void 0:u.max_webviews;F.setState(i=>{let p=t!=null?t:e.app_id,M={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:s,last_used_at:Date.now()}},y=Object.keys(M);return a&&a>0&&y.length>a&&y.filter(w=>w!==p).sort((w,m)=>M[w].last_used_at-M[m].last_used_at).slice(0,y.length-a).forEach(w=>{delete M[w]}),o?{active_key:p,instances:M}:{instances:M}})},tn=e=>Pt(e,!0),nn=e=>Pt(e,!1),ue=()=>F.setState({active_key:null}),be=e=>{F.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Rt="catalog",rn="paused_apps",on="removed_apps",sn=10*1e3,an=2,cn=3e3,pn=()=>{var e;try{return JSON.parse((e=b().storage.getString(Rt))!=null?e:"{}")}catch{return{}}},v=Se({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),kt=e=>{var t;return!!((t=b().manual_update)!=null&&t.includes(e))},Te=new Set,Ct=e=>{let t=new Set,n=()=>b().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 s=JSON.parse((r=b().storage.getString(e))!=null?r:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},V=Ct(rn),X=Ct(on);at(()=>{V.load(),X.load();let e=pn(),t={};Object.keys(e).filter(n=>!X.has(n)).forEach(n=>{let r=_(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:V.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),v.setState({catalog:e,downloads:t})});var qe=e=>j(v,t=>e?t.downloads[e]:void 0),ln=()=>j(v,e=>e.pause_reasons.length>0),U=(...e)=>L("queue",...e),T=[],K={},h=null,xe=new Set,re={},je=new Set,Q=e=>{je.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},un=e=>(je.add(e),()=>{je.delete(e)}),dn=()=>v.getState().downloads,C=(e,t)=>{let n=!!_(e),r=v.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};v.setState(a=>({downloads:{...a.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?Q({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&Q({type:"progress",app_id:e,progress:o.progress,version:o.version})},Ee=(e,t)=>{var n;(n=re[e])==null||n.forEach(r=>r(t)),delete re[e]},gn=()=>v.getState().pause_reasons.length>0,G=e=>{var u;if(h)return;let t=e?T.indexOf(e):gn()?-1:T.findIndex(i=>!V.has(i));if(t<0||t>=T.length)return;let[n]=T.splice(t,1),r=v.getState().catalog[n];if(!r){Ee(n,_(n)),G();return}let s=Date.now();K[n]=((u=K[n])!=null?u:0)+1,C(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,a=We(r,{onProgress:i=>{let p=Math.floor(i*100);p!==o&&(o=p,C(n,{progress:p/100,version:r.version}))}});h={app_id:n,handle:a,forced:!!e},U("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{U("installed",n,r.version,`${Date.now()-s}ms`),C(n,{status:"installed",progress:1,version:r.version}),Ee(n,i)}).catch(i=>{var M;if(i instanceof oe){if(xe.has(n))return;U("paused",n),K[n]-=1,T.unshift(n),C(n,{status:V.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((M=i==null?void 0:i.message)!=null?M:i);if(console.warn("[miniapp-queue] failed",n,p),K[n]<an){C(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var y;T.includes(n)||(h==null?void 0:h.app_id)===n||(T.push(n),G((y=re[n])!=null&&y.length?n:void 0))},cn);return}C(n,{status:"failed",progress:0,version:r.version,error:p}),Ee(n,_(n))}).finally(()=>{h=null;let i=T.find(p=>{var M;return(M=re[p])==null?void 0:M.length});G(i)})},Pe=(e,{front:t=!1}={})=>{if((h==null?void 0:h.app_id)===e)return;let n=T.indexOf(e);if(n>=0){if(!t)return;T.splice(n,1)}t?T.unshift(e):T.push(e)},fn=async e=>{let{host_id:t,client_token:n}=b(),r=new AbortController,s=setTimeout(()=>r.abort(),sn);try{let o=`${Ie}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(s)}},de=null,Ke=()=>(de!=null||(de=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(b().channels.map(fn)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let s=Object.keys(v.getState().catalog).filter(i=>!r[i]);b().storage.setString(Rt,JSON.stringify(r)),v.setState({catalog:r}),await Promise.all(s.map(i=>Ot(i,{by_user:!1}))),s.forEach(i=>X.delete(i));let o=Object.keys(r).filter(i=>!X.has(i)),a=[],u={};for(let i of o.map(p=>r[p])){if(await He(i)){C(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=_(i.app_id);if(kt(i.app_id)&&!Te.has(i.app_id)&&p&&await q(p)){C(i.app_id,{status:"installed",progress:1,version:p.version}),u[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return v.setState({updates:u}),a.forEach(i=>{K[i.app_id]=0,C(i.app_id,{status:V.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Pe(i.app_id)}),U("catalog",o.length,"apps, outdated",a.map(i=>i.app_id),"removed",s,`${Date.now()-e}ms`),Q({type:"sync_complete",app_ids:o,removed:s}),Object.values(u).forEach(i=>Q({type:"update_available",...i})),G(),{ok:!0,app_ids:o,removed:s}}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),Q({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{de=null}})()),de),Ot=async(e,{by_user:t})=>{var s,o,a,u;if(t&&X.add(e),xe.has(e))return;xe.add(e),V.delete(e);let n=T.indexOf(e);n>=0&&T.splice(n,1),(h==null?void 0:h.app_id)===e&&h.handle.cancel();let r=(u=(a=(s=v.getState().downloads[e])==null?void 0:s.version)!=null?a:(o=_(e))==null?void 0:o.version)!=null?u:"";C(e,{status:"uninstalling",progress:0,version:r}),await bt(e),be(e),v.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete K[e],xe.delete(e),Ee(e,null),U("uninstalled",e,t?"(user)":"(not in list)"),Q({type:"uninstalled",app_id:e})},hn=e=>Ot(e,{by_user:!0}),mn=e=>{let t=ge(e);return t?(X.delete(e),(h==null?void 0:h.app_id)===e||T.includes(e)||(K[e]=0,C(e,{status:V.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Pe(e),G(),U("restore",e)),!0):!1},An=e=>{if(V.has(e))return;if(V.add(e),U("pause app",e),(h==null?void 0:h.app_id)===e&&!h.forced){h.handle.cancel();return}let t=v.getState().downloads[e];T.includes(e)&&t&&C(e,{status:"paused",progress:0,version:t.version})},Mn=e=>{if(!V.delete(e))return;U("resume app",e);let t=v.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!T.includes(e)&&ge(e)&&(K[e]=0,Pe(e)),T.includes(e)&&t&&C(e,{status:"queued",progress:0,version:t.version}),G()},yn=e=>{let{pause_reasons:t}=v.getState();t.includes(e)||(v.setState({pause_reasons:[...t,e]}),U("pause",e),t.length===0&&Q({type:"pause_change",paused:!0,reasons:[e]}),h&&!h.forced&&h.handle.cancel())},wn=e=>{let{pause_reasons:t}=v.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);v.setState({pause_reasons:n}),U("resume",e),n.length===0&&Q({type:"pause_change",paused:!1,reasons:n}),G()},It=e=>v.getState().updates[e],vn=async e=>{var n,r;let t=It(e);Te.add(e);try{let s=await Re(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=ge(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(v.setState(a=>{var i;let u={...a.updates};return delete u[e],{updates:u,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),U("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Te.delete(e)}},_n=()=>Object.values(v.getState().catalog).map(e=>({...e,installed:!!_(e.app_id),removed_by_user:X.has(e.app_id)})),ge=e=>v.getState().catalog[e],Re=async e=>{let t=ge(e);if(!t)return;if(V.delete(e),X.delete(e),await He(t))return _(e);let n=_(e);if(kt(e)&&!Te.has(e)&&n&&await q(n))return n;let r=new Promise(s=>{var o;((o=re[e])!=null?o:re[e]=[]).push(s)});return(h==null?void 0:h.app_id)===e?h.forced=!0:(K[e]=0,Pe(e,{front:!0}),h&&!h.forced?h.handle.cancel():G(e)),r};import{Fragment as Bt,jsx as P,jsxs as he}from"react/jsx-runtime";var Ye=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Dt=0,Pn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Rn=Xe.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:s,web_at_top:o,splash:a,bridge:u,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:M})=>{var it,ot;let y=H(null),w=H(!1),m=j(F,c=>c.instances[e]),f=m==null?void 0:m.app.app_id,N=m==null?void 0:m.app.manifest_url,E=m==null?void 0:m.context,O=m==null?void 0:m.url_params,[l,R]=ie(()=>f?_(f):null),[se,d]=ie(!1),[S,z]=ie(0),[Z,ae]=ie(0),[$t,I]=ie(!1),W=H(null),et=c=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{W.current=null,I(!0)},c)};J(()=>()=>{W.current&&clearTimeout(W.current)},[]),J(()=>{if(!f||!t&&l)return;let c=!0;return d(!1),(async()=>{let g=_(f),k=g?await q(g):!1;if(!c||(R(k?$=>!$||$.version!==g.version||$.permissions.join(",")!==g.permissions.join(",")?g:$:null),__DEV__&&Date.now()-Dt>1e4&&(Dt=Date.now(),await Ke()),!c))return;let Y=await Re(f),ee=Y!==void 0?Y:N?await Et(f,N):_(f);if(c){if(!ee){d(!0);return}R($=>$!=null?$:ee)}})(),()=>{c=!1}},[t,f,N,S]),J(()=>Tt(e,c=>y.current?(y.current.postMessage(c),!0):!1),[e]);let Ft=j(v,c=>{let g=f?c.downloads[f]:void 0;return(g==null?void 0:g.status)==="installed"?g.version:void 0});J(()=>{if(t||!f||!l)return;let c=_(f);if(!c||c.version===l.version)return;let g=!0;return q(c).then(k=>{!g||!k||(L(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",l.version,"\u2192",c.version),R(c))}),()=>{g=!1}},[t,f,Ft,l==null?void 0:l.version]);let tt=j(v,c=>{var g;return f&&(g=c.apply_ticks[f])!=null?g:0});J(()=>{if(!tt||!f)return;let c=_(f);if(!c||c.version===(l==null?void 0:l.version))return;let g=!0;return q(c).then(k=>{!g||!k||(L(`webview:${e}`,"c\u1EADp nh\u1EADt",l==null?void 0:l.version,"\u2192",c.version),I(!1),R(c))}),()=>{g=!1}},[tt]),J(()=>{var k;let c=(k=b().keep_alive)==null?void 0:k.idle_close_ms;if(t||!c||c<=0)return;let g=setTimeout(()=>{be(e)},c);return()=>clearTimeout(g)},[t,e]),J(()=>{s>0&&(d(!1),I(!1),ae(c=>c+1),z(c=>c+1))},[s]);let nt=H(t);J(()=>{var c;nt.current!==t&&(nt.current=t,w.current&&((c=y.current)==null||c.injectJavaScript(ht(t?"resumed":"paused"))))},[t]);let me=`${(it=l==null?void 0:l.version)!=null?it:"none"}:${(ot=l==null?void 0:l.permissions.join(","))!=null?ot:""}:${Z}`,ce=ke(()=>JSON.stringify([E!=null?E:{},O!=null?O:{}]),[E,O]),Ce=ke(()=>{var c;return wt(O!=null?O:{},(c=l==null?void 0:l.permissions)!=null?c:[])},[ce,l==null?void 0:l.permissions]),Ut=ke(()=>Mt(E!=null?E:{},Ce)+ft()+(b().debug?gt():""),[Ce]),Ae=H(null),rt=H(null);J(()=>{var g,k,Y;if(!l)return;if(rt.current!==me){rt.current=me,Ae.current=ce;return}if(Ae.current===ce)return;let c=((k=JSON.parse((g=Ae.current)!=null?g:"[]")[0])!=null?k:{}).org_id;if(Ae.current=ce,c===(E==null?void 0:E.org_id)&&w.current){I(!1),et(1500),(Y=y.current)==null||Y.injectJavaScript(mt(E!=null?E:{},Ce));return}I(!1),ae(ee=>ee+1)},[ce,l,me]);let Vt=Qe(async c=>{var k,Y,ee,$,Oe;let g=lt(c.nativeEvent.data);if(!g){if(f&&(u!=null&&u.onWebEvent))try{Promise.resolve(u.onWebEvent(c.nativeEvent.data,{app_id:f,instance_id:e})).catch(x=>{console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)})}catch(x){console.warn("[miniapp] onWebEvent l\u1ED7i",f,x)}return}if(g.method==="log"){let{level:x,text:D}=g;L(`web:${e}`,x!=null?x:"log",D!=null?D:"");return}if(g.method==="pong"){W.current||I(!0);return}if(g.method==="touchAtTop"){o.emit(!!g.at_top);return}if(g.method==="contextApplied"){W.current&&clearTimeout(W.current),W.current=null,I(!0);return}if(g.method==="ready"){w.current=!0,I(!0);let x=(k=F.getState().instances[e])==null?void 0:k.context;x&&((Y=y.current)==null||Y.injectJavaScript(Ne(x)));return}try{let x=await vt(g,{getHostData:()=>{var D,te;return(te=(D=F.getState().instances[e])==null?void 0:D.host_data)!=null?te:{}},getPermissions:()=>{var D,te;return f?(te=(D=_(f))==null?void 0:D.permissions)!=null?te:[]:[]},is_dark:r,close:ue,app_id:f!=null?f:"",instance_id:e,options:u});g.id&&((ee=y.current)==null||ee.injectJavaScript(ut(g.id,x)))}catch(x){if(!g.id)return;let D=x==null?void 0:x.code,te=x instanceof A?x:new A(typeof D=="string"?D:"HOST_ERROR",String(($=x==null?void 0:x.message)!=null?$:x));(Oe=y.current)==null||Oe.injectJavaScript(dt(g.id,te))}},[e,r,f,o,u]),Jt=Qe(()=>{d(!1),ae(c=>c+1),z(c=>c+1)},[]);return he(Ge,{style:[Ze.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&B.behind],pointerEvents:t?"auto":"none",children:[l?P(Tn,{ref:y,source:{uri:l.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?Ue():l.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ut,onMessage:Vt,bounces:!1,overScrollMode:"never",onLoadStart:c=>{L(`webview:${e}`,"load start",Ye(c.nativeEvent.url)),w.current=!1,I(!1)},onError:c=>{L(`webview:${e}`,"load error",Ye(c.nativeEvent.url),c.nativeEvent.description),d(!0),I(!1)},onLoadEnd:c=>{let g=c.nativeEvent.url;L(`webview:${e}`,"load end",Ye(g)),f&&(M==null||M({app_id:f,instance_id:e,url:g})),et(1500)},onContentProcessDidTerminate:()=>{w.current=!1,I(!1),ae(c=>c+1)},onRenderProcessGone:()=>(w.current=!1,I(!1),ae(c=>c+1),!0),style:B.webview},me):null,m&&P(Cn,{visible:!l||!$t,interactive:se,children:P(kn,{splash:a,app:m.app,is_dark:r,error:se,has_bundle:!!l,retry:Jt})})]})}),kn=Xe.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:s,retry:o})=>{let a=e,u=qe(t.app_id),i=r?"error":!s&&(u==null?void 0:u.status)==="downloading"?"downloading":"loading";return P(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?u==null?void 0:u.progress:void 0,retry:o})}),Cn=({visible:e,interactive:t,children:n})=>{let r=H(new ze.Value(e?1:0)).current,[s,o]=ie(e);return J(()=>{if(e){o(!0),r.setValue(1);return}let a=ze.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:u})=>{u&&o(!1)}),()=>a.stop()},[e,r]),s?P(ze.View,{style:[Ze.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Nt=({app:e,is_dark:t,status:n,progress:r,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return he(Ge,{style:[B.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[P(Ge,{style:[B.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?P(xn,{source:{uri:e.icon},style:B.splash_icon_image}):P(fe,{style:B.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),P(fe,{style:[B.splash_name,{color:o}],children:e.name}),n==="error"?he(Bt,{children:[P(fe,{style:B.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),P(En,{activeOpacity:.7,style:[B.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:P(fe,{style:[B.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):he(Bt,{children:[P(Sn,{style:B.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&he(fe,{style:B.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Lt=(e,t)=>{let n=H(t),r=H(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},On=({container:e,splash:t=Nt,is_dark:n=!1,bridge:r,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:u})=>{Lt("container",e),Lt("splash",t);let i=e,p=j(F,l=>l.active_key),M=H(p);p&&(M.current=p);let y=j(F,l=>Object.keys(l.instances).join("|")),w=j(F,l=>{var R;return l.active_key?(R=l.instances[l.active_key])==null?void 0:R.app.name:void 0}),m=ke(()=>y?y.split("|"):[],[y]),[f,N]=ie({}),E=H(Pn()).current;J(()=>{if(!p||!s)return;let l=bn.addEventListener("hardwareBackPress",()=>(ue(),!0));return()=>l.remove()},[p,s]);let O=Qe(()=>{let l=F.getState().active_key;l&&N(R=>({...R,[l]:(R[l]||0)+1}))},[]);return m.length?P(i,{visible:!!p,title:w!=null?w:"",is_dark:n,close:ue,reload:O,subscribeWebAtTop:E.subscribe,children:m.map(l=>P(Rn,{instance_key:l,is_active:p===l,is_front:(p!=null?p:M.current)===l,is_dark:n,reload_tick:f[l]||0,web_at_top:E,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:a,onWebLoadEnd:u},l))}):null},B=Ze.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"}}),In=Xe.memo(On);export{Nt as DefaultMiniAppSplash,Ie as MINIAPP_PLATFORM_URL,In as MiniAppHost,A as MiniAppHostError,ue as closeMiniApp,Ht as configureMiniApp,jt as createMmkvStorage,ct as createReactNativeBiometrics,Wt as createRnfsFileSystem,Re as ensureMiniApp,_ as getLocalMiniApp,_n as getMiniAppCatalog,ge as getMiniAppCatalogEntry,dn as getMiniAppStatuses,It as getMiniAppUpdate,Qt as installBundledMiniApp,un as onMiniAppEvent,tn as openMiniApp,An as pauseMiniApp,yn as pauseMiniAppDownloads,nn as preloadMiniApp,mn as restoreMiniApp,Mn as resumeMiniApp,wn as resumeMiniAppDownloads,Xt as sendEventToWeb,Ke as syncMiniAppCatalog,hn as uninstallMiniApp,vn as updateMiniApp,qe as useMiniAppDownload,ln as useMiniAppDownloadsPaused};