@retion-miniapp/react-native 0.10.2 → 0.10.3
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/dist/index.d.mts +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +6 -6
- package/dist/index.mjs +6 -6
- package/docs/MINIAPP_README.md +1 -1
- package/docs/NATIVE_APIS.md +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -675,7 +675,15 @@ interface UploadFilesResult {
|
|
|
675
675
|
message: string;
|
|
676
676
|
}[];
|
|
677
677
|
}
|
|
678
|
+
/** 1 loại file của nguồn — web hiện `label`, truyền `accept` vào uploadFiles. */
|
|
679
|
+
interface UploadFileType {
|
|
680
|
+
type: string;
|
|
681
|
+
label: string;
|
|
682
|
+
accept: string[];
|
|
683
|
+
}
|
|
678
684
|
interface UploadCapabilities {
|
|
685
|
+
/** Loại file theo nguồn có sẵn; nguồn app tự đăng ký không có mục này. */
|
|
686
|
+
file_types: Record<string, UploadFileType[]>;
|
|
679
687
|
sources: string[];
|
|
680
688
|
targets: string[];
|
|
681
689
|
max_count: number;
|
|
@@ -683,4 +691,4 @@ interface UploadCapabilities {
|
|
|
683
691
|
/** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
|
|
684
692
|
declare const uploadToUrl: MiniAppUploader;
|
|
685
693
|
|
|
686
|
-
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
|
|
694
|
+
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
|
package/dist/index.d.ts
CHANGED
|
@@ -675,7 +675,15 @@ interface UploadFilesResult {
|
|
|
675
675
|
message: string;
|
|
676
676
|
}[];
|
|
677
677
|
}
|
|
678
|
+
/** 1 loại file của nguồn — web hiện `label`, truyền `accept` vào uploadFiles. */
|
|
679
|
+
interface UploadFileType {
|
|
680
|
+
type: string;
|
|
681
|
+
label: string;
|
|
682
|
+
accept: string[];
|
|
683
|
+
}
|
|
678
684
|
interface UploadCapabilities {
|
|
685
|
+
/** Loại file theo nguồn có sẵn; nguồn app tự đăng ký không có mục này. */
|
|
686
|
+
file_types: Record<string, UploadFileType[]>;
|
|
679
687
|
sources: string[];
|
|
680
688
|
targets: string[];
|
|
681
689
|
max_count: number;
|
|
@@ -683,4 +691,4 @@ interface UploadCapabilities {
|
|
|
683
691
|
/** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
|
|
684
692
|
declare const uploadToUrl: MiniAppUploader;
|
|
685
693
|
|
|
686
|
-
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
|
|
694
|
+
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFileType, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Vn=Object.create;var $e=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Wn=Object.prototype.hasOwnProperty;var Jn=(e,t)=>{for(var n in t)$e(e,n,{get:t[n],enumerable:!0})},Et=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of zn(t))!Wn.call(e,i)&&i!==n&&$e(e,i,{get:()=>t[i],enumerable:!(r=jn(t,i))||r.enumerable});return e};var ue=(e,t,n)=>(n=e!=null?Vn(Hn(e)):{},Et(t||!e||!e.__esModule?$e(n,"default",{value:e,enumerable:!0}):n,e)),Kn=e=>Et($e({},"__esModule",{value:!0}),e);var Dr={};Jn(Dr,{DefaultMiniAppSplash:()=>St,MINIAPP_PLATFORM_URL:()=>Be,MiniAppHost:()=>Bn,MiniAppHostError:()=>u,closeMiniApp:()=>be,configureMiniApp:()=>Rt,createMmkvStorage:()=>Ct,createReactNativeBiometrics:()=>it,createRnfsFileSystem:()=>Tt,ensureMiniApp:()=>Ne,getLocalMiniApp:()=>R,getMiniAppCatalog:()=>Nn,getMiniAppCatalogEntry:()=>xe,getMiniAppStatuses:()=>Pn,getMiniAppUpdate:()=>Mt,installBundledMiniApp:()=>fn,onMiniAppEvent:()=>En,openMiniApp:()=>Mn,pauseMiniApp:()=>Cn,pauseMiniAppDownloads:()=>In,preloadMiniApp:()=>vn,releaseSpeechFor:()=>te,restoreMiniApp:()=>Tn,resumeMiniApp:()=>kn,resumeMiniAppDownloads:()=>Ln,sendEventToWeb:()=>wn,syncMiniAppCatalog:()=>tt,uninstallMiniApp:()=>On,updateMiniApp:()=>Dn,uploadToUrl:()=>ct,useMiniAppDownload:()=>Ze,useMiniAppDownloadsPaused:()=>xn});module.exports=Kn(Dr);var Be="https://retion-miniapp-platform.vercel.app",we=null,Pt=new Set,Rt=e=>{we=e,Pt.forEach(t=>t())},k=()=>{if(!we)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return we},Ot=e=>{Pt.add(e),we&&e()},J=(...e)=>{we!=null&&we.debug&&console.log("[miniapp]",...e)};var Tt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(i=>i.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:i})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>i==null?void 0:i(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Ct=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var y=ue(require("react")),E=require("react-native"),$n=ue(require("react-native-webview"));var Ce=require("react-native");var it=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),qe,ot=()=>(qe||(qe=import("react-native-biometrics").then(({default:e})=>it(new e({allowDeviceCredentials:!1}))).catch(e=>{throw qe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),qe);var ee=require("react-native");var kt=e=>{var n,r,i;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(i=t.maximumAge)!=null?i:0}},It=(e,t=()=>!0)=>new Promise((n,r)=>{let i=!1,o=(a,s)=>{i||(i=!0,clearTimeout(c),a?r(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>i?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(ee.Platform.OS==="android"){let s=ee.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=ee.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ee.PermissionsAndroid.check(s);if(!p())return;let A=g||await ee.PermissionsAndroid.check(d);if(!p())return;if(!g&&!A){let l=await ee.PermissionsAndroid.requestMultiple([s,d]);if(!p())return;if(l[s]!==ee.PermissionsAndroid.RESULTS.GRANTED&&l[d]!==ee.PermissionsAndroid.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});var at=require("react-native");var st=20,Lt=20,Ut=/^[a-z][a-z0-9_-]{0,31}$/,Yn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Gn=["low","medium","high"],de=e=>!!e&&typeof e=="object"&&!Array.isArray(e),N=e=>new u("INVALID_PARAMS",e),Oe=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Dt=(e,t)=>{if(e===void 0)return{};if(!de(e)||Object.keys(e).length>Lt||Object.values(e).some(n=>typeof n!="string"))throw N(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Lt} key)`);return e},Ft=e=>{var n,r,i,o;if(e!==void 0&&!de(e))throw N("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ut.test(t.source)))throw N("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Yn.test(c))))throw N("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Oe(t.max_count,1,st))throw N(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${st}`);if(t.max_size!==void 0&&!Oe(t.max_size,1,Number.MAX_SAFE_INTEGER))throw N("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Oe(t.concurrency,1,5))throw N("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(c=>c.toLowerCase()),max_count:(i=t.max_count)!=null?i:1,max_size:t.max_size,process:Qn(t.process),target:Xn(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Qn=e=>{if(e===void 0)return{};if(!de(e))throw N("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!de(n))throw N("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Oe(n[r],1,1e4))throw N(`process.image.${r} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw N("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!de(n))throw N("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Oe(n.max_duration,1,3600))throw N("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Gn.includes(n.quality))throw N("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Xn=e=>{var n,r,i,o;if(e===void 0)return{target:"host",params:{}};if(!de(e))throw N("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ut.test(t))throw N("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!de(e.params))throw N("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw N("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw N(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Dt(e.headers,"upload.headers"),form_data:Dt(e.form_data,"upload.form_data"),field_name:(i=e.field_name)!=null?i:"file",url_field:(o=e.url_field)!=null?o:"url"}},$t=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Zn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=$t(e.name);return t.some(i=>i==="*/*"?!0:i.startsWith(".")?i===r:i.endsWith("/*")?n.startsWith(i.slice(0,-1)):n===i)},er=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},Ee,tr=()=>(Ee!=null||(Ee=import("react-native-image-picker").catch(e=>{throw Ee=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ee),Nt=e=>async({accept:t,max_count:n,process:r})=>{var a,s,d,g,A,l,h,T,_;let i=await tr(),o=er(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=r.image)==null?void 0:a.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(A=r.video)==null?void 0:A.quality)!=null?l:"medium",durationLimit:(h=r.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await i.launchCamera({...c,saveToPhotos:!1}):await i.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let b=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(b,(T=p.errorMessage)!=null?T:p.errorCode)}return((_=p.assets)!=null?_:[]).filter(b=>b.uri).map((b,f)=>{var L,G,$;return{uri:b.uri,name:(L=b.fileName)!=null?L:`file_${f+1}`,mime_type:(G=b.type)!=null?G:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!(($=b.type)!=null&&$.startsWith("video/"))||at.Platform.OS==="ios"}})},nr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},rr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},ir=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let r=t.map(s=>{var d;return(d=nr[s])!=null?d:rr[s]}),i=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:i,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var T,_,b;return{uri:l.uri,name:(T=l.name)!=null?T:`file_${h+1}`,mime_type:(_=l.type)!=null?_:"application/octet-stream",size:(b=l.size)!=null?b:void 0}});if(at.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),A=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=A.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Pe,or=async e=>(Pe!=null||(Pe=import("@react-native-documents/picker").then(t=>ir(t)).catch(t=>{throw Pe=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Pe)(e)),sr={library:Nt("library"),camera:Nt("camera"),document:or},Re,Bt=()=>(Re!=null||(Re=import("react-native-compressor").catch(()=>(Re=void 0,null))),Re),qt=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},ar=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),cr={low:640,medium:1280,high:1920},pr=async(e,{image:t})=>{var r;if(!t||!ar.has(e.mime_type.toLowerCase()))return e;let n=await Bt();if(!n)return e;try{let i=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:i,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await qt(n,i,e.size),processed:!0}}catch{return e}},lr=async(e,{video:t})=>{var r;let n=await Bt();if(!n)return e;try{let i=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:cr[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:i,mime_type:"video/mp4",size:await qt(n,i,e.size),processed:!0}}catch{return e}},ur={image:pr,video:lr},dr=(e,t)=>t.split(".").reduce((n,r)=>de(n)?n[r]:void 0,e),ct=({file:e,target:t,onProgress:n,signal:r})=>new Promise((i,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(r.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,A])=>a.append(g,A)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,A])=>p.setRequestHeader(g,A)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let A=dr(g,c.url_field);if(typeof A!="string"||!A){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}i({url:A,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Vt=e=>{var r,i;let t={...sr};for(let[o,c]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))c?t[o]=c:delete t[o];let n={url:ct};for(let[o,c]of Object.entries((i=e==null?void 0:e.targets)!=null?i:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},jt=e=>{let{sources:t,targets:n}=Vt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:st}},je=new Map,zt=(e,t)=>`${e}:${t}`,gr=0,Ht=(e,t)=>{var n;typeof t=="string"&&((n=je.get(zt(e,t)))==null||n.abort())},ye=e=>{for(let[t,n]of je)t.startsWith(`${e}:`)&&n.abort()},Ve=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),mr=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Wt=async(e,t)=>{var a;let{sources:n,targets:r}=Vt(t.config),i=n[e.source];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=r[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=zt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++gr}`);je.set(p,c);try{return await fr(e,t,i,o,c.signal)}finally{je.delete(p)}},fr=async(e,{instance_id:t,app_id:n,getContext:r,task_id:i,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var w,S,z;let g={app_id:n!=null?n:"",instance_id:t,context:{...(w=r==null?void 0:r())!=null?w:{}}},A=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw Ve();if(!A.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=A.filter(v=>Zn(v,e.accept)?!0:(l.push({name:v.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${v.mime_type||$t(v.name)}`}),!1)),T=h.map(()=>0),_=h.map(v=>{var D;return(D=v.size)!=null?D:0}),b=0,f=0,L=(v=!1)=>{if(!c||!i)return;let D=Date.now();if(!v&&D-f<200)return;f=D;let re=_.reduce((C,H)=>C+H,0),B=T.reduce((C,H)=>C+H,0);c("upload.progress",{task_id:i,loaded:B,total:re,percent:re?Math.min(100,Math.round(B/re*100)):0,done_count:b,count:h.length})},G=[],$=0,Se=async()=>{var v,D,re;for(;$<h.length;){let B=$++,C=h[B];try{if(d.aborted)throw Ve();let H=C.mime_type.startsWith("image/")?"image":C.mime_type.startsWith("video/")?"video":void 0,pe=H&&!C.processed?(D=(v=o==null?void 0:o.processors)==null?void 0:v[H])!=null?D:ur[H]:void 0;if(pe&&(C=await pe(C,e.process),_[B]=(re=C.size)!=null?re:_[B],d.aborted))throw Ve();if(e.max_size&&C.size&&C.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${C.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let he=(Ue,Fe)=>{T[B]=Ue,Fe&&(_[B]=Fe),L()},ie=await s({file:C,target:e.target,onProgress:he,signal:d,caller:g});if(typeof(ie==null?void 0:ie.url)!="string"||!ie.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:nt,...oe}=ie;G[B]={url:nt,name:C.name,mime_type:C.mime_type,size:C.size,width:C.width,height:C.height,duration:C.duration,...Object.keys(oe).length?{response:"response"in oe?oe.response:oe}:{}},T[B]=_[B]}catch(H){l.push(mr(h[B].name,H))}finally{b++,L(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},Se)),d.aborted)throw Ve();let ce=G.filter(v=>!!v);if(!ce.length){let v=l[0];throw new u((S=v==null?void 0:v.code)!=null?S:"UPLOAD_FAILED",(z=v==null?void 0:v.message)!=null?z:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:l}};var Me=require("react-native");var K,Jt=()=>Me.Platform.OS==="android"&&!!(K!=null&&K.requesting_permission),hr=1500,Ar=()=>new Promise(e=>{if(Me.Platform.OS!=="android"||Me.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),r.remove(),e()},n=setTimeout(t,hr),r=Me.AppState.addEventListener("change",i=>{i==="active"&&t()})}),pt=e=>{var t;if(K===e&&(K=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Me.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Kt=async(e,t,n,r=()=>!0)=>{var o,c,p,a,s;if(K)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let i={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};K=i;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(i.native=g,i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.requesting_permission=!0;let A;try{A=await g.requestPermissionsAsync()}finally{i.requesting_permission=!1}if(await Ar(),i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!A.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.subscriptions.push(g.addListener("result",l=>{var h,T;K!==i||i.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(T=(h=l.results[0])==null?void 0:h.transcript)!=null?T:""})}),g.addListener("error",l=>{K===i&&!i.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{K===i&&(pt(i),n("speech.end"))})),i.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw pt(i),d}},Yt=e=>{let t=K;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},te=e=>{let t=K;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{pt(t)}};var He=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Gt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===He&&typeof t.method=="string"?t:null}catch{return null}},ke=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Qt=(e,t)=>ke({id:e,result:t}),Xt=(e,t)=>ke({id:e,error:{code:t.code,message:t.message}}),Zt=(e,t)=>ke({event:e,data:t}),ut=e=>ke({event:"context",data:e});var en=()=>`(function () {
|
|
1
|
+
"use strict";var Wn=Object.create;var $e=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var Kn=Object.getOwnPropertyNames;var Yn=Object.getPrototypeOf,Gn=Object.prototype.hasOwnProperty;var Qn=(e,t)=>{for(var n in t)$e(e,n,{get:t[n],enumerable:!0})},Et=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Kn(t))!Gn.call(e,r)&&r!==n&&$e(e,r,{get:()=>t[r],enumerable:!(i=Jn(t,r))||i.enumerable});return e};var ue=(e,t,n)=>(n=e!=null?Wn(Yn(e)):{},Et(t||!e||!e.__esModule?$e(n,"default",{value:e,enumerable:!0}):n,e)),Xn=e=>Et($e({},"__esModule",{value:!0}),e);var Fi={};Qn(Fi,{DefaultMiniAppSplash:()=>St,MINIAPP_PLATFORM_URL:()=>Be,MiniAppHost:()=>zn,MiniAppHostError:()=>u,closeMiniApp:()=>be,configureMiniApp:()=>Rt,createMmkvStorage:()=>Ct,createReactNativeBiometrics:()=>rt,createRnfsFileSystem:()=>Tt,ensureMiniApp:()=>Ue,getLocalMiniApp:()=>R,getMiniAppCatalog:()=>Bn,getMiniAppCatalogEntry:()=>xe,getMiniAppStatuses:()=>Cn,getMiniAppUpdate:()=>Mt,installBundledMiniApp:()=>wn,onMiniAppEvent:()=>Tn,openMiniApp:()=>bn,pauseMiniApp:()=>Dn,pauseMiniAppDownloads:()=>Nn,preloadMiniApp:()=>xn,releaseSpeechFor:()=>te,restoreMiniApp:()=>Ln,resumeMiniApp:()=>Un,resumeMiniAppDownloads:()=>Fn,sendEventToWeb:()=>Sn,syncMiniAppCatalog:()=>tt,uninstallMiniApp:()=>kn,updateMiniApp:()=>$n,uploadToUrl:()=>ct,useMiniAppDownload:()=>Ze,useMiniAppDownloadsPaused:()=>On});module.exports=Xn(Fi);var Be="https://retion-miniapp-platform.vercel.app",Ae=null,Pt=new Set,Rt=e=>{Ae=e,Pt.forEach(t=>t())},I=()=>{if(!Ae)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Ae},Ot=e=>{Pt.add(e),Ae&&e()},J=(...e)=>{Ae!=null&&Ae.debug&&console.log("[miniapp]",...e)};var Tt=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(i=>i.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:r})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>r==null?void 0:r(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Ct=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var w=ue(require("react")),E=require("react-native"),jn=ue(require("react-native-webview"));var Ce=require("react-native");var rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),qe,ot=()=>(qe||(qe=import("react-native-biometrics").then(({default:e})=>rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw qe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),qe);var ee=require("react-native");var It=e=>{var n,i,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},kt=(e,t=()=>!0)=>new Promise((n,i)=>{let r=!1,o=(a,s)=>{r||(r=!0,clearTimeout(c),a?i(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>r?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(ee.Platform.OS==="android"){let s=ee.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=ee.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ee.PermissionsAndroid.check(s);if(!p())return;let y=g||await ee.PermissionsAndroid.check(d);if(!p())return;if(!g&&!y){let l=await ee.PermissionsAndroid.requestMultiple([s,d]);if(!p())return;if(l[s]!==ee.PermissionsAndroid.RESULTS.GRANTED&&l[d]!==ee.PermissionsAndroid.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});var at=require("react-native");var st=20,Lt=20,Bt=/^[a-z][a-z0-9_-]{0,31}$/,Zn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,ei=["low","medium","high"],de=e=>!!e&&typeof e=="object"&&!Array.isArray(e),U=e=>new u("INVALID_PARAMS",e),Oe=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Dt=(e,t)=>{if(e===void 0)return{};if(!de(e)||Object.keys(e).length>Lt||Object.values(e).some(n=>typeof n!="string"))throw U(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Lt} key)`);return e},qt=e=>{var n,i,r,o;if(e!==void 0&&!de(e))throw U("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Bt.test(t.source)))throw U("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Zn.test(c))))throw U("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Oe(t.max_count,1,st))throw U(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${st}`);if(t.max_size!==void 0&&!Oe(t.max_size,1,Number.MAX_SAFE_INTEGER))throw U("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Oe(t.concurrency,1,5))throw U("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:ti(t.process),target:ni(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},ti=e=>{if(e===void 0)return{};if(!de(e))throw U("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!de(n))throw U("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!Oe(n[i],1,1e4))throw U(`process.image.${i} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw U("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!de(n))throw U("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Oe(n.max_duration,1,3600))throw U("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!ei.includes(n.quality))throw U("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},ni=e=>{var n,i,r,o;if(e===void 0)return{target:"host",params:{}};if(!de(e))throw U("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Bt.test(t))throw U("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!de(e.params))throw U("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw U("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw U(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Dt(e.headers,"upload.headers"),form_data:Dt(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(o=e.url_field)!=null?o:"url"}},Vt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},ii=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=Vt(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===i:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},ri=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},Ee,oi=()=>(Ee!=null||(Ee=import("react-native-image-picker").catch(e=>{throw Ee=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ee),Ut=e=>async({accept:t,max_count:n,process:i})=>{var a,s,d,g,y,l,h,T,_;let r=await oi(),o=ri(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=i.image)==null?void 0:a.max_width,maxHeight:(s=i.image)==null?void 0:s.max_height,quality:(g=(d=i.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(y=i.video)==null?void 0:y.quality)!=null?l:"medium",durationLimit:(h=i.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await r.launchCamera({...c,saveToPhotos:!1}):await r.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let b=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(b,(T=p.errorMessage)!=null?T:p.errorCode)}return((_=p.assets)!=null?_:[]).filter(b=>b.uri).map((b,f)=>{var L,G,$;return{uri:b.uri,name:(L=b.fileName)!=null?L:`file_${f+1}`,mime_type:(G=b.type)!=null?G:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!(($=b.type)!=null&&$.startsWith("video/"))||at.Platform.OS==="ios"}})},si={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},ai={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},ci=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let i=t.map(s=>{var d;return(d=si[s])!=null?d:ai[s]}),r=!t.length||i.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(i)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var T,_,b;return{uri:l.uri,name:(T=l.name)!=null?T:`file_${h+1}`,mime_type:(_=l.type)!=null?_:"application/octet-stream",size:(b=l.size)!=null?b:void 0}});if(at.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),y=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=y.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Pe,pi=async e=>(Pe!=null||(Pe=import("@react-native-documents/picker").then(t=>ci(t)).catch(t=>{throw Pe=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Pe)(e)),jt={library:Ut("library"),camera:Ut("camera"),document:pi},Nt={type:"image",label:"\u1EA2nh",accept:["image/*"]},Ft={type:"video",label:"Video",accept:["video/*"]},$t={library:[Nt,Ft,{type:"media",label:"\u1EA2nh + video",accept:["image/*","video/*"]}],camera:[Nt,Ft],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"office",label:"Word / Excel",accept:[".doc",".docx",".xls",".xlsx"]}]},Re,zt=()=>(Re!=null||(Re=import("react-native-compressor").catch(()=>(Re=void 0,null))),Re),Ht=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},li=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),ui={low:640,medium:1280,high:1920},di=async(e,{image:t})=>{var i;if(!t||!li.has(e.mime_type.toLowerCase()))return e;let n=await zt();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(i=t.quality)!=null?i:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Ht(n,r,e.size),processed:!0}}catch{return e}},gi=async(e,{video:t})=>{var i;let n=await zt();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:ui[(i=t==null?void 0:t.quality)!=null?i:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Ht(n,r,e.size),processed:!0}}catch{return e}},mi={image:di,video:gi},fi=(e,t)=>t.split(".").reduce((n,i)=>de(n)?n[i]:void 0,e),ct=({file:e,target:t,onProgress:n,signal:i})=>new Promise((r,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,y])=>a.append(g,y)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();i.addEventListener("abort",s);let d=g=>{i.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,y])=>p.setRequestHeader(g,y)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let y=fi(g,c.url_field);if(typeof y!="string"||!y){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}r({url:y,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Wt=e=>{var i,r;let t={...jt};for(let[o,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[o]=c:delete t[o];let n={url:ct};for(let[o,c]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Jt=e=>{let{sources:t,targets:n}=Wt(e),i=Object.keys(t),r=Object.fromEntries(i.filter(o=>t[o]===jt[o]&&$t[o]).map(o=>[o,$t[o]]));return{sources:i,file_types:r,targets:Object.keys(n),max_count:st}},je=new Map,Kt=(e,t)=>`${e}:${t}`,hi=0,Yt=(e,t)=>{var n;typeof t=="string"&&((n=je.get(Kt(e,t)))==null||n.abort())},we=e=>{for(let[t,n]of je)t.startsWith(`${e}:`)&&n.abort()},Ve=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),yi=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Gt=async(e,t)=>{var a;let{sources:n,targets:i}=Wt(t.config),r=n[e.source];if(!r)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=i[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=Kt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++hi}`);je.set(p,c);try{return await Ai(e,t,r,o,c.signal)}finally{je.delete(p)}},Ai=async(e,{instance_id:t,app_id:n,getContext:i,task_id:r,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var A,S,z;let g={app_id:n!=null?n:"",instance_id:t,context:{...(A=i==null?void 0:i())!=null?A:{}}},y=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw Ve();if(!y.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=y.filter(v=>ii(v,e.accept)?!0:(l.push({name:v.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${v.mime_type||Vt(v.name)}`}),!1)),T=h.map(()=>0),_=h.map(v=>{var D;return(D=v.size)!=null?D:0}),b=0,f=0,L=(v=!1)=>{if(!c||!r)return;let D=Date.now();if(!v&&D-f<200)return;f=D;let ie=_.reduce((C,H)=>C+H,0),B=T.reduce((C,H)=>C+H,0);c("upload.progress",{task_id:r,loaded:B,total:ie,percent:ie?Math.min(100,Math.round(B/ie*100)):0,done_count:b,count:h.length})},G=[],$=0,Se=async()=>{var v,D,ie;for(;$<h.length;){let B=$++,C=h[B];try{if(d.aborted)throw Ve();let H=C.mime_type.startsWith("image/")?"image":C.mime_type.startsWith("video/")?"video":void 0,pe=H&&!C.processed?(D=(v=o==null?void 0:o.processors)==null?void 0:v[H])!=null?D:mi[H]:void 0;if(pe&&(C=await pe(C,e.process),_[B]=(ie=C.size)!=null?ie:_[B],d.aborted))throw Ve();if(e.max_size&&C.size&&C.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${C.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let he=(Ne,Fe)=>{T[B]=Ne,Fe&&(_[B]=Fe),L()},re=await s({file:C,target:e.target,onProgress:he,signal:d,caller:g});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:nt,...oe}=re;G[B]={url:nt,name:C.name,mime_type:C.mime_type,size:C.size,width:C.width,height:C.height,duration:C.duration,...Object.keys(oe).length?{response:"response"in oe?oe.response:oe}:{}},T[B]=_[B]}catch(H){l.push(yi(h[B].name,H))}finally{b++,L(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},Se)),d.aborted)throw Ve();let ce=G.filter(v=>!!v);if(!ce.length){let v=l[0];throw new u((S=v==null?void 0:v.code)!=null?S:"UPLOAD_FAILED",(z=v==null?void 0:v.message)!=null?z:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:l}};var Me=require("react-native");var K,Qt=()=>Me.Platform.OS==="android"&&!!(K!=null&&K.requesting_permission),wi=1500,Mi=()=>new Promise(e=>{if(Me.Platform.OS!=="android"||Me.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),i.remove(),e()},n=setTimeout(t,wi),i=Me.AppState.addEventListener("change",r=>{r==="active"&&t()})}),pt=e=>{var t;if(K===e&&(K=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Me.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Xt=async(e,t,n,i=()=>!0)=>{var o,c,p,a,s;if(K)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};K=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(r.native=g,r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await g.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await Mi(),r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(g.addListener("result",l=>{var h,T;K!==r||r.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(T=(h=l.results[0])==null?void 0:h.transcript)!=null?T:""})}),g.addListener("error",l=>{K===r&&!r.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{K===r&&(pt(r),n("speech.end"))})),r.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw pt(r),d}},Zt=e=>{let t=K;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},te=e=>{let t=K;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{pt(t)}};var He=1,u=class extends Error{constructor(n,i){super(i);this.code=n}},en=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===He&&typeof t.method=="string"?t:null}catch{return null}},Ie=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,tn=(e,t)=>Ie({id:e,result:t}),nn=(e,t)=>Ie({id:e,error:{code:t.code,message:t.message}}),rn=(e,t)=>Ie({event:e,data:t}),ut=e=>Ie({event:"context",data:e});var on=()=>`(function () {
|
|
2
2
|
var post = function (level, args) {
|
|
3
3
|
try {
|
|
4
4
|
var parts = [];
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
|
|
20
20
|
// Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
|
|
21
21
|
post('info', ['[page] ' + location.pathname + location.hash]);
|
|
22
|
-
})(); true;`,
|
|
22
|
+
})(); true;`,sn=()=>`(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; }
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
var el = e.target === document ? document.documentElement : e.target;
|
|
39
39
|
if (el && el.scrollTop > 0) { report(false); }
|
|
40
40
|
}, { capture: true, passive: true });
|
|
41
|
-
})(); true;`,
|
|
41
|
+
})(); true;`,an=()=>`(function () {
|
|
42
42
|
if (window.__retionSafeAreaFrozen) { return; }
|
|
43
43
|
window.__retionSafeAreaFrozen = true;
|
|
44
44
|
var max = {};
|
|
@@ -59,8 +59,8 @@
|
|
|
59
59
|
},
|
|
60
60
|
});
|
|
61
61
|
};
|
|
62
|
-
})(); true;`,
|
|
63
|
-
${ut(e)}`},
|
|
62
|
+
})(); true;`,cn=e=>Ie({event:e}),pn=(e,t)=>{let n=ln(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
|
|
63
|
+
${ut(e)}`},ln=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),un=(e,t={})=>{let n=ln(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${He} };
|
|
64
64
|
window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
|
|
65
65
|
${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
|
|
66
|
-
true;`},cn={partner:"partner_token",chatbox:"chatbox_token"},pn=(e,t)=>{let n={...e};for(let r of Object.values(cn))t.includes(r)||delete n[r];return n},lt=new Set,Te=async(e,t)=>{if(lt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);lt.add(e);try{return await t()}finally{lt.delete(e)}},wr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ze=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},ln=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:i,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var T,_,b,f,L,G,$,Se,ce;let A=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let w=kt(t);return Te(e,()=>It(w,g))}case"speech.start":{if(!d)throw h();let w={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");w.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new u("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);w[S]=t[S]}return Kt(a,w,d,g)}case"speech.stop":return Yt(a);case"uploadFiles":{let{task_id:w,...S}=t!=null?t:{};if(w!==void 0&&(typeof w!="string"||!w))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Wt(Ft(S),{instance_id:a,app_id:p,getContext:i,task_id:w,config:s==null?void 0:s.upload,emit:d,exclusivePick:z=>Te("uploadFiles.pick",z)})}case"uploadFiles.cancel":Ht(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return jt(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await ot()).getAvailability();case"authenticateBiometric":{let w=ze(t==null?void 0:t.reason,"reason").trim();if(!w||w.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Te(e,async()=>{var v;return((v=s==null?void 0:s.biometrics)!=null?v:await ot()).authenticate({reason:w,cancelButtonText:S})})}case"requestPayment":{let w=A==null?void 0:A.requestPayment;if(!w)throw h();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:ze(t==null?void 0:t.currency,"currency")};return Te(e,()=>w(z,l))}case"printImage":{let w=A==null?void 0:A.printImage;if(!w)throw h();let S=ze(t==null?void 0:t.image,"image");await Te(e,()=>w({image:S},l));return}case"openScreen":if(!(A!=null&&A.openScreen))throw h();await A.openScreen({screen:ze(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let w=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(w))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(w):Ce.Linking.openURL(w));return}case"openLink":{let w=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(w)||/^(javascript|file|data|about|blob):/i.test(w))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(w):Ce.Linking.openURL(w))}catch(S){throw new u("NOT_SUPPORTED",String((L=(f=S==null?void 0:S.message)!=null?f:S)!=null?L:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":($=s==null?void 0:s.showToast)==null||$.call(s,String((G=t==null?void 0:t.message)!=null?G:""));return;case"haptic":{let w=wr.has(t==null?void 0:t.type)?t.type:"selection";(Se=s==null?void 0:s.haptic)==null||Se.call(s,w);return}case"getSystemInfo":return{platform:Ce.Platform.OS==="ios"?"ios":"android",appVersion:(ce=s==null?void 0:s.app_version)!=null?ce:"",theme:o?"dark":"light"};case"getAccessToken":{let w=n().access_token;if(!w)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}case"getToken":{let w=t==null?void 0:t.type;if(w==="access"){let v=n().access_token;if(!v)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return v}if(w!=="partner"&&w!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(w)}`);let S=cn[w];if(!r().includes(S))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=w==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let w=n().user;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return w}case"getPageInfo":{let w=n().page;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return w}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var gt=e=>`bundle:${e}`,mt=()=>`${k().file_system.document_dir}/miniapps`,ft=mt,ht=(e,t,n="index.html",r=!1,i=[])=>{let o=`${ft()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:i}},dt=e=>{var t;k().storage.setString(gt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},yr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,R=e=>{let t=k().storage.getString(gt(e));if(!t)return null;try{let{version:n,entry:r,context_update:i,permissions:o}=JSON.parse(t);return ht(e,n,r,!!i,Array.isArray(o)?o:[])}catch{return null}},se=e=>k().file_system.exists(e.entry_uri.replace("file://","")),At=async e=>{let t=R(e.app_id);return(t==null?void 0:t.version)===e.version&&await se(t)},dn=async(e,t)=>{let n=k().file_system,r=`${ft()}/${e}`,i=await n.listDir(r).catch(()=>[]);await Promise.all(i.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},gn=async e=>{var t;await((t=Le[e])==null?void 0:t.catch(()=>{})),k().storage.setString(gt(e),""),await k().file_system.remove(`${ft()}/${e}`).catch(()=>{})},_e=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Le={},mn=(e,t)=>{var o;let r=((o=Le[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return Le[e]=i,i.then(()=>{Le[e]===i&&delete Le[e]}),r},Mr=(e,t)=>{var i,o;let n=e.split(".").map(c=>parseInt(c,10)||0),r=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,r.length);c++){let p=((i=n[c])!=null?i:0)-((o=r[c])!=null?o:0);if(p)return p}return 0},fn=({manifest:e,zip_path:t})=>mn(e.app_id,async()=>{var o;let n=k().file_system,r=R(e.app_id);if(r&&Mr(r.version,e.version)>=0&&await se(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let i=ht(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(i.dir).catch(()=>{}),await n.mkdir(i.dir),await n.unzip(t,i.dir),dt(e),J("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),dn(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),i}),wt=(e,{base_url:t,onProgress:n}={})=>{let r=k().file_system,i=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new _e},a=async()=>{var g;p();let s=R(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return dt(e),R(e.app_id);p();let d=r.download({url:t?yr(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(A,l)=>{var T;let h=l>0?l:(T=e.size)!=null?T:0;h>0&&(n==null||n(Math.min(1,A/h)))}});i=d;try{let{status:A}=await d.promise;if(p(),A!==200)throw new Error(`bundle ${A}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else J("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ht(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(l.dir).catch(()=>{}),await r.mkdir(l.dir),await r.unzip(c,l.dir),dt(e),dn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(A){throw o?new _e:A}finally{i=null,r.remove(c).catch(()=>{})}};return{promise:mn(e.app_id,a),cancel:()=>{o=!0,i==null||i.cancel()}}},Ie={},vr=__DEV__?0:60*1e3,un={},hn=(e,t)=>{var r,i;let n=R(e);return n&&Date.now()-((r=un[t])!=null?r:0)<vr?Promise.resolve(n):((i=Ie[e])!=null||(Ie[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await wt(c,{base_url:t}).promise;return un[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),R(e))).finally(()=>{Ie[e]=void 0})),Ie[e])};var We=new Map,An=(e,t)=>(We.set(e,t),()=>{We.get(e)===t&&We.delete(e)}),wn=(e,t)=>{let n=We.get(e);return n?n(t):!1};var Je=require("react"),Ke=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let i=typeof r=="function"?r(t):r;t={...t,...i},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},ne=(e,t,n=Object.is)=>{let r=(0,Je.useRef)(null),i=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return r.current={state:o,selector:t,value:a},a};return(0,Je.useSyncExternalStore)(e.subscribe,i)};var V=Ke({active_key:null,instances:{}}),yn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:i={}},o)=>{var p;let c=(p=k().keep_alive)==null?void 0:p.max_webviews;V.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:i,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(A=>A!==s).sort((A,l)=>d[A].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(A=>{delete d[A]}),o?{active_key:s,instances:d}:{instances:d}})},Mn=e=>yn(e,!0),vn=e=>yn(e,!1),be=()=>V.setState({active_key:null}),Ye=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Sn="catalog",Sr="paused_apps",_r="removed_apps",br=10*1e3,xr=2,Er=3e3,Pr=()=>{var e;try{return JSON.parse((e=k().storage.getString(Sn))!=null?e:"{}")}catch{return{}}},P=Ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),_n=e=>{var t;return!!((t=k().manual_update)!=null&&t.includes(e))},Xe=new Set,bn=e=>{let t=new Set,n=()=>k().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let i=JSON.parse((r=k().storage.getString(e))!=null?r:"[]");Array.isArray(i)&&i.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Z=bn(Sr),fe=bn(_r);Ot(()=>{Z.load(),fe.load();let e=Pr(),t={};Object.keys(e).filter(n=>!fe.has(n)).forEach(n=>{let r=R(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:Z.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),P.setState({catalog:e,downloads:t})});var Ze=e=>ne(P,t=>e?t.downloads[e]:void 0),xn=()=>ne(P,e=>e.pause_reasons.length>0),X=(...e)=>J("queue",...e),U=[],ae={},x=null,Ge=new Set,ve={},yt=new Set,ge=e=>{yt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},En=e=>(yt.add(e),()=>{yt.delete(e)}),Pn=()=>P.getState().downloads,j=(e,t)=>{let n=!!R(e),r=P.getState().downloads[e],i=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...i?{status:i}:{},has_local:n};P.setState(c=>({downloads:{...c.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?ge({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&ge({type:"progress",app_id:e,progress:o.progress,version:o.version})},Qe=(e,t)=>{var n;(n=ve[e])==null||n.forEach(r=>r(t)),delete ve[e]},Rr=()=>P.getState().pause_reasons.length>0,me=e=>{var p;if(x)return;let t=e?U.indexOf(e):Rr()?-1:U.findIndex(a=>!Z.has(a));if(t<0||t>=U.length)return;let[n]=U.splice(t,1),r=P.getState().catalog[n];if(!r){Qe(n,R(n)),me();return}let i=Date.now();ae[n]=((p=ae[n])!=null?p:0)+1,j(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=wt(r,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,j(n,{progress:s/100,version:r.version}))}});x={app_id:n,handle:c,forced:!!e},X("start",n,r.version,e?"(forced)":""),c.promise.then(a=>{X("installed",n,r.version,`${Date.now()-i}ms`),j(n,{status:"installed",progress:1,version:r.version}),Qe(n,a)}).catch(a=>{var d;if(a instanceof _e){if(Ge.has(n))return;X("paused",n),ae[n]-=1,U.unshift(n),j(n,{status:Z.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),ae[n]<xr){j(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;U.includes(n)||(x==null?void 0:x.app_id)===n||(U.push(n),me((g=ve[n])!=null&&g.length?n:void 0))},Er);return}j(n,{status:"failed",progress:0,version:r.version,error:s}),Qe(n,R(n))}).finally(()=>{x=null;let a=U.find(s=>{var d;return(d=ve[s])==null?void 0:d.length});me(a)})},et=(e,{front:t=!1}={})=>{if((x==null?void 0:x.app_id)===e)return;let n=U.indexOf(e);if(n>=0){if(!t)return;U.splice(n,1)}t?U.unshift(e):U.push(e)},Or=async e=>{let{host_id:t,client_token:n}=k(),r=new AbortController,i=setTimeout(()=>r.abort(),br);try{let o=`${Be}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(i)}},De=null,tt=()=>(De!=null||(De=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(k().channels.map(Or)),r={};[...n].reverse().flat().forEach(a=>{r[a.app_id]=a});let i=Object.keys(P.getState().catalog).filter(a=>!r[a]);k().storage.setString(Sn,JSON.stringify(r)),P.setState({catalog:r}),await Promise.all(i.map(a=>Rn(a,{by_user:!1}))),i.forEach(a=>fe.delete(a));let o=Object.keys(r).filter(a=>!fe.has(a)),c=[],p={};for(let a of o.map(s=>r[s])){if(await At(a)){j(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=R(a.app_id);if(_n(a.app_id)&&!Xe.has(a.app_id)&&s&&await se(s)){j(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return P.setState({updates:p}),c.forEach(a=>{ae[a.app_id]=0,j(a.app_id,{status:Z.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),et(a.app_id)}),X("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",i,`${Date.now()-e}ms`),ge({type:"sync_complete",app_ids:o,removed:i}),Object.values(p).forEach(a=>ge({type:"update_available",...a})),me(),{ok:!0,app_ids:o,removed:i}}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),ge({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{De=null}})()),De),Rn=async(e,{by_user:t})=>{var i,o,c,p;if(t&&fe.add(e),Ge.has(e))return;Ge.add(e),Z.delete(e);let n=U.indexOf(e);n>=0&&U.splice(n,1),(x==null?void 0:x.app_id)===e&&x.handle.cancel();let r=(p=(c=(i=P.getState().downloads[e])==null?void 0:i.version)!=null?c:(o=R(e))==null?void 0:o.version)!=null?p:"";j(e,{status:"uninstalling",progress:0,version:r}),await gn(e),Ye(e),P.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete ae[e],Ge.delete(e),Qe(e,null),X("uninstalled",e,t?"(user)":"(not in list)"),ge({type:"uninstalled",app_id:e})},On=e=>Rn(e,{by_user:!0}),Tn=e=>{let t=xe(e);return t?(fe.delete(e),(x==null?void 0:x.app_id)===e||U.includes(e)||(ae[e]=0,j(e,{status:Z.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),et(e),me(),X("restore",e)),!0):!1},Cn=e=>{if(Z.has(e))return;if(Z.add(e),X("pause app",e),(x==null?void 0:x.app_id)===e&&!x.forced){x.handle.cancel();return}let t=P.getState().downloads[e];U.includes(e)&&t&&j(e,{status:"paused",progress:0,version:t.version})},kn=e=>{if(!Z.delete(e))return;X("resume app",e);let t=P.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!U.includes(e)&&xe(e)&&(ae[e]=0,et(e)),U.includes(e)&&t&&j(e,{status:"queued",progress:0,version:t.version}),me()},In=e=>{let{pause_reasons:t}=P.getState();t.includes(e)||(P.setState({pause_reasons:[...t,e]}),X("pause",e),t.length===0&&ge({type:"pause_change",paused:!0,reasons:[e]}),x&&!x.forced&&x.handle.cancel())},Ln=e=>{let{pause_reasons:t}=P.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);P.setState({pause_reasons:n}),X("resume",e),n.length===0&&ge({type:"pause_change",paused:!1,reasons:n}),me()},Mt=e=>P.getState().updates[e],Dn=async e=>{var n,r;let t=Mt(e);Xe.add(e);try{let i=await Ne(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=xe(e))==null?void 0:n.version;return!i||!o||i.version!==o?!1:(P.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),X("updated",e,t==null?void 0:t.current_version,"\u2192",i.version),!0)}finally{Xe.delete(e)}},Nn=()=>Object.values(P.getState().catalog).map(e=>({...e,installed:!!R(e.app_id),removed_by_user:fe.has(e.app_id)})),xe=e=>P.getState().catalog[e],Ne=async e=>{let t=xe(e);if(!t)return;if(Z.delete(e),fe.delete(e),await At(t))return R(e);let n=R(e);if(_n(e)&&!Xe.has(e)&&n&&await se(n))return n;let r=new Promise(i=>{var o;((o=ve[e])!=null?o:ve[e]=[]).push(i)});return(x==null?void 0:x.app_id)===e?x.forced=!0:(ae[e]=0,et(e,{front:!0}),x&&!x.forced?x.handle.cancel():me(e)),r};var O=require("react/jsx-runtime"),vt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Un=0,Tr=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Cr=y.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:i,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=(0,y.useRef)(null),A=(0,y.useRef)(!1),l=ne(V,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,T=l==null?void 0:l.app.manifest_url,_=l==null?void 0:l.context,b=l==null?void 0:l.url_params,[f,L]=(0,y.useState)(()=>h?R(h):null),[G,$]=(0,y.useState)(!1),[Se,ce]=(0,y.useState)(0),[w,S]=(0,y.useState)(0),[z,v]=(0,y.useState)(!1),D=(0,y.useRef)(null),re=m=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,v(!0)},m)};(0,y.useEffect)(()=>()=>{D.current&&clearTimeout(D.current)},[]),(0,y.useEffect)(()=>{if(!h||!t&&f)return;let m=!0;return $(!1),(async()=>{let M=R(h),q=M?await se(M):!1;if(!m||(L(q?Q=>!Q||Q.version!==M.version||Q.permissions.join(",")!==M.permissions.join(",")?M:Q:null),__DEV__&&Date.now()-Un>1e4&&(Un=Date.now(),await tt()),!m))return;let le=await Ne(h),Ae=le!==void 0?le:T?await hn(h,T):R(h);if(m){if(!Ae){$(!0);return}L(Q=>Q!=null?Q:Ae)}})(),()=>{m=!1}},[t,h,T,Se]),(0,y.useEffect)(()=>An(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let B=ne(P,m=>{let M=h?m.downloads[h]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});(0,y.useEffect)(()=>{if(t||!h||!f)return;let m=R(h);if(!m||m.version===f.version)return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),L(m))}),()=>{M=!1}},[t,h,B,f==null?void 0:f.version]);let C=ne(P,m=>{var M;return h&&(M=m.apply_ticks[h])!=null?M:0});(0,y.useEffect)(()=>{if(!C||!h)return;let m=R(h);if(!m||m.version===(f==null?void 0:f.version))return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),v(!1),L(m))}),()=>{M=!1}},[C]),(0,y.useEffect)(()=>{var q;let m=(q=k().keep_alive)==null?void 0:q.idle_close_ms;if(t||!m||m<=0)return;let M=setTimeout(()=>{Ye(e)},m);return()=>clearTimeout(M)},[t,e]),(0,y.useEffect)(()=>{i>0&&($(!1),v(!1),S(m=>m+1),ce(m=>m+1))},[i]);let H=(0,y.useRef)(t);(0,y.useEffect)(()=>{var m;H.current!==t&&(H.current=t,A.current&&((m=g.current)==null||m.injectJavaScript(rn(t?"resumed":"paused"))))},[t]);let pe=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${w}`,he=(0,y.useMemo)(()=>JSON.stringify([_!=null?_:{},b!=null?b:{}]),[_,b]),ie=(0,y.useMemo)(()=>{var m;return pn(b!=null?b:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[he,f==null?void 0:f.permissions]),nt=(0,y.useMemo)(()=>an(_!=null?_:{},ie)+tn()+(E.Platform.OS==="android"?nn():"")+(k().debug?en():""),[ie]),oe=(0,y.useRef)(null),Ue=(0,y.useRef)(null);(0,y.useEffect)(()=>{var M,q,le;if(!f)return;if(Ue.current!==pe){Ue.current=pe,oe.current=he;return}if(oe.current===he)return;let m=((q=JSON.parse((M=oe.current)!=null?M:"[]")[0])!=null?q:{}).org_id;if(oe.current=he,m===(_==null?void 0:_.org_id)&&A.current){v(!1),re(1500),(le=g.current)==null||le.injectJavaScript(on(_!=null?_:{},ie));return}v(!1),S(Ae=>Ae+1)},[he,f,pe]),(0,y.useEffect)(()=>(t||(te(e),ye(e)),()=>{te(e),ye(e)}),[t,e,pe,i]),(0,y.useEffect)(()=>{let m=E.AppState.addEventListener("change",M=>{M==="background"&&!Jt()&&te(e)});return()=>m.remove()},[e]);let Fe=(0,y.useCallback)(async m=>{var q,le,Ae,Q,rt;let M=Gt(m.nativeEvent.data);if(!M){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(I=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,I)})}catch(I){console.warn("[miniapp] onWebEvent l\u1ED7i",h,I)}return}if(M.method==="log"){let{level:I,text:F}=M;J(`web:${e}`,I!=null?I:"log",F!=null?F:"");return}if(M.method==="pong"){D.current||v(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){D.current&&clearTimeout(D.current),D.current=null,v(!0);return}if(M.method==="ready"){A.current=!0,v(!0);let I=(q=V.getState().instances[e])==null?void 0:q.context;I&&((le=g.current)==null||le.injectJavaScript(ut(I)));return}try{let I=await ln(M,{getHostData:()=>{var F,W;return(W=(F=V.getState().instances[e])==null?void 0:F.host_data)!=null?W:{}},getPermissions:()=>{var F,W;return h?(W=(F=R(h))==null?void 0:F.permissions)!=null?W:[]:[]},getContext:()=>{var F,W;return(W=(F=V.getState().instances[e])==null?void 0:F.context)!=null?W:{}},is_dark:r,close:be,app_id:h!=null?h:"",instance_id:e,options:p,emit:(F,W)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(Zt(F,W))},isActive:()=>V.getState().active_key===e&&E.AppState.currentState!=="background"});M.id&&((Ae=g.current)==null||Ae.injectJavaScript(Qt(M.id,I)))}catch(I){if(!M.id)return;let F=I==null?void 0:I.code,W=I instanceof u?I:new u(typeof F=="string"?F:"HOST_ERROR",String((Q=I==null?void 0:I.message)!=null?Q:I));(rt=g.current)==null||rt.injectJavaScript(Xt(M.id,W))}},[e,r,h,o,p]),qn=(0,y.useCallback)(()=>{$(!1),S(m=>m+1),ce(m=>m+1)},[]);return(0,O.jsxs)(E.View,{style:[E.StyleSheet.absoluteFill,a&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&Y.behind],pointerEvents:t?"auto":"none",children:[f?(0,O.jsx)($n.default,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?mt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:nt,onMessage:Fe,bounces:!1,overScrollMode:"never",onLoadStart:m=>{te(e),ye(e),J(`webview:${e}`,"load start",vt(m.nativeEvent.url)),A.current=!1,v(!1)},onError:m=>{te(e),ye(e),J(`webview:${e}`,"load error",vt(m.nativeEvent.url),m.nativeEvent.description),$(!0),v(!1)},onLoadEnd:m=>{let M=m.nativeEvent.url;J(`webview:${e}`,"load end",vt(M)),h&&(d==null||d({app_id:h,instance_id:e,url:M})),re(1500)},onContentProcessDidTerminate:()=>{te(e),ye(e),A.current=!1,v(!1),S(m=>m+1)},onRenderProcessGone:()=>(te(e),ye(e),A.current=!1,v(!1),S(m=>m+1),!0),style:Y.webview},pe):null,l&&(0,O.jsx)(Ir,{visible:!f||!z,interactive:G,children:(0,O.jsx)(kr,{splash:c,app:l.app,is_dark:r,error:G,has_bundle:!!f,retry:qn})})]})}),kr=y.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:i,retry:o})=>{let c=e,p=Ze(t.app_id),a=r?"error":!i&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,O.jsx)(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Ir=({visible:e,interactive:t,children:n})=>{let r=(0,y.useRef)(new E.Animated.Value(e?1:0)).current,[i,o]=(0,y.useState)(e);return(0,y.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let c=E.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,r]),i?(0,O.jsx)(E.Animated.View,{style:[E.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},St=({app:e,is_dark:t,status:n,progress:r,retry:i})=>{let o=t?"#FAFAFA":"#18181B";return(0,O.jsxs)(E.View,{style:[Y.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,O.jsx)(E.View,{style:[Y.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,O.jsx)(E.Image,{source:{uri:e.icon},style:Y.splash_icon_image}):(0,O.jsx)(E.Text,{style:Y.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,O.jsx)(E.Text,{style:[Y.splash_name,{color:o}],children:e.name}),n==="error"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.Text,{style:Y.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,O.jsx)(E.TouchableOpacity,{activeOpacity:.7,style:[Y.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:i,children:(0,O.jsx)(E.Text,{style:[Y.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.ActivityIndicator,{style:Y.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,O.jsxs)(E.Text,{style:Y.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Fn=(e,t)=>{let n=(0,y.useRef)(t),r=(0,y.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.`))},Lr=({container:e,splash:t=St,is_dark:n=!1,bridge:r,close_on_back:i=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Fn("container",e),Fn("splash",t);let a=e,s=ne(V,f=>f.active_key),d=(0,y.useRef)(s);s&&(d.current=s);let g=ne(V,f=>Object.keys(f.instances).join("|")),A=ne(V,f=>{var L;return f.active_key?(L=f.instances[f.active_key])==null?void 0:L.app.name:void 0}),l=(0,y.useMemo)(()=>g?g.split("|"):[],[g]),[h,T]=(0,y.useState)({}),_=(0,y.useRef)(Tr()).current;(0,y.useEffect)(()=>{if(!s||!i)return;let f=E.BackHandler.addEventListener("hardwareBackPress",()=>(be(),!0));return()=>f.remove()},[s,i]);let b=(0,y.useCallback)(()=>{let f=V.getState().active_key;f&&T(L=>({...L,[f]:(L[f]||0)+1}))},[]);return l.length?(0,O.jsx)(a,{visible:!!s,title:A!=null?A:"",is_dark:n,close:be,reload:b,subscribeWebAtTop:_.subscribe,children:l.map(f=>(0,O.jsx)(Cr,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:_,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},Y=E.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Bn=y.default.memo(Lr);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
|
|
66
|
+
true;`},dn={partner:"partner_token",chatbox:"chatbox_token"},gn=(e,t)=>{let n={...e};for(let i of Object.values(dn))t.includes(i)||delete n[i];return n},lt=new Set,Te=async(e,t)=>{if(lt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);lt.add(e);try{return await t()}finally{lt.delete(e)}},vi=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),ze=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},mn=async({method:e,params:t},{getHostData:n,getPermissions:i,getContext:r,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var T,_,b,f,L,G,$,Se,ce;let y=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let A=It(t);return Te(e,()=>kt(A,g))}case"speech.start":{if(!d)throw h();let A={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");A.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new u("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);A[S]=t[S]}return Xt(a,A,d,g)}case"speech.stop":return Zt(a);case"uploadFiles":{let{task_id:A,...S}=t!=null?t:{};if(A!==void 0&&(typeof A!="string"||!A))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Gt(qt(S),{instance_id:a,app_id:p,getContext:r,task_id:A,config:s==null?void 0:s.upload,emit:d,exclusivePick:z=>Te("uploadFiles.pick",z)})}case"uploadFiles.cancel":Yt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Jt(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await ot()).getAvailability();case"authenticateBiometric":{let A=ze(t==null?void 0:t.reason,"reason").trim();if(!A||A.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Te(e,async()=>{var v;return((v=s==null?void 0:s.biometrics)!=null?v:await ot()).authenticate({reason:A,cancelButtonText:S})})}case"requestPayment":{let A=y==null?void 0:y.requestPayment;if(!A)throw h();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:ze(t==null?void 0:t.currency,"currency")};return Te(e,()=>A(z,l))}case"printImage":{let A=y==null?void 0:y.printImage;if(!A)throw h();let S=ze(t==null?void 0:t.image,"image");await Te(e,()=>A({image:S},l));return}case"openScreen":if(!(y!=null&&y.openScreen))throw h();await y.openScreen({screen:ze(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let A=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(A))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(A):Ce.Linking.openURL(A));return}case"openLink":{let A=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(A)||/^(javascript|file|data|about|blob):/i.test(A))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(A):Ce.Linking.openURL(A))}catch(S){throw new u("NOT_SUPPORTED",String((L=(f=S==null?void 0:S.message)!=null?f:S)!=null?L:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":($=s==null?void 0:s.showToast)==null||$.call(s,String((G=t==null?void 0:t.message)!=null?G:""));return;case"haptic":{let A=vi.has(t==null?void 0:t.type)?t.type:"selection";(Se=s==null?void 0:s.haptic)==null||Se.call(s,A);return}case"getSystemInfo":return{platform:Ce.Platform.OS==="ios"?"ios":"android",appVersion:(ce=s==null?void 0:s.app_version)!=null?ce:"",theme:o?"dark":"light"};case"getAccessToken":{let A=n().access_token;if(!A)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return A}case"getToken":{let A=t==null?void 0:t.type;if(A==="access"){let v=n().access_token;if(!v)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return v}if(A!=="partner"&&A!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(A)}`);let S=dn[A];if(!i().includes(S))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=A==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let A=n().user;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return A}case"getPageInfo":{let A=n().page;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return A}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var gt=e=>`bundle:${e}`,mt=()=>`${I().file_system.document_dir}/miniapps`,ft=mt,ht=(e,t,n="index.html",i=!1,r=[])=>{let o=`${ft()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:i,permissions:r}},dt=e=>{var t;I().storage.setString(gt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Si=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,R=e=>{let t=I().storage.getString(gt(e));if(!t)return null;try{let{version:n,entry:i,context_update:r,permissions:o}=JSON.parse(t);return ht(e,n,i,!!r,Array.isArray(o)?o:[])}catch{return null}},se=e=>I().file_system.exists(e.entry_uri.replace("file://","")),yt=async e=>{let t=R(e.app_id);return(t==null?void 0:t.version)===e.version&&await se(t)},hn=async(e,t)=>{let n=I().file_system,i=`${ft()}/${e}`,r=await n.listDir(i).catch(()=>[]);await Promise.all(r.filter(o=>!t.includes(o)).map(o=>n.remove(`${i}/${o}`).catch(()=>{})))},yn=async e=>{var t;await((t=Le[e])==null?void 0:t.catch(()=>{})),I().storage.setString(gt(e),""),await I().file_system.remove(`${ft()}/${e}`).catch(()=>{})},_e=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Le={},An=(e,t)=>{var o;let i=((o=Le[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),r=i.catch(()=>{});return Le[e]=r,r.then(()=>{Le[e]===r&&delete Le[e]}),i},_i=(e,t)=>{var r,o;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let p=((r=n[c])!=null?r:0)-((o=i[c])!=null?o:0);if(p)return p}return 0},wn=({manifest:e,zip_path:t})=>An(e.app_id,async()=>{var o;let n=I().file_system,i=R(e.app_id);if(i&&_i(i.version,e.version)>=0&&await se(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=ht(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),dt(e),J("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),hn(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),r}),At=(e,{base_url:t,onProgress:n}={})=>{let i=I().file_system,r=null,o=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new _e},a=async()=>{var g;p();let s=R(e.app_id);if((s==null?void 0:s.version)===e.version&&await i.exists(s.dir))return dt(e),R(e.app_id);p();let d=i.download({url:t?Si(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(y,l)=>{var T;let h=l>0?l:(T=e.size)!=null?T:0;h>0&&(n==null||n(Math.min(1,y/h)))}});r=d;try{let{status:y}=await d.promise;if(p(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else J("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ht(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await i.remove(l.dir).catch(()=>{}),await i.mkdir(l.dir),await i.unzip(c,l.dir),dt(e),hn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(y){throw o?new _e:y}finally{r=null,i.remove(c).catch(()=>{})}};return{promise:An(e.app_id,a),cancel:()=>{o=!0,r==null||r.cancel()}}},ke={},bi=__DEV__?0:60*1e3,fn={},Mn=(e,t)=>{var i,r;let n=R(e);return n&&Date.now()-((i=fn[t])!=null?i:0)<bi?Promise.resolve(n):((r=ke[e])!=null||(ke[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await At(c,{base_url:t}).promise;return fn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),R(e))).finally(()=>{ke[e]=void 0})),ke[e])};var We=new Map,vn=(e,t)=>(We.set(e,t),()=>{We.get(e)===t&&We.delete(e)}),Sn=(e,t)=>{let n=We.get(e);return n?n(t):!1};var Je=require("react"),Ke=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let r=typeof i=="function"?i(t):i;t={...t,...r},n.forEach(o=>o())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},ne=(e,t,n=Object.is)=>{let i=(0,Je.useRef)(null),r=()=>{let o=e.getState(),c=i.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return i.current={state:o,selector:t,value:a},a};return(0,Je.useSyncExternalStore)(e.subscribe,r)};var V=Ke({active_key:null,instances:{}}),_n=({app:e,instance_id:t,context:n={},url_params:i={},host_data:r={}},o)=>{var p;let c=(p=I().keep_alive)==null?void 0:p.max_webviews;V.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:i,host_data:r,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(y=>y!==s).sort((y,l)=>d[y].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(y=>{delete d[y]}),o?{active_key:s,instances:d}:{instances:d}})},bn=e=>_n(e,!0),xn=e=>_n(e,!1),be=()=>V.setState({active_key:null}),Ye=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var En="catalog",xi="paused_apps",Ei="removed_apps",Pi=10*1e3,Ri=2,Oi=3e3,Ti=()=>{var e;try{return JSON.parse((e=I().storage.getString(En))!=null?e:"{}")}catch{return{}}},P=Ke({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Pn=e=>{var t;return!!((t=I().manual_update)!=null&&t.includes(e))},Xe=new Set,Rn=e=>{let t=new Set,n=()=>I().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let r=JSON.parse((i=I().storage.getString(e))!=null?i:"[]");Array.isArray(r)&&r.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Z=Rn(xi),fe=Rn(Ei);Ot(()=>{Z.load(),fe.load();let e=Ti(),t={};Object.keys(e).filter(n=>!fe.has(n)).forEach(n=>{let i=R(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:Z.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),P.setState({catalog:e,downloads:t})});var Ze=e=>ne(P,t=>e?t.downloads[e]:void 0),On=()=>ne(P,e=>e.pause_reasons.length>0),X=(...e)=>J("queue",...e),N=[],ae={},x=null,Ge=new Set,ve={},wt=new Set,ge=e=>{wt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Tn=e=>(wt.add(e),()=>{wt.delete(e)}),Cn=()=>P.getState().downloads,j=(e,t)=>{let n=!!R(e),i=P.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,o={...i!=null?i:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};P.setState(c=>({downloads:{...c.downloads,[e]:o}})),(i==null?void 0:i.status)!==o.status||(i==null?void 0:i.version)!==o.version||(i==null?void 0:i.has_local)!==o.has_local?ge({type:"status_change",app_id:e,state:o}):i.progress!==o.progress&&ge({type:"progress",app_id:e,progress:o.progress,version:o.version})},Qe=(e,t)=>{var n;(n=ve[e])==null||n.forEach(i=>i(t)),delete ve[e]},Ci=()=>P.getState().pause_reasons.length>0,me=e=>{var p;if(x)return;let t=e?N.indexOf(e):Ci()?-1:N.findIndex(a=>!Z.has(a));if(t<0||t>=N.length)return;let[n]=N.splice(t,1),i=P.getState().catalog[n];if(!i){Qe(n,R(n)),me();return}let r=Date.now();ae[n]=((p=ae[n])!=null?p:0)+1,j(n,{status:"downloading",progress:0,version:i.version,error:void 0});let o=0,c=At(i,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,j(n,{progress:s/100,version:i.version}))}});x={app_id:n,handle:c,forced:!!e},X("start",n,i.version,e?"(forced)":""),c.promise.then(a=>{X("installed",n,i.version,`${Date.now()-r}ms`),j(n,{status:"installed",progress:1,version:i.version}),Qe(n,a)}).catch(a=>{var d;if(a instanceof _e){if(Ge.has(n))return;X("paused",n),ae[n]-=1,N.unshift(n),j(n,{status:Z.has(n)?"paused":"queued",progress:0,version:i.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),ae[n]<Ri){j(n,{status:"queued",progress:0,version:i.version,error:s}),setTimeout(()=>{var g;N.includes(n)||(x==null?void 0:x.app_id)===n||(N.push(n),me((g=ve[n])!=null&&g.length?n:void 0))},Oi);return}j(n,{status:"failed",progress:0,version:i.version,error:s}),Qe(n,R(n))}).finally(()=>{x=null;let a=N.find(s=>{var d;return(d=ve[s])==null?void 0:d.length});me(a)})},et=(e,{front:t=!1}={})=>{if((x==null?void 0:x.app_id)===e)return;let n=N.indexOf(e);if(n>=0){if(!t)return;N.splice(n,1)}t?N.unshift(e):N.push(e)},Ii=async e=>{let{host_id:t,client_token:n}=I(),i=new AbortController,r=setTimeout(()=>i.abort(),Pi);try{let o=`${Be}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(r)}},De=null,tt=()=>(De!=null||(De=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(I().channels.map(Ii)),i={};[...n].reverse().flat().forEach(a=>{i[a.app_id]=a});let r=Object.keys(P.getState().catalog).filter(a=>!i[a]);I().storage.setString(En,JSON.stringify(i)),P.setState({catalog:i}),await Promise.all(r.map(a=>In(a,{by_user:!1}))),r.forEach(a=>fe.delete(a));let o=Object.keys(i).filter(a=>!fe.has(a)),c=[],p={};for(let a of o.map(s=>i[s])){if(await yt(a)){j(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=R(a.app_id);if(Pn(a.app_id)&&!Xe.has(a.app_id)&&s&&await se(s)){j(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return P.setState({updates:p}),c.forEach(a=>{ae[a.app_id]=0,j(a.app_id,{status:Z.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),et(a.app_id)}),X("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",r,`${Date.now()-e}ms`),ge({type:"sync_complete",app_ids:o,removed:r}),Object.values(p).forEach(a=>ge({type:"update_available",...a})),me(),{ok:!0,app_ids:o,removed:r}}catch(n){let i=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",i),ge({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{De=null}})()),De),In=async(e,{by_user:t})=>{var r,o,c,p;if(t&&fe.add(e),Ge.has(e))return;Ge.add(e),Z.delete(e);let n=N.indexOf(e);n>=0&&N.splice(n,1),(x==null?void 0:x.app_id)===e&&x.handle.cancel();let i=(p=(c=(r=P.getState().downloads[e])==null?void 0:r.version)!=null?c:(o=R(e))==null?void 0:o.version)!=null?p:"";j(e,{status:"uninstalling",progress:0,version:i}),await yn(e),Ye(e),P.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete ae[e],Ge.delete(e),Qe(e,null),X("uninstalled",e,t?"(user)":"(not in list)"),ge({type:"uninstalled",app_id:e})},kn=e=>In(e,{by_user:!0}),Ln=e=>{let t=xe(e);return t?(fe.delete(e),(x==null?void 0:x.app_id)===e||N.includes(e)||(ae[e]=0,j(e,{status:Z.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),et(e),me(),X("restore",e)),!0):!1},Dn=e=>{if(Z.has(e))return;if(Z.add(e),X("pause app",e),(x==null?void 0:x.app_id)===e&&!x.forced){x.handle.cancel();return}let t=P.getState().downloads[e];N.includes(e)&&t&&j(e,{status:"paused",progress:0,version:t.version})},Un=e=>{if(!Z.delete(e))return;X("resume app",e);let t=P.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!N.includes(e)&&xe(e)&&(ae[e]=0,et(e)),N.includes(e)&&t&&j(e,{status:"queued",progress:0,version:t.version}),me()},Nn=e=>{let{pause_reasons:t}=P.getState();t.includes(e)||(P.setState({pause_reasons:[...t,e]}),X("pause",e),t.length===0&&ge({type:"pause_change",paused:!0,reasons:[e]}),x&&!x.forced&&x.handle.cancel())},Fn=e=>{let{pause_reasons:t}=P.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);P.setState({pause_reasons:n}),X("resume",e),n.length===0&&ge({type:"pause_change",paused:!1,reasons:n}),me()},Mt=e=>P.getState().updates[e],$n=async e=>{var n,i;let t=Mt(e);Xe.add(e);try{let r=await Ue(e),o=(i=t==null?void 0:t.next_version)!=null?i:(n=xe(e))==null?void 0:n.version;return!r||!o||r.version!==o?!1:(P.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),X("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Xe.delete(e)}},Bn=()=>Object.values(P.getState().catalog).map(e=>({...e,installed:!!R(e.app_id),removed_by_user:fe.has(e.app_id)})),xe=e=>P.getState().catalog[e],Ue=async e=>{let t=xe(e);if(!t)return;if(Z.delete(e),fe.delete(e),await yt(t))return R(e);let n=R(e);if(Pn(e)&&!Xe.has(e)&&n&&await se(n))return n;let i=new Promise(r=>{var o;((o=ve[e])!=null?o:ve[e]=[]).push(r)});return(x==null?void 0:x.app_id)===e?x.forced=!0:(ae[e]=0,et(e,{front:!0}),x&&!x.forced?x.handle.cancel():me(e)),i};var O=require("react/jsx-runtime"),vt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),qn=0,ki=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Li=w.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:r,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=(0,w.useRef)(null),y=(0,w.useRef)(!1),l=ne(V,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,T=l==null?void 0:l.app.manifest_url,_=l==null?void 0:l.context,b=l==null?void 0:l.url_params,[f,L]=(0,w.useState)(()=>h?R(h):null),[G,$]=(0,w.useState)(!1),[Se,ce]=(0,w.useState)(0),[A,S]=(0,w.useState)(0),[z,v]=(0,w.useState)(!1),D=(0,w.useRef)(null),ie=m=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,v(!0)},m)};(0,w.useEffect)(()=>()=>{D.current&&clearTimeout(D.current)},[]),(0,w.useEffect)(()=>{if(!h||!t&&f)return;let m=!0;return $(!1),(async()=>{let M=R(h),q=M?await se(M):!1;if(!m||(L(q?Q=>!Q||Q.version!==M.version||Q.permissions.join(",")!==M.permissions.join(",")?M:Q:null),__DEV__&&Date.now()-qn>1e4&&(qn=Date.now(),await tt()),!m))return;let le=await Ue(h),ye=le!==void 0?le:T?await Mn(h,T):R(h);if(m){if(!ye){$(!0);return}L(Q=>Q!=null?Q:ye)}})(),()=>{m=!1}},[t,h,T,Se]),(0,w.useEffect)(()=>vn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let B=ne(P,m=>{let M=h?m.downloads[h]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});(0,w.useEffect)(()=>{if(t||!h||!f)return;let m=R(h);if(!m||m.version===f.version)return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),L(m))}),()=>{M=!1}},[t,h,B,f==null?void 0:f.version]);let C=ne(P,m=>{var M;return h&&(M=m.apply_ticks[h])!=null?M:0});(0,w.useEffect)(()=>{if(!C||!h)return;let m=R(h);if(!m||m.version===(f==null?void 0:f.version))return;let M=!0;return se(m).then(q=>{!M||!q||(J(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),v(!1),L(m))}),()=>{M=!1}},[C]),(0,w.useEffect)(()=>{var q;let m=(q=I().keep_alive)==null?void 0:q.idle_close_ms;if(t||!m||m<=0)return;let M=setTimeout(()=>{Ye(e)},m);return()=>clearTimeout(M)},[t,e]),(0,w.useEffect)(()=>{r>0&&($(!1),v(!1),S(m=>m+1),ce(m=>m+1))},[r]);let H=(0,w.useRef)(t);(0,w.useEffect)(()=>{var m;H.current!==t&&(H.current=t,y.current&&((m=g.current)==null||m.injectJavaScript(cn(t?"resumed":"paused"))))},[t]);let pe=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${A}`,he=(0,w.useMemo)(()=>JSON.stringify([_!=null?_:{},b!=null?b:{}]),[_,b]),re=(0,w.useMemo)(()=>{var m;return gn(b!=null?b:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[he,f==null?void 0:f.permissions]),nt=(0,w.useMemo)(()=>un(_!=null?_:{},re)+sn()+(E.Platform.OS==="android"?an():"")+(I().debug?on():""),[re]),oe=(0,w.useRef)(null),Ne=(0,w.useRef)(null);(0,w.useEffect)(()=>{var M,q,le;if(!f)return;if(Ne.current!==pe){Ne.current=pe,oe.current=he;return}if(oe.current===he)return;let m=((q=JSON.parse((M=oe.current)!=null?M:"[]")[0])!=null?q:{}).org_id;if(oe.current=he,m===(_==null?void 0:_.org_id)&&y.current){v(!1),ie(1500),(le=g.current)==null||le.injectJavaScript(pn(_!=null?_:{},re));return}v(!1),S(ye=>ye+1)},[he,f,pe]),(0,w.useEffect)(()=>(t||(te(e),we(e)),()=>{te(e),we(e)}),[t,e,pe,r]),(0,w.useEffect)(()=>{let m=E.AppState.addEventListener("change",M=>{M==="background"&&!Qt()&&te(e)});return()=>m.remove()},[e]);let Fe=(0,w.useCallback)(async m=>{var q,le,ye,Q,it;let M=en(m.nativeEvent.data);if(!M){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(k=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,k)})}catch(k){console.warn("[miniapp] onWebEvent l\u1ED7i",h,k)}return}if(M.method==="log"){let{level:k,text:F}=M;J(`web:${e}`,k!=null?k:"log",F!=null?F:"");return}if(M.method==="pong"){D.current||v(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){D.current&&clearTimeout(D.current),D.current=null,v(!0);return}if(M.method==="ready"){y.current=!0,v(!0);let k=(q=V.getState().instances[e])==null?void 0:q.context;k&&((le=g.current)==null||le.injectJavaScript(ut(k)));return}try{let k=await mn(M,{getHostData:()=>{var F,W;return(W=(F=V.getState().instances[e])==null?void 0:F.host_data)!=null?W:{}},getPermissions:()=>{var F,W;return h?(W=(F=R(h))==null?void 0:F.permissions)!=null?W:[]:[]},getContext:()=>{var F,W;return(W=(F=V.getState().instances[e])==null?void 0:F.context)!=null?W:{}},is_dark:i,close:be,app_id:h!=null?h:"",instance_id:e,options:p,emit:(F,W)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(rn(F,W))},isActive:()=>V.getState().active_key===e&&E.AppState.currentState!=="background"});M.id&&((ye=g.current)==null||ye.injectJavaScript(tn(M.id,k)))}catch(k){if(!M.id)return;let F=k==null?void 0:k.code,W=k instanceof u?k:new u(typeof F=="string"?F:"HOST_ERROR",String((Q=k==null?void 0:k.message)!=null?Q:k));(it=g.current)==null||it.injectJavaScript(nn(M.id,W))}},[e,i,h,o,p]),Hn=(0,w.useCallback)(()=>{$(!1),S(m=>m+1),ce(m=>m+1)},[]);return(0,O.jsxs)(E.View,{style:[E.StyleSheet.absoluteFill,a&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&Y.behind],pointerEvents:t?"auto":"none",children:[f?(0,O.jsx)(jn.default,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?mt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:nt,onMessage:Fe,bounces:!1,overScrollMode:"never",onLoadStart:m=>{te(e),we(e),J(`webview:${e}`,"load start",vt(m.nativeEvent.url)),y.current=!1,v(!1)},onError:m=>{te(e),we(e),J(`webview:${e}`,"load error",vt(m.nativeEvent.url),m.nativeEvent.description),$(!0),v(!1)},onLoadEnd:m=>{let M=m.nativeEvent.url;J(`webview:${e}`,"load end",vt(M)),h&&(d==null||d({app_id:h,instance_id:e,url:M})),ie(1500)},onContentProcessDidTerminate:()=>{te(e),we(e),y.current=!1,v(!1),S(m=>m+1)},onRenderProcessGone:()=>(te(e),we(e),y.current=!1,v(!1),S(m=>m+1),!0),style:Y.webview},pe):null,l&&(0,O.jsx)(Ui,{visible:!f||!z,interactive:G,children:(0,O.jsx)(Di,{splash:c,app:l.app,is_dark:i,error:G,has_bundle:!!f,retry:Hn})})]})}),Di=w.default.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:r,retry:o})=>{let c=e,p=Ze(t.app_id),a=i?"error":!r&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,O.jsx)(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Ui=({visible:e,interactive:t,children:n})=>{let i=(0,w.useRef)(new E.Animated.Value(e?1:0)).current,[r,o]=(0,w.useState)(e);return(0,w.useEffect)(()=>{if(e){o(!0),i.setValue(1);return}let c=E.Animated.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,i]),r?(0,O.jsx)(E.Animated.View,{style:[E.StyleSheet.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},St=({app:e,is_dark:t,status:n,progress:i,retry:r})=>{let o=t?"#FAFAFA":"#18181B";return(0,O.jsxs)(E.View,{style:[Y.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,O.jsx)(E.View,{style:[Y.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,O.jsx)(E.Image,{source:{uri:e.icon},style:Y.splash_icon_image}):(0,O.jsx)(E.Text,{style:Y.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,O.jsx)(E.Text,{style:[Y.splash_name,{color:o}],children:e.name}),n==="error"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.Text,{style:Y.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,O.jsx)(E.TouchableOpacity,{activeOpacity:.7,style:[Y.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,O.jsx)(E.Text,{style:[Y.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.ActivityIndicator,{style:Y.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,O.jsxs)(E.Text,{style:Y.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},Vn=(e,t)=>{let n=(0,w.useRef)(t),i=(0,w.useRef)(!1);__DEV__&&!i.current&&n.current!==t&&(i.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Ni=({container:e,splash:t=St,is_dark:n=!1,bridge:i,close_on_back:r=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Vn("container",e),Vn("splash",t);let a=e,s=ne(V,f=>f.active_key),d=(0,w.useRef)(s);s&&(d.current=s);let g=ne(V,f=>Object.keys(f.instances).join("|")),y=ne(V,f=>{var L;return f.active_key?(L=f.instances[f.active_key])==null?void 0:L.app.name:void 0}),l=(0,w.useMemo)(()=>g?g.split("|"):[],[g]),[h,T]=(0,w.useState)({}),_=(0,w.useRef)(ki()).current;(0,w.useEffect)(()=>{if(!s||!r)return;let f=E.BackHandler.addEventListener("hardwareBackPress",()=>(be(),!0));return()=>f.remove()},[s,r]);let b=(0,w.useCallback)(()=>{let f=V.getState().active_key;f&&T(L=>({...L,[f]:(L[f]||0)+1}))},[]);return l.length?(0,O.jsx)(a,{visible:!!s,title:y!=null?y:"",is_dark:n,close:be,reload:b,subscribeWebAtTop:_.subscribe,children:l.map(f=>(0,O.jsx)(Li,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:_,splash:t,bridge:i,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},Y=E.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),zn=w.default.memo(Ni);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Tn=e=>{he=e,Et.forEach(t=>t())},O=()=>{if(!he)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return he},Pt=e=>{Et.add(e),he&&e()},W=(...e)=>{he!=null&&he.debug&&console.log("[miniapp]",...e)};var Cn=(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(i=>i.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:i})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>i==null?void 0:i(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),kn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import vt,{useCallback as yt,useEffect as V,useMemo as Qe,useRef as Z,useState as Me}from"react";import{AppState as bn,ActivityIndicator as Ir,Animated as At,BackHandler as Lr,Image as Dr,Platform as Nr,StyleSheet as St,Text as Le,TouchableOpacity as Ur,View as Mt}from"react-native";import Fr from"react-native-webview";import{Linking as Gt,Platform as rr}from"react-native";var Rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Fe,tt=()=>(Fe||(Fe=import("react-native-biometrics").then(({default:e})=>Rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Fe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Fe);import{PermissionsAndroid as Ae,Platform as In}from"react-native";var Ot=e=>{var n,r,i;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(i=t.maximumAge)!=null?i:0}},Tt=(e,t=()=>!0)=>new Promise((n,r)=>{let i=!1,o=(a,s)=>{i||(i=!0,clearTimeout(c),a?r(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>i?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(In.OS==="android"){let s=Ae.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ae.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await Ae.check(s);if(!p())return;let A=g||await Ae.check(d);if(!p())return;if(!g&&!A){let l=await Ae.requestMultiple([s,d]);if(!p())return;if(l[s]!==Ae.RESULTS.GRANTED&&l[d]!==Ae.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});import{Platform as Lt}from"react-native";var nt=20,Ct=20,Dt=/^[a-z][a-z0-9_-]{0,31}$/,Ln=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Dn=["low","medium","high"],le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),I=e=>new u("INVALID_PARAMS",e),Ee=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,kt=(e,t)=>{if(e===void 0)return{};if(!le(e)||Object.keys(e).length>Ct||Object.values(e).some(n=>typeof n!="string"))throw I(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Ct} key)`);return e},Nt=e=>{var n,r,i,o;if(e!==void 0&&!le(e))throw I("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Dt.test(t.source)))throw I("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Ln.test(c))))throw I("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ee(t.max_count,1,nt))throw I(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${nt}`);if(t.max_size!==void 0&&!Ee(t.max_size,1,Number.MAX_SAFE_INTEGER))throw I("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ee(t.concurrency,1,5))throw I("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(c=>c.toLowerCase()),max_count:(i=t.max_count)!=null?i:1,max_size:t.max_size,process:Nn(t.process),target:Un(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Nn=e=>{if(e===void 0)return{};if(!le(e))throw I("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!le(n))throw I("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Ee(n[r],1,1e4))throw I(`process.image.${r} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw I("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!le(n))throw I("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ee(n.max_duration,1,3600))throw I("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Dn.includes(n.quality))throw I("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Un=e=>{var n,r,i,o;if(e===void 0)return{target:"host",params:{}};if(!le(e))throw I("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Dt.test(t))throw I("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!le(e.params))throw I("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw I("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw I(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:kt(e.headers,"upload.headers"),form_data:kt(e.form_data,"upload.form_data"),field_name:(i=e.field_name)!=null?i:"file",url_field:(o=e.url_field)!=null?o:"url"}},Ut=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Fn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=Ut(e.name);return t.some(i=>i==="*/*"?!0:i.startsWith(".")?i===r:i.endsWith("/*")?n.startsWith(i.slice(0,-1)):n===i)},$n=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},_e,Bn=()=>(_e!=null||(_e=import("react-native-image-picker").catch(e=>{throw _e=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),_e),It=e=>async({accept:t,max_count:n,process:r})=>{var a,s,d,g,A,l,h,E,S;let i=await Bn(),o=$n(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=r.image)==null?void 0:a.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(A=r.video)==null?void 0:A.quality)!=null?l:"medium",durationLimit:(h=r.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await i.launchCamera({...c,saveToPhotos:!1}):await i.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let _=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(_,(E=p.errorMessage)!=null?E:p.errorCode)}return((S=p.assets)!=null?S:[]).filter(_=>_.uri).map((_,f)=>{var C,Y,U;return{uri:_.uri,name:(C=_.fileName)!=null?C:`file_${f+1}`,mime_type:(Y=_.type)!=null?Y:"application/octet-stream",size:_.fileSize,width:_.width,height:_.height,duration:_.duration,processed:!((U=_.type)!=null&&U.startsWith("video/"))||Lt.OS==="ios"}})},qn={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Vn={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},jn=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let r=t.map(s=>{var d;return(d=qn[s])!=null?d:Vn[s]}),i=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:i,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var E,S,_;return{uri:l.uri,name:(E=l.name)!=null?E:`file_${h+1}`,mime_type:(S=l.type)!=null?S:"application/octet-stream",size:(_=l.size)!=null?_:void 0}});if(Lt.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),A=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=A.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},be,zn=async e=>(be!=null||(be=import("@react-native-documents/picker").then(t=>jn(t)).catch(t=>{throw be=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await be)(e)),Hn={library:It("library"),camera:It("camera"),document:zn},xe,Ft=()=>(xe!=null||(xe=import("react-native-compressor").catch(()=>(xe=void 0,null))),xe),$t=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Wn=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Jn={low:640,medium:1280,high:1920},Kn=async(e,{image:t})=>{var r;if(!t||!Wn.has(e.mime_type.toLowerCase()))return e;let n=await Ft();if(!n)return e;try{let i=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:i,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await $t(n,i,e.size),processed:!0}}catch{return e}},Yn=async(e,{video:t})=>{var r;let n=await Ft();if(!n)return e;try{let i=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Jn[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:i,mime_type:"video/mp4",size:await $t(n,i,e.size),processed:!0}}catch{return e}},Gn={image:Kn,video:Yn},Qn=(e,t)=>t.split(".").reduce((n,r)=>le(n)?n[r]:void 0,e),Bt=({file:e,target:t,onProgress:n,signal:r})=>new Promise((i,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(r.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,A])=>a.append(g,A)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,A])=>p.setRequestHeader(g,A)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let A=Qn(g,c.url_field);if(typeof A!="string"||!A){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}i({url:A,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),qt=e=>{var r,i;let t={...Hn};for(let[o,c]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))c?t[o]=c:delete t[o];let n={url:Bt};for(let[o,c]of Object.entries((i=e==null?void 0:e.targets)!=null?i:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Vt=e=>{let{sources:t,targets:n}=qt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:nt}},Be=new Map,jt=(e,t)=>`${e}:${t}`,Xn=0,zt=(e,t)=>{var n;typeof t=="string"&&((n=Be.get(jt(e,t)))==null||n.abort())},we=e=>{for(let[t,n]of Be)t.startsWith(`${e}:`)&&n.abort()},$e=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Zn=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Ht=async(e,t)=>{var a;let{sources:n,targets:r}=qt(t.config),i=n[e.source];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=r[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=jt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++Xn}`);Be.set(p,c);try{return await er(e,t,i,o,c.signal)}finally{Be.delete(p)}},er=async(e,{instance_id:t,app_id:n,getContext:r,task_id:i,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var w,v,j;let g={app_id:n!=null?n:"",instance_id:t,context:{...(w=r==null?void 0:r())!=null?w:{}}},A=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw $e();if(!A.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=A.filter(M=>Fn(M,e.accept)?!0:(l.push({name:M.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${M.mime_type||Ut(M.name)}`}),!1)),E=h.map(()=>0),S=h.map(M=>{var k;return(k=M.size)!=null?k:0}),_=0,f=0,C=(M=!1)=>{if(!c||!i)return;let k=Date.now();if(!M&&k-f<200)return;f=k;let te=S.reduce((R,z)=>R+z,0),F=E.reduce((R,z)=>R+z,0);c("upload.progress",{task_id:i,loaded:F,total:te,percent:te?Math.min(100,Math.round(F/te*100)):0,done_count:_,count:h.length})},Y=[],U=0,ve=async()=>{var M,k,te;for(;U<h.length;){let F=U++,R=h[F];try{if(d.aborted)throw $e();let z=R.mime_type.startsWith("image/")?"image":R.mime_type.startsWith("video/")?"video":void 0,ce=z&&!R.processed?(k=(M=o==null?void 0:o.processors)==null?void 0:M[z])!=null?k:Gn[z]:void 0;if(ce&&(R=await ce(R,e.process),S[F]=(te=R.size)!=null?te:S[F],d.aborted))throw $e();if(e.max_size&&R.size&&R.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${R.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let me=(Ne,Ue)=>{E[F]=Ne,Ue&&(S[F]=Ue),C()},ne=await s({file:R,target:e.target,onProgress:me,signal:d,caller:g});if(typeof(ne==null?void 0:ne.url)!="string"||!ne.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Xe,...re}=ne;Y[F]={url:Xe,name:R.name,mime_type:R.mime_type,size:R.size,width:R.width,height:R.height,duration:R.duration,...Object.keys(re).length?{response:"response"in re?re.response:re}:{}},E[F]=S[F]}catch(z){l.push(Zn(h[F].name,z))}finally{_++,C(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},ve)),d.aborted)throw $e();let ae=Y.filter(M=>!!M);if(!ae.length){let M=l[0];throw new u((v=M==null?void 0:M.code)!=null?v:"UPLOAD_FAILED",(j=M==null?void 0:M.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ae,failed:l}};import{AppState as Wt,Platform as it}from"react-native";var J,Jt=()=>it.OS==="android"&&!!(J!=null&&J.requesting_permission),tr=1500,nr=()=>new Promise(e=>{if(it.OS!=="android"||Wt.currentState==="active"){e();return}let t=()=>{clearTimeout(n),r.remove(),e()},n=setTimeout(t,tr),r=Wt.addEventListener("change",i=>{i==="active"&&t()})}),rt=e=>{var t;if(J===e&&(J=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&it.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Kt=async(e,t,n,r=()=>!0)=>{var o,c,p,a,s;if(J)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let i={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};J=i;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(i.native=g,i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.requesting_permission=!0;let A;try{A=await g.requestPermissionsAsync()}finally{i.requesting_permission=!1}if(await nr(),i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!A.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.subscriptions.push(g.addListener("result",l=>{var h,E;J!==i||i.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(E=(h=l.results[0])==null?void 0:h.transcript)!=null?E:""})}),g.addListener("error",l=>{J===i&&!i.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{J===i&&(rt(i),n("speech.end"))})),i.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw rt(i),d}},Yt=e=>{let t=J;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ie=e=>{let t=J;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{rt(t)}};var Ve=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Qt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ve&&typeof t.method=="string"?t:null}catch{return null}},Re=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Xt=(e,t)=>Re({id:e,result:t}),Zt=(e,t)=>Re({id:e,error:{code:t.code,message:t.message}}),en=(e,t)=>Re({event:e,data:t}),st=e=>Re({event:"context",data:e});var tn=()=>`(function () {
|
|
1
|
+
var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Ln=e=>{he=e,Et.forEach(t=>t())},O=()=>{if(!he)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return he},Pt=e=>{Et.add(e),he&&e()},W=(...e)=>{he!=null&&he.debug&&console.log("[miniapp]",...e)};var Dn=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(i=>i.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:r})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>r==null?void 0:r(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Un=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import vt,{useCallback as wt,useEffect as V,useMemo as Qe,useRef as Z,useState as Me}from"react";import{AppState as Rn,ActivityIndicator as Ui,Animated as yt,BackHandler as Ni,Image as Fi,Platform as $i,StyleSheet as St,Text as Le,TouchableOpacity as Bi,View as Mt}from"react-native";import qi from"react-native-webview";import{Linking as en,Platform as si}from"react-native";var Rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Fe,tt=()=>(Fe||(Fe=import("react-native-biometrics").then(({default:e})=>Rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Fe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Fe);import{PermissionsAndroid as ye,Platform as Nn}from"react-native";var Ot=e=>{var n,i,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Tt=(e,t=()=>!0)=>new Promise((n,i)=>{let r=!1,o=(a,s)=>{r||(r=!0,clearTimeout(c),a?i(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>r?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(Nn.OS==="android"){let s=ye.PERMISSIONS.ACCESS_FINE_LOCATION,d=ye.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await ye.check(s);if(!p())return;let y=g||await ye.check(d);if(!p())return;if(!g&&!y){let l=await ye.requestMultiple([s,d]);if(!p())return;if(l[s]!==ye.RESULTS.GRANTED&&l[d]!==ye.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});import{Platform as Nt}from"react-native";var nt=20,Ct=20,Ft=/^[a-z][a-z0-9_-]{0,31}$/,Fn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,$n=["low","medium","high"],le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),k=e=>new u("INVALID_PARAMS",e),Ee=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,It=(e,t)=>{if(e===void 0)return{};if(!le(e)||Object.keys(e).length>Ct||Object.values(e).some(n=>typeof n!="string"))throw k(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Ct} key)`);return e},$t=e=>{var n,i,r,o;if(e!==void 0&&!le(e))throw k("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ft.test(t.source)))throw k("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Fn.test(c))))throw k("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ee(t.max_count,1,nt))throw k(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${nt}`);if(t.max_size!==void 0&&!Ee(t.max_size,1,Number.MAX_SAFE_INTEGER))throw k("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ee(t.concurrency,1,5))throw k("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:Bn(t.process),target:qn(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Bn=e=>{if(e===void 0)return{};if(!le(e))throw k("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!le(n))throw k("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!Ee(n[i],1,1e4))throw k(`process.image.${i} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw k("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!le(n))throw k("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ee(n.max_duration,1,3600))throw k("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!$n.includes(n.quality))throw k("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},qn=e=>{var n,i,r,o;if(e===void 0)return{target:"host",params:{}};if(!le(e))throw k("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ft.test(t))throw k("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!le(e.params))throw k("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw k("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw k(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:It(e.headers,"upload.headers"),form_data:It(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(o=e.url_field)!=null?o:"url"}},Bt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Vn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=Bt(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===i:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},jn=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},_e,zn=()=>(_e!=null||(_e=import("react-native-image-picker").catch(e=>{throw _e=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),_e),kt=e=>async({accept:t,max_count:n,process:i})=>{var a,s,d,g,y,l,h,E,S;let r=await zn(),o=jn(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=i.image)==null?void 0:a.max_width,maxHeight:(s=i.image)==null?void 0:s.max_height,quality:(g=(d=i.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(y=i.video)==null?void 0:y.quality)!=null?l:"medium",durationLimit:(h=i.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await r.launchCamera({...c,saveToPhotos:!1}):await r.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let _=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(_,(E=p.errorMessage)!=null?E:p.errorCode)}return((S=p.assets)!=null?S:[]).filter(_=>_.uri).map((_,f)=>{var C,Y,N;return{uri:_.uri,name:(C=_.fileName)!=null?C:`file_${f+1}`,mime_type:(Y=_.type)!=null?Y:"application/octet-stream",size:_.fileSize,width:_.width,height:_.height,duration:_.duration,processed:!((N=_.type)!=null&&N.startsWith("video/"))||Nt.OS==="ios"}})},Hn={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Wn={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Jn=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let i=t.map(s=>{var d;return(d=Hn[s])!=null?d:Wn[s]}),r=!t.length||i.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(i)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var E,S,_;return{uri:l.uri,name:(E=l.name)!=null?E:`file_${h+1}`,mime_type:(S=l.type)!=null?S:"application/octet-stream",size:(_=l.size)!=null?_:void 0}});if(Nt.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),y=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=y.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},be,Kn=async e=>(be!=null||(be=import("@react-native-documents/picker").then(t=>Jn(t)).catch(t=>{throw be=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await be)(e)),qt={library:kt("library"),camera:kt("camera"),document:Kn},Lt={type:"image",label:"\u1EA2nh",accept:["image/*"]},Dt={type:"video",label:"Video",accept:["video/*"]},Ut={library:[Lt,Dt,{type:"media",label:"\u1EA2nh + video",accept:["image/*","video/*"]}],camera:[Lt,Dt],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"office",label:"Word / Excel",accept:[".doc",".docx",".xls",".xlsx"]}]},xe,Vt=()=>(xe!=null||(xe=import("react-native-compressor").catch(()=>(xe=void 0,null))),xe),jt=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Yn=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Gn={low:640,medium:1280,high:1920},Qn=async(e,{image:t})=>{var i;if(!t||!Yn.has(e.mime_type.toLowerCase()))return e;let n=await Vt();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(i=t.quality)!=null?i:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await jt(n,r,e.size),processed:!0}}catch{return e}},Xn=async(e,{video:t})=>{var i;let n=await Vt();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Gn[(i=t==null?void 0:t.quality)!=null?i:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await jt(n,r,e.size),processed:!0}}catch{return e}},Zn={image:Qn,video:Xn},ei=(e,t)=>t.split(".").reduce((n,i)=>le(n)?n[i]:void 0,e),zt=({file:e,target:t,onProgress:n,signal:i})=>new Promise((r,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,y])=>a.append(g,y)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();i.addEventListener("abort",s);let d=g=>{i.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,y])=>p.setRequestHeader(g,y)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let y=ei(g,c.url_field);if(typeof y!="string"||!y){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}r({url:y,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Ht=e=>{var i,r;let t={...qt};for(let[o,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[o]=c:delete t[o];let n={url:zt};for(let[o,c]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Wt=e=>{let{sources:t,targets:n}=Ht(e),i=Object.keys(t),r=Object.fromEntries(i.filter(o=>t[o]===qt[o]&&Ut[o]).map(o=>[o,Ut[o]]));return{sources:i,file_types:r,targets:Object.keys(n),max_count:nt}},Be=new Map,Jt=(e,t)=>`${e}:${t}`,ti=0,Kt=(e,t)=>{var n;typeof t=="string"&&((n=Be.get(Jt(e,t)))==null||n.abort())},Ae=e=>{for(let[t,n]of Be)t.startsWith(`${e}:`)&&n.abort()},$e=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),ni=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Yt=async(e,t)=>{var a;let{sources:n,targets:i}=Ht(t.config),r=n[e.source];if(!r)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=i[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=Jt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++ti}`);Be.set(p,c);try{return await ii(e,t,r,o,c.signal)}finally{Be.delete(p)}},ii=async(e,{instance_id:t,app_id:n,getContext:i,task_id:r,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var A,v,j;let g={app_id:n!=null?n:"",instance_id:t,context:{...(A=i==null?void 0:i())!=null?A:{}}},y=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw $e();if(!y.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=y.filter(M=>Vn(M,e.accept)?!0:(l.push({name:M.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${M.mime_type||Bt(M.name)}`}),!1)),E=h.map(()=>0),S=h.map(M=>{var I;return(I=M.size)!=null?I:0}),_=0,f=0,C=(M=!1)=>{if(!c||!r)return;let I=Date.now();if(!M&&I-f<200)return;f=I;let te=S.reduce((R,z)=>R+z,0),F=E.reduce((R,z)=>R+z,0);c("upload.progress",{task_id:r,loaded:F,total:te,percent:te?Math.min(100,Math.round(F/te*100)):0,done_count:_,count:h.length})},Y=[],N=0,ve=async()=>{var M,I,te;for(;N<h.length;){let F=N++,R=h[F];try{if(d.aborted)throw $e();let z=R.mime_type.startsWith("image/")?"image":R.mime_type.startsWith("video/")?"video":void 0,ce=z&&!R.processed?(I=(M=o==null?void 0:o.processors)==null?void 0:M[z])!=null?I:Zn[z]:void 0;if(ce&&(R=await ce(R,e.process),S[F]=(te=R.size)!=null?te:S[F],d.aborted))throw $e();if(e.max_size&&R.size&&R.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${R.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let me=(Ue,Ne)=>{E[F]=Ue,Ne&&(S[F]=Ne),C()},ne=await s({file:R,target:e.target,onProgress:me,signal:d,caller:g});if(typeof(ne==null?void 0:ne.url)!="string"||!ne.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Xe,...ie}=ne;Y[F]={url:Xe,name:R.name,mime_type:R.mime_type,size:R.size,width:R.width,height:R.height,duration:R.duration,...Object.keys(ie).length?{response:"response"in ie?ie.response:ie}:{}},E[F]=S[F]}catch(z){l.push(ni(h[F].name,z))}finally{_++,C(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},ve)),d.aborted)throw $e();let ae=Y.filter(M=>!!M);if(!ae.length){let M=l[0];throw new u((v=M==null?void 0:M.code)!=null?v:"UPLOAD_FAILED",(j=M==null?void 0:M.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ae,failed:l}};import{AppState as Gt,Platform as rt}from"react-native";var J,Qt=()=>rt.OS==="android"&&!!(J!=null&&J.requesting_permission),ri=1500,oi=()=>new Promise(e=>{if(rt.OS!=="android"||Gt.currentState==="active"){e();return}let t=()=>{clearTimeout(n),i.remove(),e()},n=setTimeout(t,ri),i=Gt.addEventListener("change",r=>{r==="active"&&t()})}),it=e=>{var t;if(J===e&&(J=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&rt.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Xt=async(e,t,n,i=()=>!0)=>{var o,c,p,a,s;if(J)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};J=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(r.native=g,r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await g.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await oi(),r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!i())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(g.addListener("result",l=>{var h,E;J!==r||r.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(E=(h=l.results[0])==null?void 0:h.transcript)!=null?E:""})}),g.addListener("error",l=>{J===r&&!r.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{J===r&&(it(r),n("speech.end"))})),r.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw it(r),d}},Zt=e=>{let t=J;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},re=e=>{let t=J;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{it(t)}};var Ve=1,u=class extends Error{constructor(n,i){super(i);this.code=n}},tn=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ve&&typeof t.method=="string"?t:null}catch{return null}},Re=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,nn=(e,t)=>Re({id:e,result:t}),rn=(e,t)=>Re({id:e,error:{code:t.code,message:t.message}}),on=(e,t)=>Re({event:e,data:t}),st=e=>Re({event:"context",data:e});var sn=()=>`(function () {
|
|
2
2
|
var post = function (level, args) {
|
|
3
3
|
try {
|
|
4
4
|
var parts = [];
|
|
@@ -19,7 +19,7 @@ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Tn=e=>{he
|
|
|
19
19
|
window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
|
|
20
20
|
// Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
|
|
21
21
|
post('info', ['[page] ' + location.pathname + location.hash]);
|
|
22
|
-
})(); true;`,
|
|
22
|
+
})(); true;`,an=()=>`(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; }
|
|
@@ -38,7 +38,7 @@ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Tn=e=>{he
|
|
|
38
38
|
var el = e.target === document ? document.documentElement : e.target;
|
|
39
39
|
if (el && el.scrollTop > 0) { report(false); }
|
|
40
40
|
}, { capture: true, passive: true });
|
|
41
|
-
})(); true;`,
|
|
41
|
+
})(); true;`,cn=()=>`(function () {
|
|
42
42
|
if (window.__retionSafeAreaFrozen) { return; }
|
|
43
43
|
window.__retionSafeAreaFrozen = true;
|
|
44
44
|
var max = {};
|
|
@@ -59,8 +59,8 @@ var et="https://retion-miniapp-platform.vercel.app",he=null,Et=new Set,Tn=e=>{he
|
|
|
59
59
|
},
|
|
60
60
|
});
|
|
61
61
|
};
|
|
62
|
-
})(); true;`,
|
|
63
|
-
${st(e)}`},
|
|
62
|
+
})(); true;`,pn=e=>Re({event:e}),ln=(e,t)=>{let n=un(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
|
|
63
|
+
${st(e)}`},un=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),dn=(e,t={})=>{let n=un(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Ve} };
|
|
64
64
|
window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
|
|
65
65
|
${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
|
|
66
|
-
true;`},pn={partner:"partner_token",chatbox:"chatbox_token"},ln=(e,t)=>{let n={...e};for(let r of Object.values(pn))t.includes(r)||delete n[r];return n},ot=new Set,Pe=async(e,t)=>{if(ot.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);ot.add(e);try{return await t()}finally{ot.delete(e)}},ir=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),qe=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},un=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:i,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var E,S,_,f,C,Y,U,ve,ae;let A=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let w=Ot(t);return Pe(e,()=>Tt(w,g))}case"speech.start":{if(!d)throw h();let w={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");w.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new u("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);w[v]=t[v]}return Kt(a,w,d,g)}case"speech.stop":return Yt(a);case"uploadFiles":{let{task_id:w,...v}=t!=null?t:{};if(w!==void 0&&(typeof w!="string"||!w))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ht(Nt(v),{instance_id:a,app_id:p,getContext:i,task_id:w,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>Pe("uploadFiles.pick",j)})}case"uploadFiles.cancel":zt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Vt(s==null?void 0:s.upload);case"getBiometricAvailability":return((E=s==null?void 0:s.biometrics)!=null?E:await tt()).getAvailability();case"authenticateBiometric":{let w=qe(t==null?void 0:t.reason,"reason").trim();if(!w||w.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Pe(e,async()=>{var M;return((M=s==null?void 0:s.biometrics)!=null?M:await tt()).authenticate({reason:w,cancelButtonText:v})})}case"requestPayment":{let w=A==null?void 0:A.requestPayment;if(!w)throw h();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:v,currency:qe(t==null?void 0:t.currency,"currency")};return Pe(e,()=>w(j,l))}case"printImage":{let w=A==null?void 0:A.printImage;if(!w)throw h();let v=qe(t==null?void 0:t.image,"image");await Pe(e,()=>w({image:v},l));return}case"openScreen":if(!(A!=null&&A.openScreen))throw h();await A.openScreen({screen:qe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let w=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(w))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(w):Gt.openURL(w));return}case"openLink":{let w=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(w)||/^(javascript|file|data|about|blob):/i.test(w))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(w):Gt.openURL(w))}catch(v){throw new u("NOT_SUPPORTED",String((C=(f=v==null?void 0:v.message)!=null?f:v)!=null?C:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(U=s==null?void 0:s.showToast)==null||U.call(s,String((Y=t==null?void 0:t.message)!=null?Y:""));return;case"haptic":{let w=ir.has(t==null?void 0:t.type)?t.type:"selection";(ve=s==null?void 0:s.haptic)==null||ve.call(s,w);return}case"getSystemInfo":return{platform:rr.OS==="ios"?"ios":"android",appVersion:(ae=s==null?void 0:s.app_version)!=null?ae:"",theme:o?"dark":"light"};case"getAccessToken":{let w=n().access_token;if(!w)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}case"getToken":{let w=t==null?void 0:t.type;if(w==="access"){let M=n().access_token;if(!M)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return M}if(w!=="partner"&&w!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(w)}`);let v=pn[w];if(!r().includes(v))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=w==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return j}case"getUserInfo":{let w=n().user;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return w}case"getPageInfo":{let w=n().page;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return w}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ct=e=>`bundle:${e}`,pt=()=>`${O().file_system.document_dir}/miniapps`,lt=pt,ut=(e,t,n="index.html",r=!1,i=[])=>{let o=`${lt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:i}},at=e=>{var t;O().storage.setString(ct(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},or=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,P=e=>{let t=O().storage.getString(ct(e));if(!t)return null;try{let{version:n,entry:r,context_update:i,permissions:o}=JSON.parse(t);return ut(e,n,r,!!i,Array.isArray(o)?o:[])}catch{return null}},oe=e=>O().file_system.exists(e.entry_uri.replace("file://","")),dt=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await oe(t)},gn=async(e,t)=>{let n=O().file_system,r=`${lt()}/${e}`,i=await n.listDir(r).catch(()=>[]);await Promise.all(i.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},mn=async e=>{var t;await((t=Te[e])==null?void 0:t.catch(()=>{})),O().storage.setString(ct(e),""),await O().file_system.remove(`${lt()}/${e}`).catch(()=>{})},Se=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Te={},fn=(e,t)=>{var o;let r=((o=Te[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return Te[e]=i,i.then(()=>{Te[e]===i&&delete Te[e]}),r},sr=(e,t)=>{var i,o;let n=e.split(".").map(c=>parseInt(c,10)||0),r=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,r.length);c++){let p=((i=n[c])!=null?i:0)-((o=r[c])!=null?o:0);if(p)return p}return 0},ar=({manifest:e,zip_path:t})=>fn(e.app_id,async()=>{var o;let n=O().file_system,r=P(e.app_id);if(r&&sr(r.version,e.version)>=0&&await oe(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let i=ut(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(i.dir).catch(()=>{}),await n.mkdir(i.dir),await n.unzip(t,i.dir),at(e),W("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),gn(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),i}),gt=(e,{base_url:t,onProgress:n}={})=>{let r=O().file_system,i=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new Se},a=async()=>{var g;p();let s=P(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return at(e),P(e.app_id);p();let d=r.download({url:t?or(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(A,l)=>{var E;let h=l>0?l:(E=e.size)!=null?E:0;h>0&&(n==null||n(Math.min(1,A/h)))}});i=d;try{let{status:A}=await d.promise;if(p(),A!==200)throw new Error(`bundle ${A}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else W("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ut(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(l.dir).catch(()=>{}),await r.mkdir(l.dir),await r.unzip(c,l.dir),at(e),gn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(A){throw o?new Se:A}finally{i=null,r.remove(c).catch(()=>{})}};return{promise:fn(e.app_id,a),cancel:()=>{o=!0,i==null||i.cancel()}}},Oe={},cr=__DEV__?0:60*1e3,dn={},hn=(e,t)=>{var r,i;let n=P(e);return n&&Date.now()-((r=dn[t])!=null?r:0)<cr?Promise.resolve(n):((i=Oe[e])!=null||(Oe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await gt(c,{base_url:t}).promise;return dn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{Oe[e]=void 0})),Oe[e])};var je=new Map,An=(e,t)=>(je.set(e,t),()=>{je.get(e)===t&&je.delete(e)}),pr=(e,t)=>{let n=je.get(e);return n?n(t):!1};import{useRef as lr,useSyncExternalStore as ur}from"react";var ze=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let i=typeof r=="function"?r(t):r;t={...t,...i},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},ee=(e,t,n=Object.is)=>{let r=lr(null),i=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return r.current={state:o,selector:t,value:a},a};return ur(e.subscribe,i)};var B=ze({active_key:null,instances:{}}),wn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:i={}},o)=>{var p;let c=(p=O().keep_alive)==null?void 0:p.max_webviews;B.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:i,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(A=>A!==s).sort((A,l)=>d[A].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(A=>{delete d[A]}),o?{active_key:s,instances:d}:{instances:d}})},dr=e=>wn(e,!0),gr=e=>wn(e,!1),Ce=()=>B.setState({active_key:null}),He=e=>{B.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var yn="catalog",mr="paused_apps",fr="removed_apps",hr=10*1e3,Ar=2,wr=3e3,yr=()=>{var e;try{return JSON.parse((e=O().storage.getString(yn))!=null?e:"{}")}catch{return{}}},x=ze({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Mn=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},Ke=new Set,vn=e=>{let t=new Set,n=()=>O().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let i=JSON.parse((r=O().storage.getString(e))!=null?r:"[]");Array.isArray(i)&&i.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},X=vn(mr),ge=vn(fr);Pt(()=>{X.load(),ge.load();let e=yr(),t={};Object.keys(e).filter(n=>!ge.has(n)).forEach(n=>{let r=P(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:X.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),x.setState({catalog:e,downloads:t})});var ft=e=>ee(x,t=>e?t.downloads[e]:void 0),Mr=()=>ee(x,e=>e.pause_reasons.length>0),Q=(...e)=>W("queue",...e),L=[],se={},b=null,We=new Set,ye={},mt=new Set,ue=e=>{mt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},vr=e=>(mt.add(e),()=>{mt.delete(e)}),Sr=()=>x.getState().downloads,q=(e,t)=>{let n=!!P(e),r=x.getState().downloads[e],i=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...i?{status:i}:{},has_local:n};x.setState(c=>({downloads:{...c.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?ue({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&ue({type:"progress",app_id:e,progress:o.progress,version:o.version})},Je=(e,t)=>{var n;(n=ye[e])==null||n.forEach(r=>r(t)),delete ye[e]},_r=()=>x.getState().pause_reasons.length>0,de=e=>{var p;if(b)return;let t=e?L.indexOf(e):_r()?-1:L.findIndex(a=>!X.has(a));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),r=x.getState().catalog[n];if(!r){Je(n,P(n)),de();return}let i=Date.now();se[n]=((p=se[n])!=null?p:0)+1,q(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=gt(r,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,q(n,{progress:s/100,version:r.version}))}});b={app_id:n,handle:c,forced:!!e},Q("start",n,r.version,e?"(forced)":""),c.promise.then(a=>{Q("installed",n,r.version,`${Date.now()-i}ms`),q(n,{status:"installed",progress:1,version:r.version}),Je(n,a)}).catch(a=>{var d;if(a instanceof Se){if(We.has(n))return;Q("paused",n),se[n]-=1,L.unshift(n),q(n,{status:X.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),se[n]<Ar){q(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;L.includes(n)||(b==null?void 0:b.app_id)===n||(L.push(n),de((g=ye[n])!=null&&g.length?n:void 0))},wr);return}q(n,{status:"failed",progress:0,version:r.version,error:s}),Je(n,P(n))}).finally(()=>{b=null;let a=L.find(s=>{var d;return(d=ye[s])==null?void 0:d.length});de(a)})},Ye=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},br=async e=>{let{host_id:t,client_token:n}=O(),r=new AbortController,i=setTimeout(()=>r.abort(),hr);try{let o=`${et}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(i)}},ke=null,ht=()=>(ke!=null||(ke=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(br)),r={};[...n].reverse().flat().forEach(a=>{r[a.app_id]=a});let i=Object.keys(x.getState().catalog).filter(a=>!r[a]);O().storage.setString(yn,JSON.stringify(r)),x.setState({catalog:r}),await Promise.all(i.map(a=>Sn(a,{by_user:!1}))),i.forEach(a=>ge.delete(a));let o=Object.keys(r).filter(a=>!ge.has(a)),c=[],p={};for(let a of o.map(s=>r[s])){if(await dt(a)){q(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=P(a.app_id);if(Mn(a.app_id)&&!Ke.has(a.app_id)&&s&&await oe(s)){q(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return x.setState({updates:p}),c.forEach(a=>{se[a.app_id]=0,q(a.app_id,{status:X.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),Ye(a.app_id)}),Q("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",i,`${Date.now()-e}ms`),ue({type:"sync_complete",app_ids:o,removed:i}),Object.values(p).forEach(a=>ue({type:"update_available",...a})),de(),{ok:!0,app_ids:o,removed:i}}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),ue({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ke=null}})()),ke),Sn=async(e,{by_user:t})=>{var i,o,c,p;if(t&&ge.add(e),We.has(e))return;We.add(e),X.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let r=(p=(c=(i=x.getState().downloads[e])==null?void 0:i.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?p:"";q(e,{status:"uninstalling",progress:0,version:r}),await mn(e),He(e),x.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete se[e],We.delete(e),Je(e,null),Q("uninstalled",e,t?"(user)":"(not in list)"),ue({type:"uninstalled",app_id:e})},xr=e=>Sn(e,{by_user:!0}),Er=e=>{let t=Ie(e);return t?(ge.delete(e),(b==null?void 0:b.app_id)===e||L.includes(e)||(se[e]=0,q(e,{status:X.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ye(e),de(),Q("restore",e)),!0):!1},Pr=e=>{if(X.has(e))return;if(X.add(e),Q("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=x.getState().downloads[e];L.includes(e)&&t&&q(e,{status:"paused",progress:0,version:t.version})},Rr=e=>{if(!X.delete(e))return;Q("resume app",e);let t=x.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&Ie(e)&&(se[e]=0,Ye(e)),L.includes(e)&&t&&q(e,{status:"queued",progress:0,version:t.version}),de()},Or=e=>{let{pause_reasons:t}=x.getState();t.includes(e)||(x.setState({pause_reasons:[...t,e]}),Q("pause",e),t.length===0&&ue({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},Tr=e=>{let{pause_reasons:t}=x.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);x.setState({pause_reasons:n}),Q("resume",e),n.length===0&&ue({type:"pause_change",paused:!1,reasons:n}),de()},_n=e=>x.getState().updates[e],Cr=async e=>{var n,r;let t=_n(e);Ke.add(e);try{let i=await Ge(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=Ie(e))==null?void 0:n.version;return!i||!o||i.version!==o?!1:(x.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),Q("updated",e,t==null?void 0:t.current_version,"\u2192",i.version),!0)}finally{Ke.delete(e)}},kr=()=>Object.values(x.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:ge.has(e.app_id)})),Ie=e=>x.getState().catalog[e],Ge=async e=>{let t=Ie(e);if(!t)return;if(X.delete(e),ge.delete(e),await dt(t))return P(e);let n=P(e);if(Mn(e)&&!Ke.has(e)&&n&&await oe(n))return n;let r=new Promise(i=>{var o;((o=ye[e])!=null?o:ye[e]=[]).push(i)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(se[e]=0,Ye(e,{front:!0}),b&&!b.forced?b.handle.cancel():de(e)),r};import{Fragment as Pn,jsx as N,jsxs as De}from"react/jsx-runtime";var wt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),xn=0,$r=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Br=vt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:i,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=Z(null),A=Z(!1),l=ee(B,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,E=l==null?void 0:l.app.manifest_url,S=l==null?void 0:l.context,_=l==null?void 0:l.url_params,[f,C]=Me(()=>h?P(h):null),[Y,U]=Me(!1),[ve,ae]=Me(0),[w,v]=Me(0),[j,M]=Me(!1),k=Z(null),te=m=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{k.current=null,M(!0)},m)};V(()=>()=>{k.current&&clearTimeout(k.current)},[]),V(()=>{if(!h||!t&&f)return;let m=!0;return U(!1),(async()=>{let y=P(h),$=y?await oe(y):!1;if(!m||(C($?G=>!G||G.version!==y.version||G.permissions.join(",")!==y.permissions.join(",")?y:G:null),__DEV__&&Date.now()-xn>1e4&&(xn=Date.now(),await ht()),!m))return;let pe=await Ge(h),fe=pe!==void 0?pe:E?await hn(h,E):P(h);if(m){if(!fe){U(!0);return}C(G=>G!=null?G:fe)}})(),()=>{m=!1}},[t,h,E,ve]),V(()=>An(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let F=ee(x,m=>{let y=h?m.downloads[h]:void 0;return(y==null?void 0:y.status)==="installed"?y.version:void 0});V(()=>{if(t||!h||!f)return;let m=P(h);if(!m||m.version===f.version)return;let y=!0;return oe(m).then($=>{!y||!$||(W(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),C(m))}),()=>{y=!1}},[t,h,F,f==null?void 0:f.version]);let R=ee(x,m=>{var y;return h&&(y=m.apply_ticks[h])!=null?y:0});V(()=>{if(!R||!h)return;let m=P(h);if(!m||m.version===(f==null?void 0:f.version))return;let y=!0;return oe(m).then($=>{!y||!$||(W(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),M(!1),C(m))}),()=>{y=!1}},[R]),V(()=>{var $;let m=($=O().keep_alive)==null?void 0:$.idle_close_ms;if(t||!m||m<=0)return;let y=setTimeout(()=>{He(e)},m);return()=>clearTimeout(y)},[t,e]),V(()=>{i>0&&(U(!1),M(!1),v(m=>m+1),ae(m=>m+1))},[i]);let z=Z(t);V(()=>{var m;z.current!==t&&(z.current=t,A.current&&((m=g.current)==null||m.injectJavaScript(on(t?"resumed":"paused"))))},[t]);let ce=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${w}`,me=Qe(()=>JSON.stringify([S!=null?S:{},_!=null?_:{}]),[S,_]),ne=Qe(()=>{var m;return ln(_!=null?_:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[me,f==null?void 0:f.permissions]),Xe=Qe(()=>cn(S!=null?S:{},ne)+nn()+(Nr.OS==="android"?rn():"")+(O().debug?tn():""),[ne]),re=Z(null),Ne=Z(null);V(()=>{var y,$,pe;if(!f)return;if(Ne.current!==ce){Ne.current=ce,re.current=me;return}if(re.current===me)return;let m=(($=JSON.parse((y=re.current)!=null?y:"[]")[0])!=null?$:{}).org_id;if(re.current=me,m===(S==null?void 0:S.org_id)&&A.current){M(!1),te(1500),(pe=g.current)==null||pe.injectJavaScript(sn(S!=null?S:{},ne));return}M(!1),v(fe=>fe+1)},[me,f,ce]),V(()=>(t||(ie(e),we(e)),()=>{ie(e),we(e)}),[t,e,ce,i]),V(()=>{let m=bn.addEventListener("change",y=>{y==="background"&&!Jt()&&ie(e)});return()=>m.remove()},[e]);let Ue=yt(async m=>{var $,pe,fe,G,Ze;let y=Qt(m.nativeEvent.data);if(!y){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(T=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)})}catch(T){console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)}return}if(y.method==="log"){let{level:T,text:D}=y;W(`web:${e}`,T!=null?T:"log",D!=null?D:"");return}if(y.method==="pong"){k.current||M(!0);return}if(y.method==="touchAtTop"){o.emit(!!y.at_top);return}if(y.method==="contextApplied"){k.current&&clearTimeout(k.current),k.current=null,M(!0);return}if(y.method==="ready"){A.current=!0,M(!0);let T=($=B.getState().instances[e])==null?void 0:$.context;T&&((pe=g.current)==null||pe.injectJavaScript(st(T)));return}try{let T=await un(y,{getHostData:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.host_data)!=null?H:{}},getPermissions:()=>{var D,H;return h?(H=(D=P(h))==null?void 0:D.permissions)!=null?H:[]:[]},getContext:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.context)!=null?H:{}},is_dark:r,close:Ce,app_id:h!=null?h:"",instance_id:e,options:p,emit:(D,H)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(en(D,H))},isActive:()=>B.getState().active_key===e&&bn.currentState!=="background"});y.id&&((fe=g.current)==null||fe.injectJavaScript(Xt(y.id,T)))}catch(T){if(!y.id)return;let D=T==null?void 0:T.code,H=T instanceof u?T:new u(typeof D=="string"?D:"HOST_ERROR",String((G=T==null?void 0:T.message)!=null?G:T));(Ze=g.current)==null||Ze.injectJavaScript(Zt(y.id,H))}},[e,r,h,o,p]),On=yt(()=>{U(!1),v(m=>m+1),ae(m=>m+1)},[]);return De(Mt,{style:[St.absoluteFill,a&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&K.behind],pointerEvents:t?"auto":"none",children:[f?N(Fr,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?pt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Xe,onMessage:Ue,bounces:!1,overScrollMode:"never",onLoadStart:m=>{ie(e),we(e),W(`webview:${e}`,"load start",wt(m.nativeEvent.url)),A.current=!1,M(!1)},onError:m=>{ie(e),we(e),W(`webview:${e}`,"load error",wt(m.nativeEvent.url),m.nativeEvent.description),U(!0),M(!1)},onLoadEnd:m=>{let y=m.nativeEvent.url;W(`webview:${e}`,"load end",wt(y)),h&&(d==null||d({app_id:h,instance_id:e,url:y})),te(1500)},onContentProcessDidTerminate:()=>{ie(e),we(e),A.current=!1,M(!1),v(m=>m+1)},onRenderProcessGone:()=>(ie(e),we(e),A.current=!1,M(!1),v(m=>m+1),!0),style:K.webview},ce):null,l&&N(Vr,{visible:!f||!j,interactive:Y,children:N(qr,{splash:c,app:l.app,is_dark:r,error:Y,has_bundle:!!f,retry:On})})]})}),qr=vt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:i,retry:o})=>{let c=e,p=ft(t.app_id),a=r?"error":!i&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return N(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Vr=({visible:e,interactive:t,children:n})=>{let r=Z(new At.Value(e?1:0)).current,[i,o]=Me(e);return V(()=>{if(e){o(!0),r.setValue(1);return}let c=At.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,r]),i?N(At.View,{style:[St.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},Rn=({app:e,is_dark:t,status:n,progress:r,retry:i})=>{let o=t?"#FAFAFA":"#18181B";return De(Mt,{style:[K.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[N(Mt,{style:[K.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?N(Dr,{source:{uri:e.icon},style:K.splash_icon_image}):N(Le,{style:K.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),N(Le,{style:[K.splash_name,{color:o}],children:e.name}),n==="error"?De(Pn,{children:[N(Le,{style:K.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),N(Ur,{activeOpacity:.7,style:[K.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:i,children:N(Le,{style:[K.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):De(Pn,{children:[N(Ir,{style:K.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&De(Le,{style:K.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},En=(e,t)=>{let n=Z(t),r=Z(!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.`))},jr=({container:e,splash:t=Rn,is_dark:n=!1,bridge:r,close_on_back:i=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{En("container",e),En("splash",t);let a=e,s=ee(B,f=>f.active_key),d=Z(s);s&&(d.current=s);let g=ee(B,f=>Object.keys(f.instances).join("|")),A=ee(B,f=>{var C;return f.active_key?(C=f.instances[f.active_key])==null?void 0:C.app.name:void 0}),l=Qe(()=>g?g.split("|"):[],[g]),[h,E]=Me({}),S=Z($r()).current;V(()=>{if(!s||!i)return;let f=Lr.addEventListener("hardwareBackPress",()=>(Ce(),!0));return()=>f.remove()},[s,i]);let _=yt(()=>{let f=B.getState().active_key;f&&E(C=>({...C,[f]:(C[f]||0)+1}))},[]);return l.length?N(a,{visible:!!s,title:A!=null?A:"",is_dark:n,close:Ce,reload:_,subscribeWebAtTop:S.subscribe,children:l.map(f=>N(Br,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:S,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},K=St.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),zr=vt.memo(jr);export{Rn as DefaultMiniAppSplash,et as MINIAPP_PLATFORM_URL,zr as MiniAppHost,u as MiniAppHostError,Ce as closeMiniApp,Tn as configureMiniApp,kn as createMmkvStorage,Rt as createReactNativeBiometrics,Cn as createRnfsFileSystem,Ge as ensureMiniApp,P as getLocalMiniApp,kr as getMiniAppCatalog,Ie as getMiniAppCatalogEntry,Sr as getMiniAppStatuses,_n as getMiniAppUpdate,ar as installBundledMiniApp,vr as onMiniAppEvent,dr as openMiniApp,Pr as pauseMiniApp,Or as pauseMiniAppDownloads,gr as preloadMiniApp,ie as releaseSpeechFor,Er as restoreMiniApp,Rr as resumeMiniApp,Tr as resumeMiniAppDownloads,pr as sendEventToWeb,ht as syncMiniAppCatalog,xr as uninstallMiniApp,Cr as updateMiniApp,Bt as uploadToUrl,ft as useMiniAppDownload,Mr as useMiniAppDownloadsPaused};
|
|
66
|
+
true;`},gn={partner:"partner_token",chatbox:"chatbox_token"},mn=(e,t)=>{let n={...e};for(let i of Object.values(gn))t.includes(i)||delete n[i];return n},ot=new Set,Pe=async(e,t)=>{if(ot.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);ot.add(e);try{return await t()}finally{ot.delete(e)}},ai=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),qe=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},fn=async({method:e,params:t},{getHostData:n,getPermissions:i,getContext:r,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var E,S,_,f,C,Y,N,ve,ae;let y=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let A=Ot(t);return Pe(e,()=>Tt(A,g))}case"speech.start":{if(!d)throw h();let A={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");A.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new u("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);A[v]=t[v]}return Xt(a,A,d,g)}case"speech.stop":return Zt(a);case"uploadFiles":{let{task_id:A,...v}=t!=null?t:{};if(A!==void 0&&(typeof A!="string"||!A))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Yt($t(v),{instance_id:a,app_id:p,getContext:r,task_id:A,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>Pe("uploadFiles.pick",j)})}case"uploadFiles.cancel":Kt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Wt(s==null?void 0:s.upload);case"getBiometricAvailability":return((E=s==null?void 0:s.biometrics)!=null?E:await tt()).getAvailability();case"authenticateBiometric":{let A=qe(t==null?void 0:t.reason,"reason").trim();if(!A||A.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Pe(e,async()=>{var M;return((M=s==null?void 0:s.biometrics)!=null?M:await tt()).authenticate({reason:A,cancelButtonText:v})})}case"requestPayment":{let A=y==null?void 0:y.requestPayment;if(!A)throw h();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:v,currency:qe(t==null?void 0:t.currency,"currency")};return Pe(e,()=>A(j,l))}case"printImage":{let A=y==null?void 0:y.printImage;if(!A)throw h();let v=qe(t==null?void 0:t.image,"image");await Pe(e,()=>A({image:v},l));return}case"openScreen":if(!(y!=null&&y.openScreen))throw h();await y.openScreen({screen:qe(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let A=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(A))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(A):en.openURL(A));return}case"openLink":{let A=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(A)||/^(javascript|file|data|about|blob):/i.test(A))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(A):en.openURL(A))}catch(v){throw new u("NOT_SUPPORTED",String((C=(f=v==null?void 0:v.message)!=null?f:v)!=null?C:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(N=s==null?void 0:s.showToast)==null||N.call(s,String((Y=t==null?void 0:t.message)!=null?Y:""));return;case"haptic":{let A=ai.has(t==null?void 0:t.type)?t.type:"selection";(ve=s==null?void 0:s.haptic)==null||ve.call(s,A);return}case"getSystemInfo":return{platform:si.OS==="ios"?"ios":"android",appVersion:(ae=s==null?void 0:s.app_version)!=null?ae:"",theme:o?"dark":"light"};case"getAccessToken":{let A=n().access_token;if(!A)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return A}case"getToken":{let A=t==null?void 0:t.type;if(A==="access"){let M=n().access_token;if(!M)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return M}if(A!=="partner"&&A!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(A)}`);let v=gn[A];if(!i().includes(v))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=A==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return j}case"getUserInfo":{let A=n().user;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return A}case"getPageInfo":{let A=n().page;if(!A)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return A}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ct=e=>`bundle:${e}`,pt=()=>`${O().file_system.document_dir}/miniapps`,lt=pt,ut=(e,t,n="index.html",i=!1,r=[])=>{let o=`${lt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:i,permissions:r}},at=e=>{var t;O().storage.setString(ct(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ci=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,P=e=>{let t=O().storage.getString(ct(e));if(!t)return null;try{let{version:n,entry:i,context_update:r,permissions:o}=JSON.parse(t);return ut(e,n,i,!!r,Array.isArray(o)?o:[])}catch{return null}},oe=e=>O().file_system.exists(e.entry_uri.replace("file://","")),dt=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await oe(t)},yn=async(e,t)=>{let n=O().file_system,i=`${lt()}/${e}`,r=await n.listDir(i).catch(()=>[]);await Promise.all(r.filter(o=>!t.includes(o)).map(o=>n.remove(`${i}/${o}`).catch(()=>{})))},An=async e=>{var t;await((t=Te[e])==null?void 0:t.catch(()=>{})),O().storage.setString(ct(e),""),await O().file_system.remove(`${lt()}/${e}`).catch(()=>{})},Se=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Te={},wn=(e,t)=>{var o;let i=((o=Te[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),r=i.catch(()=>{});return Te[e]=r,r.then(()=>{Te[e]===r&&delete Te[e]}),i},pi=(e,t)=>{var r,o;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let p=((r=n[c])!=null?r:0)-((o=i[c])!=null?o:0);if(p)return p}return 0},li=({manifest:e,zip_path:t})=>wn(e.app_id,async()=>{var o;let n=O().file_system,i=P(e.app_id);if(i&&pi(i.version,e.version)>=0&&await oe(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=ut(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),at(e),W("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),yn(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),r}),gt=(e,{base_url:t,onProgress:n}={})=>{let i=O().file_system,r=null,o=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new Se},a=async()=>{var g;p();let s=P(e.app_id);if((s==null?void 0:s.version)===e.version&&await i.exists(s.dir))return at(e),P(e.app_id);p();let d=i.download({url:t?ci(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(y,l)=>{var E;let h=l>0?l:(E=e.size)!=null?E:0;h>0&&(n==null||n(Math.min(1,y/h)))}});r=d;try{let{status:y}=await d.promise;if(p(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else W("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ut(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await i.remove(l.dir).catch(()=>{}),await i.mkdir(l.dir),await i.unzip(c,l.dir),at(e),yn(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(y){throw o?new Se:y}finally{r=null,i.remove(c).catch(()=>{})}};return{promise:wn(e.app_id,a),cancel:()=>{o=!0,r==null||r.cancel()}}},Oe={},ui=__DEV__?0:60*1e3,hn={},Mn=(e,t)=>{var i,r;let n=P(e);return n&&Date.now()-((i=hn[t])!=null?i:0)<ui?Promise.resolve(n):((r=Oe[e])!=null||(Oe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await gt(c,{base_url:t}).promise;return hn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{Oe[e]=void 0})),Oe[e])};var je=new Map,vn=(e,t)=>(je.set(e,t),()=>{je.get(e)===t&&je.delete(e)}),di=(e,t)=>{let n=je.get(e);return n?n(t):!1};import{useRef as gi,useSyncExternalStore as mi}from"react";var ze=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let r=typeof i=="function"?i(t):i;t={...t,...r},n.forEach(o=>o())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},ee=(e,t,n=Object.is)=>{let i=gi(null),r=()=>{let o=e.getState(),c=i.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return i.current={state:o,selector:t,value:a},a};return mi(e.subscribe,r)};var B=ze({active_key:null,instances:{}}),Sn=({app:e,instance_id:t,context:n={},url_params:i={},host_data:r={}},o)=>{var p;let c=(p=O().keep_alive)==null?void 0:p.max_webviews;B.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:i,host_data:r,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(y=>y!==s).sort((y,l)=>d[y].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(y=>{delete d[y]}),o?{active_key:s,instances:d}:{instances:d}})},fi=e=>Sn(e,!0),hi=e=>Sn(e,!1),Ce=()=>B.setState({active_key:null}),He=e=>{B.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var _n="catalog",yi="paused_apps",Ai="removed_apps",wi=10*1e3,Mi=2,vi=3e3,Si=()=>{var e;try{return JSON.parse((e=O().storage.getString(_n))!=null?e:"{}")}catch{return{}}},x=ze({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),bn=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},Ke=new Set,xn=e=>{let t=new Set,n=()=>O().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let r=JSON.parse((i=O().storage.getString(e))!=null?i:"[]");Array.isArray(r)&&r.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},X=xn(yi),ge=xn(Ai);Pt(()=>{X.load(),ge.load();let e=Si(),t={};Object.keys(e).filter(n=>!ge.has(n)).forEach(n=>{let i=P(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:X.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),x.setState({catalog:e,downloads:t})});var ft=e=>ee(x,t=>e?t.downloads[e]:void 0),_i=()=>ee(x,e=>e.pause_reasons.length>0),Q=(...e)=>W("queue",...e),L=[],se={},b=null,We=new Set,we={},mt=new Set,ue=e=>{mt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},bi=e=>(mt.add(e),()=>{mt.delete(e)}),xi=()=>x.getState().downloads,q=(e,t)=>{let n=!!P(e),i=x.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,o={...i!=null?i:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};x.setState(c=>({downloads:{...c.downloads,[e]:o}})),(i==null?void 0:i.status)!==o.status||(i==null?void 0:i.version)!==o.version||(i==null?void 0:i.has_local)!==o.has_local?ue({type:"status_change",app_id:e,state:o}):i.progress!==o.progress&&ue({type:"progress",app_id:e,progress:o.progress,version:o.version})},Je=(e,t)=>{var n;(n=we[e])==null||n.forEach(i=>i(t)),delete we[e]},Ei=()=>x.getState().pause_reasons.length>0,de=e=>{var p;if(b)return;let t=e?L.indexOf(e):Ei()?-1:L.findIndex(a=>!X.has(a));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),i=x.getState().catalog[n];if(!i){Je(n,P(n)),de();return}let r=Date.now();se[n]=((p=se[n])!=null?p:0)+1,q(n,{status:"downloading",progress:0,version:i.version,error:void 0});let o=0,c=gt(i,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,q(n,{progress:s/100,version:i.version}))}});b={app_id:n,handle:c,forced:!!e},Q("start",n,i.version,e?"(forced)":""),c.promise.then(a=>{Q("installed",n,i.version,`${Date.now()-r}ms`),q(n,{status:"installed",progress:1,version:i.version}),Je(n,a)}).catch(a=>{var d;if(a instanceof Se){if(We.has(n))return;Q("paused",n),se[n]-=1,L.unshift(n),q(n,{status:X.has(n)?"paused":"queued",progress:0,version:i.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),se[n]<Mi){q(n,{status:"queued",progress:0,version:i.version,error:s}),setTimeout(()=>{var g;L.includes(n)||(b==null?void 0:b.app_id)===n||(L.push(n),de((g=we[n])!=null&&g.length?n:void 0))},vi);return}q(n,{status:"failed",progress:0,version:i.version,error:s}),Je(n,P(n))}).finally(()=>{b=null;let a=L.find(s=>{var d;return(d=we[s])==null?void 0:d.length});de(a)})},Ye=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},Pi=async e=>{let{host_id:t,client_token:n}=O(),i=new AbortController,r=setTimeout(()=>i.abort(),wi);try{let o=`${et}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(r)}},Ie=null,ht=()=>(Ie!=null||(Ie=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(Pi)),i={};[...n].reverse().flat().forEach(a=>{i[a.app_id]=a});let r=Object.keys(x.getState().catalog).filter(a=>!i[a]);O().storage.setString(_n,JSON.stringify(i)),x.setState({catalog:i}),await Promise.all(r.map(a=>En(a,{by_user:!1}))),r.forEach(a=>ge.delete(a));let o=Object.keys(i).filter(a=>!ge.has(a)),c=[],p={};for(let a of o.map(s=>i[s])){if(await dt(a)){q(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=P(a.app_id);if(bn(a.app_id)&&!Ke.has(a.app_id)&&s&&await oe(s)){q(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return x.setState({updates:p}),c.forEach(a=>{se[a.app_id]=0,q(a.app_id,{status:X.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),Ye(a.app_id)}),Q("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",r,`${Date.now()-e}ms`),ue({type:"sync_complete",app_ids:o,removed:r}),Object.values(p).forEach(a=>ue({type:"update_available",...a})),de(),{ok:!0,app_ids:o,removed:r}}catch(n){let i=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",i),ue({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{Ie=null}})()),Ie),En=async(e,{by_user:t})=>{var r,o,c,p;if(t&&ge.add(e),We.has(e))return;We.add(e),X.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let i=(p=(c=(r=x.getState().downloads[e])==null?void 0:r.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?p:"";q(e,{status:"uninstalling",progress:0,version:i}),await An(e),He(e),x.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete se[e],We.delete(e),Je(e,null),Q("uninstalled",e,t?"(user)":"(not in list)"),ue({type:"uninstalled",app_id:e})},Ri=e=>En(e,{by_user:!0}),Oi=e=>{let t=ke(e);return t?(ge.delete(e),(b==null?void 0:b.app_id)===e||L.includes(e)||(se[e]=0,q(e,{status:X.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ye(e),de(),Q("restore",e)),!0):!1},Ti=e=>{if(X.has(e))return;if(X.add(e),Q("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=x.getState().downloads[e];L.includes(e)&&t&&q(e,{status:"paused",progress:0,version:t.version})},Ci=e=>{if(!X.delete(e))return;Q("resume app",e);let t=x.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&ke(e)&&(se[e]=0,Ye(e)),L.includes(e)&&t&&q(e,{status:"queued",progress:0,version:t.version}),de()},Ii=e=>{let{pause_reasons:t}=x.getState();t.includes(e)||(x.setState({pause_reasons:[...t,e]}),Q("pause",e),t.length===0&&ue({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},ki=e=>{let{pause_reasons:t}=x.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);x.setState({pause_reasons:n}),Q("resume",e),n.length===0&&ue({type:"pause_change",paused:!1,reasons:n}),de()},Pn=e=>x.getState().updates[e],Li=async e=>{var n,i;let t=Pn(e);Ke.add(e);try{let r=await Ge(e),o=(i=t==null?void 0:t.next_version)!=null?i:(n=ke(e))==null?void 0:n.version;return!r||!o||r.version!==o?!1:(x.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),Q("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Ke.delete(e)}},Di=()=>Object.values(x.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:ge.has(e.app_id)})),ke=e=>x.getState().catalog[e],Ge=async e=>{let t=ke(e);if(!t)return;if(X.delete(e),ge.delete(e),await dt(t))return P(e);let n=P(e);if(bn(e)&&!Ke.has(e)&&n&&await oe(n))return n;let i=new Promise(r=>{var o;((o=we[e])!=null?o:we[e]=[]).push(r)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(se[e]=0,Ye(e,{front:!0}),b&&!b.forced?b.handle.cancel():de(e)),i};import{Fragment as Cn,jsx as U,jsxs as De}from"react/jsx-runtime";var At=e=>(e!=null?e:"").replace(/\?[^#]*/,""),On=0,Vi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},ji=vt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:r,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var _t,bt;let g=Z(null),y=Z(!1),l=ee(B,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,E=l==null?void 0:l.app.manifest_url,S=l==null?void 0:l.context,_=l==null?void 0:l.url_params,[f,C]=Me(()=>h?P(h):null),[Y,N]=Me(!1),[ve,ae]=Me(0),[A,v]=Me(0),[j,M]=Me(!1),I=Z(null),te=m=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,M(!0)},m)};V(()=>()=>{I.current&&clearTimeout(I.current)},[]),V(()=>{if(!h||!t&&f)return;let m=!0;return N(!1),(async()=>{let w=P(h),$=w?await oe(w):!1;if(!m||(C($?G=>!G||G.version!==w.version||G.permissions.join(",")!==w.permissions.join(",")?w:G:null),__DEV__&&Date.now()-On>1e4&&(On=Date.now(),await ht()),!m))return;let pe=await Ge(h),fe=pe!==void 0?pe:E?await Mn(h,E):P(h);if(m){if(!fe){N(!0);return}C(G=>G!=null?G:fe)}})(),()=>{m=!1}},[t,h,E,ve]),V(()=>vn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let F=ee(x,m=>{let w=h?m.downloads[h]:void 0;return(w==null?void 0:w.status)==="installed"?w.version:void 0});V(()=>{if(t||!h||!f)return;let m=P(h);if(!m||m.version===f.version)return;let w=!0;return oe(m).then($=>{!w||!$||(W(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),C(m))}),()=>{w=!1}},[t,h,F,f==null?void 0:f.version]);let R=ee(x,m=>{var w;return h&&(w=m.apply_ticks[h])!=null?w:0});V(()=>{if(!R||!h)return;let m=P(h);if(!m||m.version===(f==null?void 0:f.version))return;let w=!0;return oe(m).then($=>{!w||!$||(W(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),M(!1),C(m))}),()=>{w=!1}},[R]),V(()=>{var $;let m=($=O().keep_alive)==null?void 0:$.idle_close_ms;if(t||!m||m<=0)return;let w=setTimeout(()=>{He(e)},m);return()=>clearTimeout(w)},[t,e]),V(()=>{r>0&&(N(!1),M(!1),v(m=>m+1),ae(m=>m+1))},[r]);let z=Z(t);V(()=>{var m;z.current!==t&&(z.current=t,y.current&&((m=g.current)==null||m.injectJavaScript(pn(t?"resumed":"paused"))))},[t]);let ce=`${(_t=f==null?void 0:f.version)!=null?_t:"none"}:${(bt=f==null?void 0:f.permissions.join(","))!=null?bt:""}:${A}`,me=Qe(()=>JSON.stringify([S!=null?S:{},_!=null?_:{}]),[S,_]),ne=Qe(()=>{var m;return mn(_!=null?_:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[me,f==null?void 0:f.permissions]),Xe=Qe(()=>dn(S!=null?S:{},ne)+an()+($i.OS==="android"?cn():"")+(O().debug?sn():""),[ne]),ie=Z(null),Ue=Z(null);V(()=>{var w,$,pe;if(!f)return;if(Ue.current!==ce){Ue.current=ce,ie.current=me;return}if(ie.current===me)return;let m=(($=JSON.parse((w=ie.current)!=null?w:"[]")[0])!=null?$:{}).org_id;if(ie.current=me,m===(S==null?void 0:S.org_id)&&y.current){M(!1),te(1500),(pe=g.current)==null||pe.injectJavaScript(ln(S!=null?S:{},ne));return}M(!1),v(fe=>fe+1)},[me,f,ce]),V(()=>(t||(re(e),Ae(e)),()=>{re(e),Ae(e)}),[t,e,ce,r]),V(()=>{let m=Rn.addEventListener("change",w=>{w==="background"&&!Qt()&&re(e)});return()=>m.remove()},[e]);let Ne=wt(async m=>{var $,pe,fe,G,Ze;let w=tn(m.nativeEvent.data);if(!w){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(T=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)})}catch(T){console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)}return}if(w.method==="log"){let{level:T,text:D}=w;W(`web:${e}`,T!=null?T:"log",D!=null?D:"");return}if(w.method==="pong"){I.current||M(!0);return}if(w.method==="touchAtTop"){o.emit(!!w.at_top);return}if(w.method==="contextApplied"){I.current&&clearTimeout(I.current),I.current=null,M(!0);return}if(w.method==="ready"){y.current=!0,M(!0);let T=($=B.getState().instances[e])==null?void 0:$.context;T&&((pe=g.current)==null||pe.injectJavaScript(st(T)));return}try{let T=await fn(w,{getHostData:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.host_data)!=null?H:{}},getPermissions:()=>{var D,H;return h?(H=(D=P(h))==null?void 0:D.permissions)!=null?H:[]:[]},getContext:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.context)!=null?H:{}},is_dark:i,close:Ce,app_id:h!=null?h:"",instance_id:e,options:p,emit:(D,H)=>{var xt;(xt=g.current)==null||xt.injectJavaScript(on(D,H))},isActive:()=>B.getState().active_key===e&&Rn.currentState!=="background"});w.id&&((fe=g.current)==null||fe.injectJavaScript(nn(w.id,T)))}catch(T){if(!w.id)return;let D=T==null?void 0:T.code,H=T instanceof u?T:new u(typeof D=="string"?D:"HOST_ERROR",String((G=T==null?void 0:T.message)!=null?G:T));(Ze=g.current)==null||Ze.injectJavaScript(rn(w.id,H))}},[e,i,h,o,p]),kn=wt(()=>{N(!1),v(m=>m+1),ae(m=>m+1)},[]);return De(Mt,{style:[St.absoluteFill,a&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&K.behind],pointerEvents:t?"auto":"none",children:[f?U(qi,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?pt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Xe,onMessage:Ne,bounces:!1,overScrollMode:"never",onLoadStart:m=>{re(e),Ae(e),W(`webview:${e}`,"load start",At(m.nativeEvent.url)),y.current=!1,M(!1)},onError:m=>{re(e),Ae(e),W(`webview:${e}`,"load error",At(m.nativeEvent.url),m.nativeEvent.description),N(!0),M(!1)},onLoadEnd:m=>{let w=m.nativeEvent.url;W(`webview:${e}`,"load end",At(w)),h&&(d==null||d({app_id:h,instance_id:e,url:w})),te(1500)},onContentProcessDidTerminate:()=>{re(e),Ae(e),y.current=!1,M(!1),v(m=>m+1)},onRenderProcessGone:()=>(re(e),Ae(e),y.current=!1,M(!1),v(m=>m+1),!0),style:K.webview},ce):null,l&&U(Hi,{visible:!f||!j,interactive:Y,children:U(zi,{splash:c,app:l.app,is_dark:i,error:Y,has_bundle:!!f,retry:kn})})]})}),zi=vt.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:r,retry:o})=>{let c=e,p=ft(t.app_id),a=i?"error":!r&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return U(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Hi=({visible:e,interactive:t,children:n})=>{let i=Z(new yt.Value(e?1:0)).current,[r,o]=Me(e);return V(()=>{if(e){o(!0),i.setValue(1);return}let c=yt.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,i]),r?U(yt.View,{style:[St.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},In=({app:e,is_dark:t,status:n,progress:i,retry:r})=>{let o=t?"#FAFAFA":"#18181B";return De(Mt,{style:[K.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[U(Mt,{style:[K.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?U(Fi,{source:{uri:e.icon},style:K.splash_icon_image}):U(Le,{style:K.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),U(Le,{style:[K.splash_name,{color:o}],children:e.name}),n==="error"?De(Cn,{children:[U(Le,{style:K.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),U(Bi,{activeOpacity:.7,style:[K.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:U(Le,{style:[K.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):De(Cn,{children:[U(Ui,{style:K.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&De(Le,{style:K.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},Tn=(e,t)=>{let n=Z(t),i=Z(!1);__DEV__&&!i.current&&n.current!==t&&(i.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Wi=({container:e,splash:t=In,is_dark:n=!1,bridge:i,close_on_back:r=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Tn("container",e),Tn("splash",t);let a=e,s=ee(B,f=>f.active_key),d=Z(s);s&&(d.current=s);let g=ee(B,f=>Object.keys(f.instances).join("|")),y=ee(B,f=>{var C;return f.active_key?(C=f.instances[f.active_key])==null?void 0:C.app.name:void 0}),l=Qe(()=>g?g.split("|"):[],[g]),[h,E]=Me({}),S=Z(Vi()).current;V(()=>{if(!s||!r)return;let f=Ni.addEventListener("hardwareBackPress",()=>(Ce(),!0));return()=>f.remove()},[s,r]);let _=wt(()=>{let f=B.getState().active_key;f&&E(C=>({...C,[f]:(C[f]||0)+1}))},[]);return l.length?U(a,{visible:!!s,title:y!=null?y:"",is_dark:n,close:Ce,reload:_,subscribeWebAtTop:S.subscribe,children:l.map(f=>U(ji,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:S,splash:t,bridge:i,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},K=St.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),Ji=vt.memo(Wi);export{In as DefaultMiniAppSplash,et as MINIAPP_PLATFORM_URL,Ji as MiniAppHost,u as MiniAppHostError,Ce as closeMiniApp,Ln as configureMiniApp,Un as createMmkvStorage,Rt as createReactNativeBiometrics,Dn as createRnfsFileSystem,Ge as ensureMiniApp,P as getLocalMiniApp,Di as getMiniAppCatalog,ke as getMiniAppCatalogEntry,xi as getMiniAppStatuses,Pn as getMiniAppUpdate,li as installBundledMiniApp,bi as onMiniAppEvent,fi as openMiniApp,Ti as pauseMiniApp,Ii as pauseMiniAppDownloads,hi as preloadMiniApp,re as releaseSpeechFor,Oi as restoreMiniApp,Ci as resumeMiniApp,ki as resumeMiniAppDownloads,di as sendEventToWeb,ht as syncMiniAppCatalog,Ri as uninstallMiniApp,Li as updateMiniApp,zt as uploadToUrl,ft as useMiniAppDownload,_i as useMiniAppDownloadsPaused};
|
package/docs/MINIAPP_README.md
CHANGED
|
@@ -882,7 +882,7 @@ Web chờ tối đa khoảng 2 phút + `timeout` (gồm thời gian người dù
|
|
|
882
882
|
```ts
|
|
883
883
|
import { uploadFiles, getUploadCapabilities } from '@retion-miniapp/sdk';
|
|
884
884
|
|
|
885
|
-
const { sources, targets } = await getUploadCapabilities(); // vd ['library','camera','document'], ['url','host']
|
|
885
|
+
const { sources, targets, file_types } = await getUploadCapabilities(); // vd ['library','camera','document'], ['url','host'], { library: [{ type: 'image', label: 'Ảnh', accept: ['image/*'] }, ...] }
|
|
886
886
|
|
|
887
887
|
const controller = new AbortController();
|
|
888
888
|
const { files, failed } = await uploadFiles({
|
package/docs/NATIVE_APIS.md
CHANGED
|
@@ -395,7 +395,7 @@ const BRIDGE: MiniAppBridgeOptions = {
|
|
|
395
395
|
```ts
|
|
396
396
|
import { uploadFiles, getUploadCapabilities } from '@retion-miniapp/sdk';
|
|
397
397
|
|
|
398
|
-
const { sources, targets } = await getUploadCapabilities(); // vd ['library','camera','document'], ['url','host']
|
|
398
|
+
const { sources, targets, file_types } = await getUploadCapabilities(); // vd ['library','camera','document'], ['url','host'], { library: [{ type: 'image', label: 'Ảnh', accept: ['image/*'] }, ...] }
|
|
399
399
|
|
|
400
400
|
const controller = new AbortController();
|
|
401
401
|
const { files, failed } = await uploadFiles({
|