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