@retion-miniapp/react-native 0.23.1 → 0.23.2

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 CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Fi=Object.create;var sn=Object.defineProperty;var Li=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Ui=Object.prototype.hasOwnProperty;var Vi=(e,t)=>{for(var n in t)sn(e,n,{get:t[n],enumerable:!0})},Io=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Di(t))!Ui.call(e,r)&&r!==n&&sn(e,r,{get:()=>t[r],enumerable:!(o=Li(t,r))||o.enumerable});return e};var he=(e,t,n)=>(n=e!=null?Fi(Ni(e)):{},Io(t||!e||!e.__esModule?sn(n,"default",{value:e,enumerable:!0}):n,e)),Bi=e=>Io(sn({},"__esModule",{value:!0}),e);var ia={};Vi(ia,{AGENT_BRIDGE_VERSION:()=>Dn,AGENT_MESSAGE_EVENT:()=>Ao,AGENT_PAYLOAD_META_EVENT:()=>Mo,AGENT_PAYLOAD_META_RESULT_EVENT:()=>vo,AGENT_STOPPED_EVENT:()=>So,CodeType:()=>pe,DEFAULT_MINIAPP_UPDATES_LABELS:()=>Bn,DefaultMiniAppChangelogHistoryModal:()=>Zt,DefaultMiniAppChangelogPrompt:()=>Xt,DefaultMiniAppSplash:()=>Po,DefaultMiniAppUpdatePrompt:()=>Qt,MINIAPP_CHANGELOG_KINDS:()=>qn,MINIAPP_PLATFORM_URL:()=>ht,MiniAppChangelogGroups:()=>pt,MiniAppChangelogHistory:()=>Et,MiniAppChangelogText:()=>zn,MiniAppHost:()=>Ci,MiniAppHostError:()=>f,MiniAppUpdates:()=>Ii,MiniAppUpdatesThemeProvider:()=>ct,ScannerEndReason:()=>lt,ScannerEvent:()=>kn,ScannerLayout:()=>Se,ScannerMethod:()=>St,ToastType:()=>ve,closeMiniApp:()=>mt,closeMiniAppChangelogHistory:()=>Cn,configureMiniApp:()=>Lo,createMmkvStorage:()=>No,createReactNativeBiometrics:()=>Gn,createRnfsFileSystem:()=>Do,dismissMiniAppChangelog:()=>Mn,ensureMiniApp:()=>Nt,fetchMiniAppChangelog:()=>Vt,getLocalMiniApp:()=>$,getMiniAppCatalog:()=>Er,getMiniAppCatalogEntry:()=>bt,getMiniAppChangelogSeen:()=>wn,getMiniAppIdByAgentId:()=>mi,getMiniAppStatuses:()=>_r,getMiniAppUpdate:()=>ao,getPendingChangelog:()=>An,installBundledMiniApp:()=>pr,markMiniAppChangelogSeen:()=>wt,mergeMiniAppChangelog:()=>Yt,onMiniAppEvent:()=>mn,openMiniApp:()=>gr,parseInlineMarkdown:()=>Jt,pauseMiniApp:()=>Mr,pauseMiniAppDownloads:()=>xr,preloadMiniApp:()=>hr,releaseSpeechFor:()=>Ne,resolveMiniAppUpdatesTheme:()=>Kt,restoreMiniApp:()=>Sr,resumeMiniApp:()=>vr,resumeMiniAppDownloads:()=>Cr,sendEventToWeb:()=>In,showMiniAppChangelog:()=>_t,showMiniAppChangelogHistory:()=>xn,stripInlineMarkdown:()=>Ei,syncMiniAppCatalog:()=>bn,uninstallMiniApp:()=>Ar,updateMiniApp:()=>_n,uploadToUrl:()=>Xn,useMiniAppChangelog:()=>Sn,useMiniAppChangelogHistoryRequest:()=>En,useMiniAppChangelogRequest:()=>vn,useMiniAppDownload:()=>yt,useMiniAppDownloadsPaused:()=>br,useMiniAppUpdatesTheme:()=>Pe});module.exports=Bi(ia);var ht="https://retion-miniapp-platform.vercel.app",rt=null,Fo=new Set,Lo=e=>{rt=e,Fo.forEach(t=>t())},U=()=>{if(!rt)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return rt},an=e=>{Fo.add(e),rt&&e()},ye=(...e)=>{rt!=null&&rt.debug&&console.log("[miniapp]",...e)};var Do=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:l}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:s,contentLength:c})=>r==null?void 0:r(s,c)});return{promise:l.then(({statusCode:s})=>({status:s})),cancel:()=>e.stopDownload(i)}}}),No=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var M=he(require("react")),F=require("react-native"),xi=he(require("react-native-webview"));var qt=require("react-native");var Gn=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),ln,Jn=()=>(ln||(ln=import("react-native-biometrics").then(({default:e})=>Gn(new e({allowDeviceCredentials:!1}))).catch(e=>{throw ln=void 0,new f("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),ln);var Le=require("react-native");var Uo=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new f("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new f("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,l,s]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<l||c>s))throw new f("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${l}\u2013${s} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Vo=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,a)=>{r||(r=!0,clearTimeout(l),c?o(c):n(a))},l=setTimeout(()=>i(new f("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),s=()=>r?!1:t()?!0:(i(new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!s())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(s()){if(Le.Platform.OS==="android"){let a=Le.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,p=Le.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await Le.PermissionsAndroid.check(a);if(!s())return;let m=d||await Le.PermissionsAndroid.check(p);if(!s())return;if(!d&&!m){let u=await Le.PermissionsAndroid.requestMultiple([a,p]);if(!s())return;if(u[a]!==Le.PermissionsAndroid.RESULTS.GRANTED&&u[p]!==Le.PermissionsAndroid.RESULTS.GRANTED)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}s()&&c.getCurrentPosition(a=>{s()&&i(void 0,a)},a=>{var d;if(!s())return;let p=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[a.code])!=null?d:"LOCATION_ERROR";i(new f(p,a.message))},e)}})().catch(c=>i(c))});var Yn=require("react-native");var Kn=20,Bo=20,jo=/^[a-z][a-z0-9_-]{0,31}$/,Hi=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,qi=["low","medium","high"],Ke=e=>!!e&&typeof e=="object"&&!Array.isArray(e),se=e=>new f("INVALID_PARAMS",e),Ot=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ho=(e,t)=>{if(e===void 0)return{};if(!Ke(e)||Object.keys(e).length>Bo||Object.values(e).some(n=>typeof n!="string"))throw se(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Bo} key)`);return e},Go=e=>{var n,o,r,i;if(e!==void 0&&!Ke(e))throw se("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!jo.test(t.source)))throw se("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(l=>typeof l!="string"||!Hi.test(l))))throw se("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ot(t.max_count,1,Kn))throw se(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Kn}`);if(t.max_size!==void 0&&!Ot(t.max_size,1,Number.MAX_SAFE_INTEGER))throw se("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ot(t.concurrency,1,5))throw se("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(l=>l.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:zi(t.process),target:$i(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},zi=e=>{if(e===void 0)return{};if(!Ke(e))throw se("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Ke(n))throw se("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Ot(n[o],1,1e4))throw se(`process.image.${o} 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 se("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(!Ke(n))throw se("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ot(n.max_duration,1,3600))throw se("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!qi.includes(n.quality))throw se("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},$i=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Ke(e))throw se("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!jo.test(t))throw se("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Ke(e.params))throw se("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw se("upload.url ph\u1EA3i l\xE0 https");for(let l of["field_name","url_field"])if(e[l]!==void 0&&(typeof e[l]!="string"||!e[l]))throw se(`upload.${l} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Ho(e.headers,"upload.headers"),form_data:Ho(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},Jo=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Wi=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=Jo(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},ji=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},Pt,Gi=()=>(Pt!=null||(Pt=import("react-native-image-picker").catch(e=>{throw Pt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Pt),qo=e=>async({accept:t,max_count:n,process:o})=>{var c,a,p,d,m,u,S,v,D;let r=await Gi(),i=ji(t),l={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(a=o.image)==null?void 0:a.max_height,quality:(d=(p=o.image)==null?void 0:p.quality)!=null?d:.8,videoQuality:(u=(m=o.video)==null?void 0:m.quality)!=null?u:"medium",durationLimit:(S=o.video)==null?void 0:S.max_duration,assetRepresentationMode:"compatible"},s=e==="camera"?await r.launchCamera({...l,saveToPhotos:!1}):await r.launchImageLibrary({...l,selectionLimit:n});if(s.didCancel)return[];if(s.errorCode){let C=s.errorCode==="permission"?"PERMISSION_DENIED":s.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new f(C,(v=s.errorMessage)!=null?v:s.errorCode)}return((D=s.assets)!=null?D:[]).filter(C=>C.uri).map((C,x)=>{var j,A,G;return{uri:C.uri,name:(j=C.fileName)!=null?j:`file_${x+1}`,mime_type:(A=C.type)!=null?A:"application/octet-stream",size:C.fileSize,width:C.width,height:C.height,duration:C.duration,processed:!((G=C.type)!=null&&G.startsWith("video/"))||Yn.Platform.OS==="ios"}})},Ji={"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"},Ki={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Yi=e=>async({accept:t,max_count:n})=>{var i,l,s,c;let o=t.map(a=>{var p;return(p=Ji[a])!=null?p:Ki[a]}),r=!t.length||o.some(a=>!a||!e.types[a])?e.types.allFiles:[...new Set(o)].flatMap(a=>e.types[a]);try{let p=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,S)=>{var v,D,C;return{uri:u.uri,name:(v=u.name)!=null?v:`file_${S+1}`,mime_type:(D=u.type)!=null?D:"application/octet-stream",size:(C=u.size)!=null?C:void 0}});if(Yn.Platform.OS!=="android"||!e.keepLocalCopy||!p.some(u=>u.uri.startsWith("content://")))return p;let d=await e.keepLocalCopy({files:p.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),m=new Map(d.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return p.map(u=>{var S;return{...u,uri:(S=m.get(u.uri))!=null?S:u.uri}})}catch(a){let p=a==null?void 0:a.code;if(p===((l=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?l:"OPERATION_CANCELED"))return[];throw p===((c=(s=e.errorCodes)==null?void 0:s.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new f("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):a}},kt,Xi=async e=>(kt!=null||(kt=import("@react-native-documents/picker").then(t=>Yi(t)).catch(t=>{throw kt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await kt)(e)),Ko={library:qo("library"),camera:qo("camera"),document:Xi},zo={type:"image",label:"\u1EA2nh",accept:["image/*"]},$o={type:"video",label:"Video",accept:["video/*"]},Wo={library:[zo,$o],camera:[zo,$o],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},Rt,Yo=()=>(Rt!=null||(Rt=import("react-native-compressor").catch(()=>(Rt=void 0,null))),Rt),Xo=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Qi=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Zi={low:640,medium:1280,high:1920},es=async(e,{image:t})=>{var o;if(!t||!Qi.has(e.mime_type.toLowerCase()))return e;let n=await Yo();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Xo(n,r,e.size),processed:!0}}catch{return e}},ts=async(e,{video:t})=>{var o;let n=await Yo();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Zi[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Xo(n,r,e.size),processed:!0}}catch{return e}},ns={image:es,video:ts},os=(e,t)=>t.split(".").reduce((n,o)=>Ke(n)?n[o]:void 0,e),Xn=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new f("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let l=t;if(o.aborted){i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let s=new XMLHttpRequest,c=new FormData;Object.entries(l.form_data).forEach(([d,m])=>c.append(d,m)),c.append(l.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let a=()=>s.abort();o.addEventListener("abort",a);let p=d=>{o.removeEventListener("abort",a),d()};s.open("POST",l.url),Object.entries(l.headers).forEach(([d,m])=>s.setRequestHeader(d,m)),s.upload.onprogress=d=>n(d.loaded,d.total||e.size||0),s.onload=()=>p(()=>{let d=s.responseText;try{d=JSON.parse(s.responseText)}catch{}if(s.status<200||s.status>=300){i(new f("UPLOAD_FAILED",`HTTP ${s.status}`));return}let m=os(d,l.url_field);if(typeof m!="string"||!m){i(new f("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${l.url_field}"`));return}r({url:m,response:d})}),s.onerror=()=>p(()=>i(new f("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),s.onabort=()=>p(()=>i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),s.send(c)}),Qo=e=>{var o,r;let t={...Ko};for(let[i,l]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))l?t[i]=l:delete t[i];let n={url:Xn};for(let[i,l]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&l&&(n[i]=l);return{sources:t,targets:n}},Zo=e=>{let{sources:t,targets:n}=Qo(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Ko[i]&&Wo[i]).map(i=>[i,Wo[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Kn}},pn=new Map,er=(e,t)=>`${e}:${t}`,rs=0,tr=(e,t)=>{var n;typeof t=="string"&&((n=pn.get(er(e,t)))==null||n.abort())},it=e=>{for(let[t,n]of pn)t.startsWith(`${e}:`)&&n.abort()},cn=()=>new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),is=(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)}},nr=async(e,t)=>{var c;let{sources:n,targets:o}=Qo(t.config),r=n[e.source];if(!r)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let l=new AbortController,s=er(t.instance_id,(c=t.task_id)!=null?c:`auto-${++rs}`);pn.set(s,l);try{return await ss(e,t,r,i,l.signal)}finally{pn.delete(s)}},ss=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:l,exclusivePick:s=d=>d()},c,a,p)=>{var Y,h,L;let d={app_id:n!=null?n:"",instance_id:t,context:{...(Y=o==null?void 0:o())!=null?Y:{}}},m=(await s(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:d}))).slice(0,e.max_count);if(p.aborted)throw cn();if(!m.length)throw new f("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],S=m.filter(R=>Wi(R,e.accept)?!0:(u.push({name:R.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${R.mime_type||Jo(R.name)}`}),!1)),v=S.map(()=>0),D=S.map(R=>{var w;return(w=R.size)!=null?w:0}),C=0,x=0,j=(R=!1)=>{if(!l||!r)return;let w=Date.now();if(!R&&w-x<200)return;x=w;let be=D.reduce((H,ge)=>H+ge,0),te=v.reduce((H,ge)=>H+ge,0);l("upload.progress",{task_id:r,loaded:te,total:be,percent:be?Math.min(100,Math.round(te/be*100)):0,done_count:C,count:S.length})},A=[],G=0,Q=async()=>{var R,w,be;for(;G<S.length;){let te=G++,H=S[te];try{if(p.aborted)throw cn();let ge=H.mime_type.startsWith("image/")?"image":H.mime_type.startsWith("video/")?"video":void 0,Ie=ge&&!H.processed?(w=(R=i==null?void 0:i.processors)==null?void 0:R[ge])!=null?w:ns[ge]:void 0;if(Ie&&(H=await Ie(H,e.process),D[te]=(be=H.size)!=null?be:D[te],p.aborted))throw cn();if(e.max_size&&H.size&&H.size>e.max_size)throw new f("FILE_TOO_LARGE",`File ${H.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let We=(_e,tt)=>{v[te]=_e,tt&&(D[te]=tt),j()},re=await a({file:H,target:e.target,onProgress:We,signal:p,caller:d});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new f("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Fe,...ne}=re;A[te]={url:Fe,name:H.name,mime_type:H.mime_type,size:H.size,width:H.width,height:H.height,duration:H.duration,...Object.keys(ne).length?{response:"response"in ne?ne.response:ne}:{}},v[te]=D[te]}catch(ge){u.push(is(S[te].name,ge))}finally{C++,j(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,S.length)},Q)),p.aborted)throw cn();let me=A.filter(R=>!!R);if(!me.length){let R=u[0];throw new f((h=R==null?void 0:R.code)!=null?h:"UPLOAD_FAILED",(L=R==null?void 0:R.message)!=null?L:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:me,failed:u}};var un=require("react"),De=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},J=(e,t,n=Object.is)=>{let o=(0,un.useRef)(null),r=()=>{let i=e.getState(),l=o.current;if(l&&l.state===i&&l.selector===t)return l.value;let s=t(i),c=l&&n(l.value,s)?l.value:s;return o.current={state:i,selector:t,value:c},c};return(0,un.useSyncExternalStore)(e.subscribe,r)};var ve={info:"info",success:"success",error:"error"},as=200,or={info:2e3,success:2e3,error:3e3},It=De({message:"",type:ve.info,tick:0}),rr=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,as);return o?{message:o,type:Object.values(ve).includes(n)?n:ve.info}:null},ir=(e,t=ve.info)=>{It.setState(n=>({message:e,type:t,tick:n.tick+1}))};var qe=require("react");var Zn=e=>`bundle:${e}`,eo=()=>`${U().file_system.document_dir}/miniapps`,to=eo,no=(e,t,n="index.html",o=!1,r=[])=>{let i=`${to()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Qn=e=>{var t;U().storage.setString(Zn(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ls=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,$=e=>{let t=U().storage.getString(Zn(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return no(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Ve=e=>U().file_system.exists(e.entry_uri.replace("file://","")),oo=async e=>{let t=$(e.app_id);return(t==null?void 0:t.version)===e.version&&await Ve(t)},ar=async(e,t)=>{let n=U().file_system,o=`${to()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},lr=async e=>{var t;await((t=Lt[e])==null?void 0:t.catch(()=>{})),U().storage.setString(Zn(e),""),await U().file_system.remove(`${to()}/${e}`).catch(()=>{})},ft=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Lt={},cr=(e,t)=>{var i;let o=((i=Lt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return Lt[e]=r,r.then(()=>{Lt[e]===r&&delete Lt[e]}),o},ro=(e,t)=>{var r,i;let n=e.split(".").map(l=>parseInt(l,10)||0),o=t.split(".").map(l=>parseInt(l,10)||0);for(let l=0;l<Math.max(n.length,o.length);l++){let s=((r=n[l])!=null?r:0)-((i=o[l])!=null?i:0);if(s)return s}return 0},pr=({manifest:e,zip_path:t})=>cr(e.app_id,async()=>{var i;let n=U().file_system,o=$(e.app_id);if(o&&ro(o.version,e.version)>=0&&await Ve(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=no(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),Qn(e),ye("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),ar(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),io=(e,{base_url:t,onProgress:n}={})=>{let o=U().file_system,r=null,i=!1,l=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,s=()=>{if(i)throw new ft},c=async()=>{var d;s();let a=$(e.app_id);if((a==null?void 0:a.version)===e.version&&await o.exists(a.dir))return Qn(e),$(e.app_id);s();let p=o.download({url:t?ls(t,e.bundle_url):e.bundle_url,to_file:l,onProgress:(m,u)=>{var v;let S=u>0?u:(v=e.size)!=null?v:0;S>0&&(n==null||n(Math.min(1,m/S)))}});r=p;try{let{status:m}=await p.promise;if(s(),m!==200)throw new Error(`bundle ${m}`);if(e.sha256)if(o.sha256){if(await o.sha256(l)!==e.sha256)throw new Error("sha256 mismatch")}else ye("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);s();let u=no(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(l,u.dir),Qn(e),ar(e.app_id,[e.version,a==null?void 0:a.version].filter(Boolean)),u}catch(m){throw i?new ft:m}finally{r=null,o.remove(l).catch(()=>{})}};return{promise:cr(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},Ft={},cs=__DEV__?0:60*1e3,sr={},ur=(e,t)=>{var o,r;let n=$(e);return n&&Date.now()-((o=sr[t])!=null?o:0)<cs?Promise.resolve(n):((r=Ft[e])!=null||(Ft[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let l=await i.json(),s=await io(l,{base_url:t}).promise;return sr[t]=Date.now(),s})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),$(e))).finally(()=>{Ft[e]=void 0})),Ft[e])};var ce=De({active_key:null,instances:{}}),dr=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var s;let l=(s=U().keep_alive)==null?void 0:s.max_webviews;ce.setState(c=>{let a=t!=null?t:e.app_id,p={...c.instances,[a]:{key:a,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},d=Object.keys(p);return l&&l>0&&d.length>l&&d.filter(m=>m!==a).sort((m,u)=>p[m].last_used_at-p[u].last_used_at).slice(0,d.length-l).forEach(m=>{delete p[m]}),i?{active_key:a,instances:p}:{instances:p}})},gr=e=>dr(e,!0),hr=e=>dr(e,!1),mt=()=>ce.setState({active_key:null}),dn=e=>{ce.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var fr="catalog",ps="paused_apps",us="removed_apps",ds=10*1e3,gs=2,hs=3e3,fs=()=>{var e;try{return JSON.parse((e=U().storage.getString(fr))!=null?e:"{}")}catch{return{}}},B=De({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),mr=e=>{var t;return!!((t=U().manual_update)!=null&&t.includes(e))},fn=new Set,yr=e=>{let t=new Set,n=()=>U().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=U().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},Oe=yr(ps),Xe=yr(us);an(()=>{Oe.load(),Xe.load();let e=fs(),t={};Object.keys(e).filter(n=>!Xe.has(n)).forEach(n=>{let o=$(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:Oe.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),B.setState({catalog:e,downloads:t})});var yt=e=>J(B,t=>e?t.downloads[e]:void 0),br=()=>J(B,e=>e.pause_reasons.length>0),Re=(...e)=>ye("queue",...e),le=[],Be={},V=null,gn=new Set,st={},so=new Set,He=e=>{so.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},mn=e=>(so.add(e),()=>{so.delete(e)}),_r=()=>B.getState().downloads,Ae=(e,t)=>{let n=!!$(e),o=B.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};B.setState(l=>({downloads:{...l.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?He({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&He({type:"progress",app_id:e,progress:i.progress,version:i.version})},hn=(e,t)=>{var n;(n=st[e])==null||n.forEach(o=>o(t)),delete st[e]},ms=()=>B.getState().pause_reasons.length>0,Ye=e=>{var s;if(V)return;let t=e?le.indexOf(e):ms()?-1:le.findIndex(c=>!Oe.has(c));if(t<0||t>=le.length)return;let[n]=le.splice(t,1),o=B.getState().catalog[n];if(!o){hn(n,$(n)),Ye();return}let r=Date.now();Be[n]=((s=Be[n])!=null?s:0)+1,Ae(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,l=io(o,{onProgress:c=>{let a=Math.floor(c*100);a!==i&&(i=a,Ae(n,{progress:a/100,version:o.version}))}});V={app_id:n,handle:l,forced:!!e},Re("start",n,o.version,e?"(forced)":""),l.promise.then(c=>{Re("installed",n,o.version,`${Date.now()-r}ms`),Ae(n,{status:"installed",progress:1,version:o.version}),hn(n,c)}).catch(c=>{var p;if(c instanceof ft){if(gn.has(n))return;Re("paused",n),Be[n]-=1,le.unshift(n),Ae(n,{status:Oe.has(n)?"paused":"queued",progress:0,version:o.version});return}let a=String((p=c==null?void 0:c.message)!=null?p:c);if(console.warn("[miniapp-queue] failed",n,a),Be[n]<gs){Ae(n,{status:"queued",progress:0,version:o.version,error:a}),setTimeout(()=>{var d;le.includes(n)||(V==null?void 0:V.app_id)===n||(le.push(n),Ye((d=st[n])!=null&&d.length?n:void 0))},hs);return}Ae(n,{status:"failed",progress:0,version:o.version,error:a}),hn(n,$(n))}).finally(()=>{V=null;let c=le.find(a=>{var p;return(p=st[a])==null?void 0:p.length});Ye(c)})},yn=(e,{front:t=!1}={})=>{if((V==null?void 0:V.app_id)===e)return;let n=le.indexOf(e);if(n>=0){if(!t)return;le.splice(n,1)}t?le.unshift(e):le.push(e)},ys=async e=>{let{host_id:t,client_token:n}=U(),o=new AbortController,r=setTimeout(()=>o.abort(),ds);try{let i=`${ht}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,l=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!l.ok)throw new Error(`host list ${e} ${l.status}`);return(await l.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},Dt=null,bn=()=>(Dt!=null||(Dt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(U().channels.map(ys)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(B.getState().catalog).filter(c=>!o[c]);U().storage.setString(fr,JSON.stringify(o)),B.setState({catalog:o}),await Promise.all(r.map(c=>wr(c,{by_user:!1}))),r.forEach(c=>Xe.delete(c));let i=Object.keys(o).filter(c=>!Xe.has(c)),l=[],s={};for(let c of i.map(a=>o[a])){if(await oo(c)){Ae(c.app_id,{status:"installed",progress:1,version:c.version});continue}let a=$(c.app_id);if(mr(c.app_id)&&!fn.has(c.app_id)&&a&&await Ve(a)){Ae(c.app_id,{status:"installed",progress:1,version:a.version}),s[c.app_id]={app_id:c.app_id,current_version:a.version,next_version:c.version};continue}l.push(c)}return B.setState({updates:s}),l.forEach(c=>{Be[c.app_id]=0,Ae(c.app_id,{status:Oe.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),yn(c.app_id)}),Re("catalog",i.length,"apps, outdated",l.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),He({type:"sync_complete",app_ids:i,removed:r}),Object.values(s).forEach(c=>He({type:"update_available",...c})),Ye(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),He({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{Dt=null}})()),Dt),wr=async(e,{by_user:t})=>{var r,i,l,s;if(t&&Xe.add(e),gn.has(e))return;gn.add(e),Oe.delete(e);let n=le.indexOf(e);n>=0&&le.splice(n,1),(V==null?void 0:V.app_id)===e&&V.handle.cancel();let o=(s=(l=(r=B.getState().downloads[e])==null?void 0:r.version)!=null?l:(i=$(e))==null?void 0:i.version)!=null?s:"";Ae(e,{status:"uninstalling",progress:0,version:o}),await lr(e),dn(e),B.setState(c=>{let a={...c.downloads};return delete a[e],{downloads:a}}),delete Be[e],gn.delete(e),hn(e,null),Re("uninstalled",e,t?"(user)":"(not in list)"),He({type:"uninstalled",app_id:e})},Ar=e=>wr(e,{by_user:!0}),Sr=e=>{let t=bt(e);return t?(Xe.delete(e),(V==null?void 0:V.app_id)===e||le.includes(e)||(Be[e]=0,Ae(e,{status:Oe.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),yn(e),Ye(),Re("restore",e)),!0):!1},Mr=e=>{if(Oe.has(e))return;if(Oe.add(e),Re("pause app",e),(V==null?void 0:V.app_id)===e&&!V.forced){V.handle.cancel();return}let t=B.getState().downloads[e];le.includes(e)&&t&&Ae(e,{status:"paused",progress:0,version:t.version})},vr=e=>{if(!Oe.delete(e))return;Re("resume app",e);let t=B.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!le.includes(e)&&bt(e)&&(Be[e]=0,yn(e)),le.includes(e)&&t&&Ae(e,{status:"queued",progress:0,version:t.version}),Ye()},xr=e=>{let{pause_reasons:t}=B.getState();t.includes(e)||(B.setState({pause_reasons:[...t,e]}),Re("pause",e),t.length===0&&He({type:"pause_change",paused:!0,reasons:[e]}),V&&!V.forced&&V.handle.cancel())},Cr=e=>{let{pause_reasons:t}=B.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);B.setState({pause_reasons:n}),Re("resume",e),n.length===0&&He({type:"pause_change",paused:!1,reasons:n}),Ye()},ao=e=>B.getState().updates[e],_n=async e=>{var n,o;let t=ao(e);fn.add(e);try{let r=await Nt(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=bt(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(B.setState(l=>{var c;let s={...l.updates};return delete s[e],{updates:s,apply_ticks:{...l.apply_ticks,[e]:((c=l.apply_ticks[e])!=null?c:0)+1}}}),Re("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),He({type:"update_applied",app_id:e,version:r.version}),!0)}finally{fn.delete(e)}},Er=()=>Object.values(B.getState().catalog).map(e=>({...e,installed:!!$(e.app_id),removed_by_user:Xe.has(e.app_id)})),bt=e=>B.getState().catalog[e],Nt=async e=>{let t=bt(e);if(!t)return;if(Oe.delete(e),Xe.delete(e),await oo(t))return $(e);let n=$(e);if(mr(e)&&!fn.has(e)&&n&&await Ve(n))return n;let o=new Promise(r=>{var i;((i=st[e])!=null?i:st[e]=[]).push(r)});return(V==null?void 0:V.app_id)===e?V.forced=!0:(Be[e]=0,yn(e,{front:!0}),V&&!V.forced?V.handle.cancel():Ye(e)),o};var Pr=e=>`changelog_seen:${e}`,bs=10*1e3,wn=e=>U().storage.getString(Pr(e))||null,wt=(e,t=(n=>(n=$(e))==null?void 0:n.version)())=>{t&&U().storage.setString(Pr(e),t)},An=e=>{var o;let t=(o=$(e))==null?void 0:o.version;if(!t)return null;let n=wn(e);return n?ro(t,n)>0?{app_id:e,from:n,to:t}:null:(wt(e,t),null)},_s=e=>{var t,n,o;return(o=(n=(t=B.getState().catalog[e])==null?void 0:t.channel)!=null?n:U().channels[0])!=null?o:"production"},Vt=async(e,{from:t,to:n,channel:o=_s(e)}={})=>{let{client_token:r}=U(),i=new URLSearchParams({channel:o});t&&i.set("from",t),n&&i.set("to",n);let l=new AbortController,s=setTimeout(()=>l.abort(),bs);try{let c=await fetch(`${ht}/api/miniapps/${encodeURIComponent(e)}/changelog?${i}`,{headers:{Authorization:`Bearer ${r}`},signal:l.signal});if(!c.ok)throw new Error(`changelog ${e} ${c.status}`);return(await c.json()).versions}finally{clearTimeout(s)}},Sn=(e,{from:t,to:n,enabled:o=!0}={})=>{let[r,i]=(0,qe.useState)([]),[l,s]=(0,qe.useState)(!1),[c,a]=(0,qe.useState)(),[p,d]=(0,qe.useState)(0),m=(0,qe.useCallback)(()=>d(u=>u+1),[]);return(0,qe.useEffect)(()=>{if(!e||!o)return;let u=!0;return s(!0),a(void 0),Vt(e,{from:t,to:n}).then(S=>{u&&i(S)}).catch(S=>{var v;u&&a(String((S==null?void 0:S.name)==="AbortError"?"timeout":(v=S==null?void 0:S.message)!=null?v:S))}).finally(()=>{u&&s(!1)}),()=>{u=!1}},[e,t,n,o,p]),{versions:r,loading:l,error:c,reload:m}},ze=De({request:null,history:null}),Ut=!1,lo=e=>{var t,n;return(n=(t=B.getState().catalog[e])==null?void 0:t.name)!=null?n:e},ws=async e=>{var i,l,s,c;let t=(i=$(e))==null?void 0:i.version;if(!t)return null;let n=An(e),o=await Vt(e,n?{from:n.from,to:n.to}:{to:t}),r=n&&o.length?o:o.slice(0,1);return r.length?{app_id:e,name:lo(e),from:(c=(s=n==null?void 0:n.from)!=null?s:(l=o[1])==null?void 0:l.version)!=null?c:r[0].version,to:t,versions:r}:null},_t=async(e,{name:t,force:n=!1}={})=>{if(ze.getState().request||Ut)return!1;if(n){Ut=!0;try{let r=await ws(e);return r&&ze.setState({request:{...r,name:t!=null?t:r.name}}),!!r}catch(r){return ye("changelog failed",e,r),!1}finally{Ut=!1}}let o=An(e);if(!o)return!1;Ut=!0;try{let r=await Vt(e,{from:o.from,to:o.to});return r.length?(ze.setState({request:{...o,name:t!=null?t:lo(e),versions:r}}),!0):(wt(e,o.to),!1)}catch(r){return ye("changelog failed",e,r),!1}finally{Ut=!1}},Mn=()=>{let{request:e}=ze.getState();e&&wt(e.app_id,e.to),ze.setState({request:null})},vn=()=>J(ze,e=>e.request),xn=(e,{name:t}={})=>{ze.setState({history:{app_id:e,name:t!=null?t:lo(e)}})},Cn=()=>ze.setState({history:null}),En=()=>J(ze,e=>e.history),Tr=!1;an(()=>{if(Tr)return;Tr=!0;let e=()=>U().changelog!==!1;mn(n=>{n.type==="status_change"&&n.state.status==="installed"&&!wn(n.app_id)&&wt(n.app_id,n.state.version),n.type==="update_applied"&&e()&&_t(n.app_id)});let t=ce.getState().active_key;ce.subscribe(()=>{let{active_key:n,instances:o}=ce.getState();if(n===t)return;t=n;let r=n?o[n]:void 0;r&&e()&&_t(r.app.app_id,{name:r.app.name})})});var Ce=require("react-native");var at=require("react-native");var xe,At=new Map,kr=(e,t)=>{var o;let n=(o=At.get(e))!=null?o:new Set;n.add(t),At.set(e,n)},Rr=(e,t)=>{let n=At.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&At.delete(e))},po=new Map,Or=(e,t)=>{po.set(e,t)},Ir=e=>po.get(e),Fr=()=>at.Platform.OS==="android"&&!!(xe!=null&&xe.requesting_permission),As=1500,Tn=()=>new Promise(e=>{if(at.Platform.OS!=="android"||at.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,As),o=at.AppState.addEventListener("change",r=>{r==="active"&&t()})}),co=e=>{var t;if(xe===e&&(xe=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&at.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Lr=async(e,t,n,o=()=>!0)=>{var i,l,s,c,a;if(xe)throw new f("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};xe=r;try{let p;try{p=await import("expo-speech-recognition")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=p.ExpoSpeechRecognitionModule;if(r.native=d,r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let m;try{m=await d.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await Tn(),r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!m.granted)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new f("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(d.addListener("result",u=>{var S,v;xe!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(v=(S=u.results[0])==null?void 0:S.transcript)!=null?v:""})}),d.addListener("error",u=>{xe===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),d.addListener("end",()=>{xe===r&&(co(r),n("speech.end"))})),r.started=!0,d.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(l=t.continuous)!=null?l:!0,interimResults:(s=t.interimResults)!=null?s:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(a=t.requiresOnDeviceRecognition)!=null?a:!1,iosCategory:{category:p.AVAudioSessionCategory.playAndRecord,categoryOptions:[p.AVAudioSessionCategoryOptions.defaultToSpeaker,p.AVAudioSessionCategoryOptions.allowBluetooth],mode:p.AVAudioSessionMode.measurement}})}catch(p){throw co(r),p}},Dr=e=>{let t=xe;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Ne=e=>{po.delete(e);let t=At.get(e);At.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=xe;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{co(n)}};var Nr={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},pe={...Nr,all:Object.values(Nr)},St={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},kn={result:"scanner.result",end:"scanner.end"},lt={user:"user",web:"web",closed:"closed",error:"error"},Se={top:"top",full:"full"},Qe={once:"once",continuous:"continuous"},Ss=1500,Ur=6e4,X,ae=De({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Br=()=>Ce.Platform.OS==="android"&&!!(X!=null&&X.requesting_permission),go=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},l={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(s=>pe.all.includes(s)))throw new f("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");l.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Ur)throw new f("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Ur}`);l.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new f("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");l.hint=o}if(r!==void 0){if(!Object.values(Se).includes(r))throw new f("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");l.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new f("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");l.absolute=i}return l},ho=e=>X!==e?!1:(X=void 0,ae.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Ms=()=>Ce.Alert.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{Ce.Linking.openSettings().catch(()=>{})}}]),Hr=async(e,t)=>{if(X)throw new f("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");X=e;let n=()=>{if(e.cancelled||!t())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let l=Ce.Platform.OS==="ios"&&r==="denied";e.requesting_permission=!0;let s;try{s=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await Tn(),n(),s!=="granted")throw l&&Ms(),new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(l=>l.position==="back"))throw new f("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await Bt();n(),ae.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw ho(e),o}},Pn;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{Pn=e==null?void 0:e.insets}).catch(()=>{});var Mt=()=>{var e;return Pn!=null?Pn:{top:Ce.Platform.OS==="ios"?54:(e=Ce.StatusBar.currentHeight)!=null?e:0,bottom:Ce.Platform.OS==="ios"?34:48}},Bt=async()=>{if(Ce.Platform.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},qr=(e,t,n)=>{var o,r,i,l;return{owner:e,mode:t,types:(o=n.types)!=null?o:pe.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Ss,hint:n.hint,layout:t===Qe.once?Se.full:(i=n.layout)!=null?i:Se.top,absolute:t!==Qe.once&&((l=n.layout)!=null?l:Se.top)===Se.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},zr=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let l=qr(e,Qe.once,t);l.onHit=o,l.resolve=r,l.reject=i,Hr(l,n).catch(i)}),$r=(e,t,n,o=()=>!0,r)=>{let i=qr(e,Qe.continuous,t);return i.emit=n,i.onHit=r,Hr(i,o)},Rn=(e,t,n)=>{var o,r;if(!ae.getState().active){e.cancelled=!0;return}if(ho(e)){if(e.mode===Qe.once){(o=e.reject)==null||o.call(e,t===lt.error?new f("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new f("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,kn.end,n?{reason:t,message:n}:{reason:t})}},Wr=e=>{(X==null?void 0:X.owner)===e&&Rn(X,lt.web)},Ze=e=>{(X==null?void 0:X.owner)===e&&Rn(X,lt.closed)},fo=()=>{X&&Rn(X,lt.user)},jr=e=>{X&&Rn(X,lt.error,e)},mo=(e,t=Date.now(),n=!1)=>{var r,i,l;let o=X;if(!(!o||!ae.getState().active))for(let{value:s,type:c}of e){if(!s)continue;let a=o.last_seen.get(s);if(o.last_seen.set(s,t),!(!n&&a!==void 0&&t-a<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Qe.once){ho(o),(i=o.resolve)==null||i.call(o,{value:s,type:c});return}ae.setState(p=>({last_value:s,hit_tick:p.hit_tick+1,scan_count:p.scan_count+1,notice:null})),(l=o.emit)==null||l.call(o,kn.result,{value:s,type:c})}}},vs={1:pe.code128,2:pe.code39,4:pe.code93,8:pe.codabar,16:pe.dataMatrix,32:pe.ean13,64:pe.ean8,128:pe.itf,256:pe.qr,512:pe.upcA,1024:pe.upcE,2048:pe.pdf417,4096:pe.aztec},xs=2500,Vr=2e3,uo=e=>{ae.setState({notice:e}),setTimeout(()=>{ae.getState().notice===e&&ae.setState({notice:null})},xs)},Gr=async()=>{var t,n;let e=X;if(!(!e||ae.getState().is_picking)){e.requesting_permission=!0,ae.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:Vr,maxHeight:Vr}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||X!==e)return;if(r.errorCode||!i){uo("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:l}=await import("@react-native-ml-kit/barcode-scanning"),s=await l.scan(i);if(X!==e)return;let c=s.map(({value:a,format:p})=>({value:a,code_type:vs[p]})).filter(({code_type:a})=>!a||e.types.includes(a)).map(({value:a,code_type:p})=>({value:a,type:p!=null?p:"unknown"}));if(!c.length){uo("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}mo(c,Date.now(),!0)}catch{X===e&&uo("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await Tn(),e.requesting_permission=!1,X===e&&ae.setState({is_picking:!1})}}};var zt=1,f=class extends Error{constructor(n,o){super(o);this.code=n}},Jr=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===zt&&typeof t.method=="string"?t:null}catch{return null}},$t=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Kr=(e,t)=>$t({id:e,result:t}),Yr=(e,t)=>$t({id:e,error:{code:t.code,message:t.message}}),Xr=(e,t)=>$t({event:e,data:t}),bo=e=>$t({event:"context",data:e});var Qr=()=>`(function () {
1
+ "use strict";var Fi=Object.create;var sn=Object.defineProperty;var Li=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Ui=Object.prototype.hasOwnProperty;var Vi=(e,t)=>{for(var n in t)sn(e,n,{get:t[n],enumerable:!0})},Io=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Di(t))!Ui.call(e,r)&&r!==n&&sn(e,r,{get:()=>t[r],enumerable:!(o=Li(t,r))||o.enumerable});return e};var he=(e,t,n)=>(n=e!=null?Fi(Ni(e)):{},Io(t||!e||!e.__esModule?sn(n,"default",{value:e,enumerable:!0}):n,e)),Bi=e=>Io(sn({},"__esModule",{value:!0}),e);var ia={};Vi(ia,{AGENT_BRIDGE_VERSION:()=>wo,AGENT_MESSAGE_EVENT:()=>Ao,AGENT_PAYLOAD_META_EVENT:()=>Mo,AGENT_PAYLOAD_META_RESULT_EVENT:()=>vo,AGENT_STOPPED_EVENT:()=>So,CodeType:()=>pe,DEFAULT_MINIAPP_UPDATES_LABELS:()=>Vn,DefaultMiniAppChangelogHistoryModal:()=>Zt,DefaultMiniAppChangelogPrompt:()=>Xt,DefaultMiniAppSplash:()=>Po,DefaultMiniAppUpdatePrompt:()=>Qt,MINIAPP_CHANGELOG_KINDS:()=>Hn,MINIAPP_PLATFORM_URL:()=>ht,MiniAppChangelogGroups:()=>pt,MiniAppChangelogHistory:()=>Et,MiniAppChangelogText:()=>qn,MiniAppHost:()=>Ci,MiniAppHostError:()=>f,MiniAppUpdates:()=>Ii,MiniAppUpdatesThemeProvider:()=>ct,ScannerEndReason:()=>lt,ScannerEvent:()=>kn,ScannerLayout:()=>Se,ScannerMethod:()=>St,ToastType:()=>ve,closeMiniApp:()=>mt,closeMiniAppChangelogHistory:()=>Cn,configureMiniApp:()=>Lo,createMmkvStorage:()=>No,createReactNativeBiometrics:()=>jn,createRnfsFileSystem:()=>Do,dismissMiniAppChangelog:()=>Mn,ensureMiniApp:()=>Nt,fetchMiniAppChangelog:()=>Vt,getLocalMiniApp:()=>$,getMiniAppCatalog:()=>Er,getMiniAppCatalogEntry:()=>_t,getMiniAppChangelogSeen:()=>wn,getMiniAppIdByAgentId:()=>mi,getMiniAppStatuses:()=>br,getMiniAppUpdate:()=>so,getPendingChangelog:()=>An,installBundledMiniApp:()=>pr,markMiniAppChangelogSeen:()=>wt,mergeMiniAppChangelog:()=>Yt,onMiniAppEvent:()=>mn,openMiniApp:()=>gr,parseInlineMarkdown:()=>Jt,pauseMiniApp:()=>Mr,pauseMiniAppDownloads:()=>xr,preloadMiniApp:()=>hr,releaseSpeechFor:()=>Ne,resolveMiniAppUpdatesTheme:()=>Kt,restoreMiniApp:()=>Sr,resumeMiniApp:()=>vr,resumeMiniAppDownloads:()=>Cr,sendEventToWeb:()=>Fn,showMiniAppChangelog:()=>bt,showMiniAppChangelogHistory:()=>xn,stripInlineMarkdown:()=>Ei,syncMiniAppCatalog:()=>_n,uninstallMiniApp:()=>Ar,updateMiniApp:()=>bn,uploadToUrl:()=>Yn,useMiniAppChangelog:()=>Sn,useMiniAppChangelogHistoryRequest:()=>En,useMiniAppChangelogRequest:()=>vn,useMiniAppDownload:()=>yt,useMiniAppDownloadsPaused:()=>_r,useMiniAppUpdatesTheme:()=>Pe});module.exports=Bi(ia);var ht="https://retion-miniapp-platform.vercel.app",rt=null,Fo=new Set,Lo=e=>{rt=e,Fo.forEach(t=>t())},U=()=>{if(!rt)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return rt},an=e=>{Fo.add(e),rt&&e()},ye=(...e)=>{rt!=null&&rt.debug&&console.log("[miniapp]",...e)};var Do=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:l}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:s,contentLength:c})=>r==null?void 0:r(s,c)});return{promise:l.then(({statusCode:s})=>({status:s})),cancel:()=>e.stopDownload(i)}}}),No=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var M=he(require("react")),F=require("react-native"),xi=he(require("react-native-webview"));var qt=require("react-native");var jn=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),ln,Gn=()=>(ln||(ln=import("react-native-biometrics").then(({default:e})=>jn(new e({allowDeviceCredentials:!1}))).catch(e=>{throw ln=void 0,new f("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),ln);var Le=require("react-native");var Uo=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new f("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new f("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,l,s]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<l||c>s))throw new f("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${l}\u2013${s} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Vo=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,a)=>{r||(r=!0,clearTimeout(l),c?o(c):n(a))},l=setTimeout(()=>i(new f("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),s=()=>r?!1:t()?!0:(i(new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!s())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(s()){if(Le.Platform.OS==="android"){let a=Le.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,p=Le.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await Le.PermissionsAndroid.check(a);if(!s())return;let m=d||await Le.PermissionsAndroid.check(p);if(!s())return;if(!d&&!m){let u=await Le.PermissionsAndroid.requestMultiple([a,p]);if(!s())return;if(u[a]!==Le.PermissionsAndroid.RESULTS.GRANTED&&u[p]!==Le.PermissionsAndroid.RESULTS.GRANTED)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}s()&&c.getCurrentPosition(a=>{s()&&i(void 0,a)},a=>{var d;if(!s())return;let p=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[a.code])!=null?d:"LOCATION_ERROR";i(new f(p,a.message))},e)}})().catch(c=>i(c))});var Kn=require("react-native");var Jn=20,Bo=20,jo=/^[a-z][a-z0-9_-]{0,31}$/,Hi=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,qi=["low","medium","high"],Ke=e=>!!e&&typeof e=="object"&&!Array.isArray(e),se=e=>new f("INVALID_PARAMS",e),Ot=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ho=(e,t)=>{if(e===void 0)return{};if(!Ke(e)||Object.keys(e).length>Bo||Object.values(e).some(n=>typeof n!="string"))throw se(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Bo} key)`);return e},Go=e=>{var n,o,r,i;if(e!==void 0&&!Ke(e))throw se("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!jo.test(t.source)))throw se("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(l=>typeof l!="string"||!Hi.test(l))))throw se("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ot(t.max_count,1,Jn))throw se(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Jn}`);if(t.max_size!==void 0&&!Ot(t.max_size,1,Number.MAX_SAFE_INTEGER))throw se("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ot(t.concurrency,1,5))throw se("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(l=>l.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:zi(t.process),target:$i(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},zi=e=>{if(e===void 0)return{};if(!Ke(e))throw se("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Ke(n))throw se("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Ot(n[o],1,1e4))throw se(`process.image.${o} 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 se("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(!Ke(n))throw se("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ot(n.max_duration,1,3600))throw se("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!qi.includes(n.quality))throw se("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},$i=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Ke(e))throw se("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!jo.test(t))throw se("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Ke(e.params))throw se("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw se("upload.url ph\u1EA3i l\xE0 https");for(let l of["field_name","url_field"])if(e[l]!==void 0&&(typeof e[l]!="string"||!e[l]))throw se(`upload.${l} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Ho(e.headers,"upload.headers"),form_data:Ho(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},Jo=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Wi=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=Jo(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},ji=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},Pt,Gi=()=>(Pt!=null||(Pt=import("react-native-image-picker").catch(e=>{throw Pt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Pt),qo=e=>async({accept:t,max_count:n,process:o})=>{var c,a,p,d,m,u,S,v,D;let r=await Gi(),i=ji(t),l={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(a=o.image)==null?void 0:a.max_height,quality:(d=(p=o.image)==null?void 0:p.quality)!=null?d:.8,videoQuality:(u=(m=o.video)==null?void 0:m.quality)!=null?u:"medium",durationLimit:(S=o.video)==null?void 0:S.max_duration,assetRepresentationMode:"compatible"},s=e==="camera"?await r.launchCamera({...l,saveToPhotos:!1}):await r.launchImageLibrary({...l,selectionLimit:n});if(s.didCancel)return[];if(s.errorCode){let C=s.errorCode==="permission"?"PERMISSION_DENIED":s.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new f(C,(v=s.errorMessage)!=null?v:s.errorCode)}return((D=s.assets)!=null?D:[]).filter(C=>C.uri).map((C,x)=>{var j,A,G;return{uri:C.uri,name:(j=C.fileName)!=null?j:`file_${x+1}`,mime_type:(A=C.type)!=null?A:"application/octet-stream",size:C.fileSize,width:C.width,height:C.height,duration:C.duration,processed:!((G=C.type)!=null&&G.startsWith("video/"))||Kn.Platform.OS==="ios"}})},Ji={"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"},Ki={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Yi=e=>async({accept:t,max_count:n})=>{var i,l,s,c;let o=t.map(a=>{var p;return(p=Ji[a])!=null?p:Ki[a]}),r=!t.length||o.some(a=>!a||!e.types[a])?e.types.allFiles:[...new Set(o)].flatMap(a=>e.types[a]);try{let p=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,S)=>{var v,D,C;return{uri:u.uri,name:(v=u.name)!=null?v:`file_${S+1}`,mime_type:(D=u.type)!=null?D:"application/octet-stream",size:(C=u.size)!=null?C:void 0}});if(Kn.Platform.OS!=="android"||!e.keepLocalCopy||!p.some(u=>u.uri.startsWith("content://")))return p;let d=await e.keepLocalCopy({files:p.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),m=new Map(d.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return p.map(u=>{var S;return{...u,uri:(S=m.get(u.uri))!=null?S:u.uri}})}catch(a){let p=a==null?void 0:a.code;if(p===((l=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?l:"OPERATION_CANCELED"))return[];throw p===((c=(s=e.errorCodes)==null?void 0:s.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new f("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):a}},kt,Xi=async e=>(kt!=null||(kt=import("@react-native-documents/picker").then(t=>Yi(t)).catch(t=>{throw kt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await kt)(e)),Ko={library:qo("library"),camera:qo("camera"),document:Xi},zo={type:"image",label:"\u1EA2nh",accept:["image/*"]},$o={type:"video",label:"Video",accept:["video/*"]},Wo={library:[zo,$o],camera:[zo,$o],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},Rt,Yo=()=>(Rt!=null||(Rt=import("react-native-compressor").catch(()=>(Rt=void 0,null))),Rt),Xo=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},Qi=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),Zi={low:640,medium:1280,high:1920},es=async(e,{image:t})=>{var o;if(!t||!Qi.has(e.mime_type.toLowerCase()))return e;let n=await Yo();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Xo(n,r,e.size),processed:!0}}catch{return e}},ts=async(e,{video:t})=>{var o;let n=await Yo();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:Zi[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Xo(n,r,e.size),processed:!0}}catch{return e}},ns={image:es,video:ts},os=(e,t)=>t.split(".").reduce((n,o)=>Ke(n)?n[o]:void 0,e),Yn=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new f("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let l=t;if(o.aborted){i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let s=new XMLHttpRequest,c=new FormData;Object.entries(l.form_data).forEach(([d,m])=>c.append(d,m)),c.append(l.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let a=()=>s.abort();o.addEventListener("abort",a);let p=d=>{o.removeEventListener("abort",a),d()};s.open("POST",l.url),Object.entries(l.headers).forEach(([d,m])=>s.setRequestHeader(d,m)),s.upload.onprogress=d=>n(d.loaded,d.total||e.size||0),s.onload=()=>p(()=>{let d=s.responseText;try{d=JSON.parse(s.responseText)}catch{}if(s.status<200||s.status>=300){i(new f("UPLOAD_FAILED",`HTTP ${s.status}`));return}let m=os(d,l.url_field);if(typeof m!="string"||!m){i(new f("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${l.url_field}"`));return}r({url:m,response:d})}),s.onerror=()=>p(()=>i(new f("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),s.onabort=()=>p(()=>i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),s.send(c)}),Qo=e=>{var o,r;let t={...Ko};for(let[i,l]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))l?t[i]=l:delete t[i];let n={url:Yn};for(let[i,l]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&l&&(n[i]=l);return{sources:t,targets:n}},Zo=e=>{let{sources:t,targets:n}=Qo(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Ko[i]&&Wo[i]).map(i=>[i,Wo[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Jn}},pn=new Map,er=(e,t)=>`${e}:${t}`,rs=0,tr=(e,t)=>{var n;typeof t=="string"&&((n=pn.get(er(e,t)))==null||n.abort())},it=e=>{for(let[t,n]of pn)t.startsWith(`${e}:`)&&n.abort()},cn=()=>new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),is=(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)}},nr=async(e,t)=>{var c;let{sources:n,targets:o}=Qo(t.config),r=n[e.source];if(!r)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let l=new AbortController,s=er(t.instance_id,(c=t.task_id)!=null?c:`auto-${++rs}`);pn.set(s,l);try{return await ss(e,t,r,i,l.signal)}finally{pn.delete(s)}},ss=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:l,exclusivePick:s=d=>d()},c,a,p)=>{var Y,h,L;let d={app_id:n!=null?n:"",instance_id:t,context:{...(Y=o==null?void 0:o())!=null?Y:{}}},m=(await s(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:d}))).slice(0,e.max_count);if(p.aborted)throw cn();if(!m.length)throw new f("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],S=m.filter(R=>Wi(R,e.accept)?!0:(u.push({name:R.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${R.mime_type||Jo(R.name)}`}),!1)),v=S.map(()=>0),D=S.map(R=>{var w;return(w=R.size)!=null?w:0}),C=0,x=0,j=(R=!1)=>{if(!l||!r)return;let w=Date.now();if(!R&&w-x<200)return;x=w;let _e=D.reduce((H,ge)=>H+ge,0),te=v.reduce((H,ge)=>H+ge,0);l("upload.progress",{task_id:r,loaded:te,total:_e,percent:_e?Math.min(100,Math.round(te/_e*100)):0,done_count:C,count:S.length})},A=[],G=0,Q=async()=>{var R,w,_e;for(;G<S.length;){let te=G++,H=S[te];try{if(p.aborted)throw cn();let ge=H.mime_type.startsWith("image/")?"image":H.mime_type.startsWith("video/")?"video":void 0,Ie=ge&&!H.processed?(w=(R=i==null?void 0:i.processors)==null?void 0:R[ge])!=null?w:ns[ge]:void 0;if(Ie&&(H=await Ie(H,e.process),D[te]=(_e=H.size)!=null?_e:D[te],p.aborted))throw cn();if(e.max_size&&H.size&&H.size>e.max_size)throw new f("FILE_TOO_LARGE",`File ${H.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let We=(be,tt)=>{v[te]=be,tt&&(D[te]=tt),j()},re=await a({file:H,target:e.target,onProgress:We,signal:p,caller:d});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new f("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Fe,...ne}=re;A[te]={url:Fe,name:H.name,mime_type:H.mime_type,size:H.size,width:H.width,height:H.height,duration:H.duration,...Object.keys(ne).length?{response:"response"in ne?ne.response:ne}:{}},v[te]=D[te]}catch(ge){u.push(is(S[te].name,ge))}finally{C++,j(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,S.length)},Q)),p.aborted)throw cn();let me=A.filter(R=>!!R);if(!me.length){let R=u[0];throw new f((h=R==null?void 0:R.code)!=null?h:"UPLOAD_FAILED",(L=R==null?void 0:R.message)!=null?L:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:me,failed:u}};var un=require("react"),De=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},J=(e,t,n=Object.is)=>{let o=(0,un.useRef)(null),r=()=>{let i=e.getState(),l=o.current;if(l&&l.state===i&&l.selector===t)return l.value;let s=t(i),c=l&&n(l.value,s)?l.value:s;return o.current={state:i,selector:t,value:c},c};return(0,un.useSyncExternalStore)(e.subscribe,r)};var ve={info:"info",success:"success",error:"error"},as=200,or={info:2e3,success:2e3,error:3e3},It=De({message:"",type:ve.info,tick:0}),rr=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,as);return o?{message:o,type:Object.values(ve).includes(n)?n:ve.info}:null},ir=(e,t=ve.info)=>{It.setState(n=>({message:e,type:t,tick:n.tick+1}))};var qe=require("react");var Qn=e=>`bundle:${e}`,Zn=()=>`${U().file_system.document_dir}/miniapps`,eo=Zn,to=(e,t,n="index.html",o=!1,r=[])=>{let i=`${eo()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Xn=e=>{var t;U().storage.setString(Qn(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},ls=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,$=e=>{let t=U().storage.getString(Qn(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return to(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Ve=e=>U().file_system.exists(e.entry_uri.replace("file://","")),no=async e=>{let t=$(e.app_id);return(t==null?void 0:t.version)===e.version&&await Ve(t)},ar=async(e,t)=>{let n=U().file_system,o=`${eo()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},lr=async e=>{var t;await((t=Lt[e])==null?void 0:t.catch(()=>{})),U().storage.setString(Qn(e),""),await U().file_system.remove(`${eo()}/${e}`).catch(()=>{})},ft=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Lt={},cr=(e,t)=>{var i;let o=((i=Lt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return Lt[e]=r,r.then(()=>{Lt[e]===r&&delete Lt[e]}),o},oo=(e,t)=>{var r,i;let n=e.split(".").map(l=>parseInt(l,10)||0),o=t.split(".").map(l=>parseInt(l,10)||0);for(let l=0;l<Math.max(n.length,o.length);l++){let s=((r=n[l])!=null?r:0)-((i=o[l])!=null?i:0);if(s)return s}return 0},pr=({manifest:e,zip_path:t})=>cr(e.app_id,async()=>{var i;let n=U().file_system,o=$(e.app_id);if(o&&oo(o.version,e.version)>=0&&await Ve(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=to(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),Xn(e),ye("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),ar(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),ro=(e,{base_url:t,onProgress:n}={})=>{let o=U().file_system,r=null,i=!1,l=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,s=()=>{if(i)throw new ft},c=async()=>{var d;s();let a=$(e.app_id);if((a==null?void 0:a.version)===e.version&&await o.exists(a.dir))return Xn(e),$(e.app_id);s();let p=o.download({url:t?ls(t,e.bundle_url):e.bundle_url,to_file:l,onProgress:(m,u)=>{var v;let S=u>0?u:(v=e.size)!=null?v:0;S>0&&(n==null||n(Math.min(1,m/S)))}});r=p;try{let{status:m}=await p.promise;if(s(),m!==200)throw new Error(`bundle ${m}`);if(e.sha256)if(o.sha256){if(await o.sha256(l)!==e.sha256)throw new Error("sha256 mismatch")}else ye("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);s();let u=to(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(l,u.dir),Xn(e),ar(e.app_id,[e.version,a==null?void 0:a.version].filter(Boolean)),u}catch(m){throw i?new ft:m}finally{r=null,o.remove(l).catch(()=>{})}};return{promise:cr(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},Ft={},cs=__DEV__?0:60*1e3,sr={},ur=(e,t)=>{var o,r;let n=$(e);return n&&Date.now()-((o=sr[t])!=null?o:0)<cs?Promise.resolve(n):((r=Ft[e])!=null||(Ft[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let l=await i.json(),s=await ro(l,{base_url:t}).promise;return sr[t]=Date.now(),s})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),$(e))).finally(()=>{Ft[e]=void 0})),Ft[e])};var ce=De({active_key:null,instances:{}}),dr=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var s;let l=(s=U().keep_alive)==null?void 0:s.max_webviews;ce.setState(c=>{let a=t!=null?t:e.app_id,p={...c.instances,[a]:{key:a,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},d=Object.keys(p);return l&&l>0&&d.length>l&&d.filter(m=>m!==a).sort((m,u)=>p[m].last_used_at-p[u].last_used_at).slice(0,d.length-l).forEach(m=>{delete p[m]}),i?{active_key:a,instances:p}:{instances:p}})},gr=e=>dr(e,!0),hr=e=>dr(e,!1),mt=()=>ce.setState({active_key:null}),dn=e=>{ce.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var fr="catalog",ps="paused_apps",us="removed_apps",ds=10*1e3,gs=2,hs=3e3,fs=()=>{var e;try{return JSON.parse((e=U().storage.getString(fr))!=null?e:"{}")}catch{return{}}},B=De({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),mr=e=>{var t;return!!((t=U().manual_update)!=null&&t.includes(e))},fn=new Set,yr=e=>{let t=new Set,n=()=>U().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=U().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},Oe=yr(ps),Xe=yr(us);an(()=>{Oe.load(),Xe.load();let e=fs(),t={};Object.keys(e).filter(n=>!Xe.has(n)).forEach(n=>{let o=$(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:Oe.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),B.setState({catalog:e,downloads:t})});var yt=e=>J(B,t=>e?t.downloads[e]:void 0),_r=()=>J(B,e=>e.pause_reasons.length>0),Re=(...e)=>ye("queue",...e),le=[],Be={},V=null,gn=new Set,st={},io=new Set,He=e=>{io.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},mn=e=>(io.add(e),()=>{io.delete(e)}),br=()=>B.getState().downloads,Ae=(e,t)=>{let n=!!$(e),o=B.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};B.setState(l=>({downloads:{...l.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?He({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&He({type:"progress",app_id:e,progress:i.progress,version:i.version})},hn=(e,t)=>{var n;(n=st[e])==null||n.forEach(o=>o(t)),delete st[e]},ms=()=>B.getState().pause_reasons.length>0,Ye=e=>{var s;if(V)return;let t=e?le.indexOf(e):ms()?-1:le.findIndex(c=>!Oe.has(c));if(t<0||t>=le.length)return;let[n]=le.splice(t,1),o=B.getState().catalog[n];if(!o){hn(n,$(n)),Ye();return}let r=Date.now();Be[n]=((s=Be[n])!=null?s:0)+1,Ae(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,l=ro(o,{onProgress:c=>{let a=Math.floor(c*100);a!==i&&(i=a,Ae(n,{progress:a/100,version:o.version}))}});V={app_id:n,handle:l,forced:!!e},Re("start",n,o.version,e?"(forced)":""),l.promise.then(c=>{Re("installed",n,o.version,`${Date.now()-r}ms`),Ae(n,{status:"installed",progress:1,version:o.version}),hn(n,c)}).catch(c=>{var p;if(c instanceof ft){if(gn.has(n))return;Re("paused",n),Be[n]-=1,le.unshift(n),Ae(n,{status:Oe.has(n)?"paused":"queued",progress:0,version:o.version});return}let a=String((p=c==null?void 0:c.message)!=null?p:c);if(console.warn("[miniapp-queue] failed",n,a),Be[n]<gs){Ae(n,{status:"queued",progress:0,version:o.version,error:a}),setTimeout(()=>{var d;le.includes(n)||(V==null?void 0:V.app_id)===n||(le.push(n),Ye((d=st[n])!=null&&d.length?n:void 0))},hs);return}Ae(n,{status:"failed",progress:0,version:o.version,error:a}),hn(n,$(n))}).finally(()=>{V=null;let c=le.find(a=>{var p;return(p=st[a])==null?void 0:p.length});Ye(c)})},yn=(e,{front:t=!1}={})=>{if((V==null?void 0:V.app_id)===e)return;let n=le.indexOf(e);if(n>=0){if(!t)return;le.splice(n,1)}t?le.unshift(e):le.push(e)},ys=async e=>{let{host_id:t,client_token:n}=U(),o=new AbortController,r=setTimeout(()=>o.abort(),ds);try{let i=`${ht}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,l=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!l.ok)throw new Error(`host list ${e} ${l.status}`);return(await l.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},Dt=null,_n=()=>(Dt!=null||(Dt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(U().channels.map(ys)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(B.getState().catalog).filter(c=>!o[c]);U().storage.setString(fr,JSON.stringify(o)),B.setState({catalog:o}),await Promise.all(r.map(c=>wr(c,{by_user:!1}))),r.forEach(c=>Xe.delete(c));let i=Object.keys(o).filter(c=>!Xe.has(c)),l=[],s={};for(let c of i.map(a=>o[a])){if(await no(c)){Ae(c.app_id,{status:"installed",progress:1,version:c.version});continue}let a=$(c.app_id);if(mr(c.app_id)&&!fn.has(c.app_id)&&a&&await Ve(a)){Ae(c.app_id,{status:"installed",progress:1,version:a.version}),s[c.app_id]={app_id:c.app_id,current_version:a.version,next_version:c.version};continue}l.push(c)}return B.setState({updates:s}),l.forEach(c=>{Be[c.app_id]=0,Ae(c.app_id,{status:Oe.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),yn(c.app_id)}),Re("catalog",i.length,"apps, outdated",l.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),He({type:"sync_complete",app_ids:i,removed:r}),Object.values(s).forEach(c=>He({type:"update_available",...c})),Ye(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),He({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{Dt=null}})()),Dt),wr=async(e,{by_user:t})=>{var r,i,l,s;if(t&&Xe.add(e),gn.has(e))return;gn.add(e),Oe.delete(e);let n=le.indexOf(e);n>=0&&le.splice(n,1),(V==null?void 0:V.app_id)===e&&V.handle.cancel();let o=(s=(l=(r=B.getState().downloads[e])==null?void 0:r.version)!=null?l:(i=$(e))==null?void 0:i.version)!=null?s:"";Ae(e,{status:"uninstalling",progress:0,version:o}),await lr(e),dn(e),B.setState(c=>{let a={...c.downloads};return delete a[e],{downloads:a}}),delete Be[e],gn.delete(e),hn(e,null),Re("uninstalled",e,t?"(user)":"(not in list)"),He({type:"uninstalled",app_id:e})},Ar=e=>wr(e,{by_user:!0}),Sr=e=>{let t=_t(e);return t?(Xe.delete(e),(V==null?void 0:V.app_id)===e||le.includes(e)||(Be[e]=0,Ae(e,{status:Oe.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),yn(e),Ye(),Re("restore",e)),!0):!1},Mr=e=>{if(Oe.has(e))return;if(Oe.add(e),Re("pause app",e),(V==null?void 0:V.app_id)===e&&!V.forced){V.handle.cancel();return}let t=B.getState().downloads[e];le.includes(e)&&t&&Ae(e,{status:"paused",progress:0,version:t.version})},vr=e=>{if(!Oe.delete(e))return;Re("resume app",e);let t=B.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!le.includes(e)&&_t(e)&&(Be[e]=0,yn(e)),le.includes(e)&&t&&Ae(e,{status:"queued",progress:0,version:t.version}),Ye()},xr=e=>{let{pause_reasons:t}=B.getState();t.includes(e)||(B.setState({pause_reasons:[...t,e]}),Re("pause",e),t.length===0&&He({type:"pause_change",paused:!0,reasons:[e]}),V&&!V.forced&&V.handle.cancel())},Cr=e=>{let{pause_reasons:t}=B.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);B.setState({pause_reasons:n}),Re("resume",e),n.length===0&&He({type:"pause_change",paused:!1,reasons:n}),Ye()},so=e=>B.getState().updates[e],bn=async e=>{var n,o;let t=so(e);fn.add(e);try{let r=await Nt(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=_t(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(B.setState(l=>{var c;let s={...l.updates};return delete s[e],{updates:s,apply_ticks:{...l.apply_ticks,[e]:((c=l.apply_ticks[e])!=null?c:0)+1}}}),Re("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),He({type:"update_applied",app_id:e,version:r.version}),!0)}finally{fn.delete(e)}},Er=()=>Object.values(B.getState().catalog).map(e=>({...e,installed:!!$(e.app_id),removed_by_user:Xe.has(e.app_id)})),_t=e=>B.getState().catalog[e],Nt=async e=>{let t=_t(e);if(!t)return;if(Oe.delete(e),Xe.delete(e),await no(t))return $(e);let n=$(e);if(mr(e)&&!fn.has(e)&&n&&await Ve(n))return n;let o=new Promise(r=>{var i;((i=st[e])!=null?i:st[e]=[]).push(r)});return(V==null?void 0:V.app_id)===e?V.forced=!0:(Be[e]=0,yn(e,{front:!0}),V&&!V.forced?V.handle.cancel():Ye(e)),o};var Pr=e=>`changelog_seen:${e}`,_s=10*1e3,wn=e=>U().storage.getString(Pr(e))||null,wt=(e,t=(n=>(n=$(e))==null?void 0:n.version)())=>{t&&U().storage.setString(Pr(e),t)},An=e=>{var o;let t=(o=$(e))==null?void 0:o.version;if(!t)return null;let n=wn(e);return n?oo(t,n)>0?{app_id:e,from:n,to:t}:null:(wt(e,t),null)},bs=e=>{var t,n,o;return(o=(n=(t=B.getState().catalog[e])==null?void 0:t.channel)!=null?n:U().channels[0])!=null?o:"production"},Vt=async(e,{from:t,to:n,channel:o=bs(e)}={})=>{let{client_token:r}=U(),i=new URLSearchParams({channel:o});t&&i.set("from",t),n&&i.set("to",n);let l=new AbortController,s=setTimeout(()=>l.abort(),_s);try{let c=await fetch(`${ht}/api/miniapps/${encodeURIComponent(e)}/changelog?${i}`,{headers:{Authorization:`Bearer ${r}`},signal:l.signal});if(!c.ok)throw new Error(`changelog ${e} ${c.status}`);return(await c.json()).versions}finally{clearTimeout(s)}},Sn=(e,{from:t,to:n,enabled:o=!0}={})=>{let[r,i]=(0,qe.useState)([]),[l,s]=(0,qe.useState)(!1),[c,a]=(0,qe.useState)(),[p,d]=(0,qe.useState)(0),m=(0,qe.useCallback)(()=>d(u=>u+1),[]);return(0,qe.useEffect)(()=>{if(!e||!o)return;let u=!0;return s(!0),a(void 0),Vt(e,{from:t,to:n}).then(S=>{u&&i(S)}).catch(S=>{var v;u&&a(String((S==null?void 0:S.name)==="AbortError"?"timeout":(v=S==null?void 0:S.message)!=null?v:S))}).finally(()=>{u&&s(!1)}),()=>{u=!1}},[e,t,n,o,p]),{versions:r,loading:l,error:c,reload:m}},ze=De({request:null,history:null}),Ut=!1,ao=e=>{var t,n;return(n=(t=B.getState().catalog[e])==null?void 0:t.name)!=null?n:e},ws=async e=>{var i,l,s,c;let t=(i=$(e))==null?void 0:i.version;if(!t)return null;let n=An(e),o=await Vt(e,n?{from:n.from,to:n.to}:{to:t}),r=n&&o.length?o:o.slice(0,1);return r.length?{app_id:e,name:ao(e),from:(c=(s=n==null?void 0:n.from)!=null?s:(l=o[1])==null?void 0:l.version)!=null?c:r[0].version,to:t,versions:r}:null},bt=async(e,{name:t,force:n=!1}={})=>{if(ze.getState().request||Ut)return!1;if(n){Ut=!0;try{let r=await ws(e);return r&&ze.setState({request:{...r,name:t!=null?t:r.name}}),!!r}catch(r){return ye("changelog failed",e,r),!1}finally{Ut=!1}}let o=An(e);if(!o)return!1;Ut=!0;try{let r=await Vt(e,{from:o.from,to:o.to});return r.length?(ze.setState({request:{...o,name:t!=null?t:ao(e),versions:r}}),!0):(wt(e,o.to),!1)}catch(r){return ye("changelog failed",e,r),!1}finally{Ut=!1}},Mn=()=>{let{request:e}=ze.getState();e&&wt(e.app_id,e.to),ze.setState({request:null})},vn=()=>J(ze,e=>e.request),xn=(e,{name:t}={})=>{ze.setState({history:{app_id:e,name:t!=null?t:ao(e)}})},Cn=()=>ze.setState({history:null}),En=()=>J(ze,e=>e.history),Tr=!1;an(()=>{if(Tr)return;Tr=!0;let e=()=>U().changelog!==!1;mn(n=>{n.type==="status_change"&&n.state.status==="installed"&&!wn(n.app_id)&&wt(n.app_id,n.state.version),n.type==="update_applied"&&e()&&bt(n.app_id)});let t=ce.getState().active_key;ce.subscribe(()=>{let{active_key:n,instances:o}=ce.getState();if(n===t)return;t=n;let r=n?o[n]:void 0;r&&e()&&bt(r.app.app_id,{name:r.app.name})})});var Ce=require("react-native");var at=require("react-native");var xe,At=new Map,kr=(e,t)=>{var o;let n=(o=At.get(e))!=null?o:new Set;n.add(t),At.set(e,n)},Rr=(e,t)=>{let n=At.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&At.delete(e))},co=new Map,Or=(e,t)=>{co.set(e,t)},Ir=e=>co.get(e),Fr=()=>at.Platform.OS==="android"&&!!(xe!=null&&xe.requesting_permission),As=1500,Tn=()=>new Promise(e=>{if(at.Platform.OS!=="android"||at.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,As),o=at.AppState.addEventListener("change",r=>{r==="active"&&t()})}),lo=e=>{var t;if(xe===e&&(xe=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&at.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Lr=async(e,t,n,o=()=>!0)=>{var i,l,s,c,a;if(xe)throw new f("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};xe=r;try{let p;try{p=await import("expo-speech-recognition")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=p.ExpoSpeechRecognitionModule;if(r.native=d,r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let m;try{m=await d.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await Tn(),r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!m.granted)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new f("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(d.addListener("result",u=>{var S,v;xe!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(v=(S=u.results[0])==null?void 0:S.transcript)!=null?v:""})}),d.addListener("error",u=>{xe===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),d.addListener("end",()=>{xe===r&&(lo(r),n("speech.end"))})),r.started=!0,d.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(l=t.continuous)!=null?l:!0,interimResults:(s=t.interimResults)!=null?s:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(a=t.requiresOnDeviceRecognition)!=null?a:!1,iosCategory:{category:p.AVAudioSessionCategory.playAndRecord,categoryOptions:[p.AVAudioSessionCategoryOptions.defaultToSpeaker,p.AVAudioSessionCategoryOptions.allowBluetooth],mode:p.AVAudioSessionMode.measurement}})}catch(p){throw lo(r),p}},Dr=e=>{let t=xe;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Ne=e=>{co.delete(e);let t=At.get(e);At.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=xe;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{lo(n)}};var Nr={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},pe={...Nr,all:Object.values(Nr)},St={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},kn={result:"scanner.result",end:"scanner.end"},lt={user:"user",web:"web",closed:"closed",error:"error"},Se={top:"top",full:"full"},Qe={once:"once",continuous:"continuous"},Ss=1500,Ur=6e4,X,ae=De({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Br=()=>Ce.Platform.OS==="android"&&!!(X!=null&&X.requesting_permission),uo=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},l={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(s=>pe.all.includes(s)))throw new f("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");l.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Ur)throw new f("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Ur}`);l.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new f("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");l.hint=o}if(r!==void 0){if(!Object.values(Se).includes(r))throw new f("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");l.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new f("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");l.absolute=i}return l},go=e=>X!==e?!1:(X=void 0,ae.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Ms=()=>Ce.Alert.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{Ce.Linking.openSettings().catch(()=>{})}}]),Hr=async(e,t)=>{if(X)throw new f("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");X=e;let n=()=>{if(e.cancelled||!t())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let l=Ce.Platform.OS==="ios"&&r==="denied";e.requesting_permission=!0;let s;try{s=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await Tn(),n(),s!=="granted")throw l&&Ms(),new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(l=>l.position==="back"))throw new f("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await Bt();n(),ae.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw go(e),o}},Pn;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{Pn=e==null?void 0:e.insets}).catch(()=>{});var Mt=()=>{var e;return Pn!=null?Pn:{top:Ce.Platform.OS==="ios"?54:(e=Ce.StatusBar.currentHeight)!=null?e:0,bottom:Ce.Platform.OS==="ios"?34:48}},Bt=async()=>{if(Ce.Platform.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},qr=(e,t,n)=>{var o,r,i,l;return{owner:e,mode:t,types:(o=n.types)!=null?o:pe.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Ss,hint:n.hint,layout:t===Qe.once?Se.full:(i=n.layout)!=null?i:Se.top,absolute:t!==Qe.once&&((l=n.layout)!=null?l:Se.top)===Se.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},zr=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let l=qr(e,Qe.once,t);l.onHit=o,l.resolve=r,l.reject=i,Hr(l,n).catch(i)}),$r=(e,t,n,o=()=>!0,r)=>{let i=qr(e,Qe.continuous,t);return i.emit=n,i.onHit=r,Hr(i,o)},Rn=(e,t,n)=>{var o,r;if(!ae.getState().active){e.cancelled=!0;return}if(go(e)){if(e.mode===Qe.once){(o=e.reject)==null||o.call(e,t===lt.error?new f("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new f("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,kn.end,n?{reason:t,message:n}:{reason:t})}},Wr=e=>{(X==null?void 0:X.owner)===e&&Rn(X,lt.web)},Ze=e=>{(X==null?void 0:X.owner)===e&&Rn(X,lt.closed)},ho=()=>{X&&Rn(X,lt.user)},jr=e=>{X&&Rn(X,lt.error,e)},fo=(e,t=Date.now(),n=!1)=>{var r,i,l;let o=X;if(!(!o||!ae.getState().active))for(let{value:s,type:c}of e){if(!s)continue;let a=o.last_seen.get(s);if(o.last_seen.set(s,t),!(!n&&a!==void 0&&t-a<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Qe.once){go(o),(i=o.resolve)==null||i.call(o,{value:s,type:c});return}ae.setState(p=>({last_value:s,hit_tick:p.hit_tick+1,scan_count:p.scan_count+1,notice:null})),(l=o.emit)==null||l.call(o,kn.result,{value:s,type:c})}}},vs={1:pe.code128,2:pe.code39,4:pe.code93,8:pe.codabar,16:pe.dataMatrix,32:pe.ean13,64:pe.ean8,128:pe.itf,256:pe.qr,512:pe.upcA,1024:pe.upcE,2048:pe.pdf417,4096:pe.aztec},xs=2500,Vr=2e3,po=e=>{ae.setState({notice:e}),setTimeout(()=>{ae.getState().notice===e&&ae.setState({notice:null})},xs)},Gr=async()=>{var t,n;let e=X;if(!(!e||ae.getState().is_picking)){e.requesting_permission=!0,ae.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:Vr,maxHeight:Vr}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||X!==e)return;if(r.errorCode||!i){po("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:l}=await import("@react-native-ml-kit/barcode-scanning"),s=await l.scan(i);if(X!==e)return;let c=s.map(({value:a,format:p})=>({value:a,code_type:vs[p]})).filter(({code_type:a})=>!a||e.types.includes(a)).map(({value:a,code_type:p})=>({value:a,type:p!=null?p:"unknown"}));if(!c.length){po("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}fo(c,Date.now(),!0)}catch{X===e&&po("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await Tn(),e.requesting_permission=!1,X===e&&ae.setState({is_picking:!1})}}};var zt=1,f=class extends Error{constructor(n,o){super(o);this.code=n}},Jr=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===zt&&typeof t.method=="string"?t:null}catch{return null}},$t=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Kr=(e,t)=>$t({id:e,result:t}),Yr=(e,t)=>$t({id:e,error:{code:t.code,message:t.message}}),Xr=(e,t)=>$t({event:e,data:t}),yo=e=>$t({event:"context",data:e});var Qr=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -60,10 +60,10 @@
60
60
  });
61
61
  };
62
62
  })(); true;`,ti=e=>$t({event:e}),ni=(e,t)=>{let n=oi(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${bo(e)}`},oi=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ri=(e,t={},{keyboard_mode:n}={})=>{let o=oi(t);return`window.__RETION_MINIAPP_HOST__ = ${JSON.stringify(n?{protocol:zt,keyboard_mode:n}:{protocol:zt})};
63
+ ${yo(e)}`},oi=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ri=(e,t={},{keyboard_mode:n}={})=>{let o=oi(t);return`window.__RETION_MINIAPP_HOST__ = ${JSON.stringify(n?{protocol:zt,keyboard_mode:n}:{protocol:zt})};
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${o?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(o)} + location.hash); } catch (e) {}`:""}
66
- true;`},ii={partner:"partner_token",chatbox:"chatbox_token"},si=(e,t)=>{let n={...e};for(let o of Object.values(ii))t.includes(o)||delete n[o];return n},yo=new Set,Ht=async(e,t)=>{if(yo.has(e))throw new f("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);yo.add(e);try{return await t()}finally{yo.delete(e)}},_o=e=>`(function () {
66
+ true;`},ii={partner:"partner_token",chatbox:"chatbox_token"},si=(e,t)=>{let n={...e};for(let o of Object.values(ii))t.includes(o)||delete n[o];return n},mo=new Set,Ht=async(e,t)=>{if(mo.has(e))throw new f("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);mo.add(e);try{return await t()}finally{mo.delete(e)}},_o=e=>`(function () {
67
67
  window.__retionScannerHeight = ${Math.max(0,Math.round(e))};
68
68
  window.dispatchEvent(new Event('retionscannerheight'));
69
69
  })(); true;`,ai=()=>`(function () {
@@ -85,5 +85,5 @@
85
85
  // iOS c\xF3 th\u1EC3 \u0111\u1EC3 context \u1EDF suspended / interrupted (vd. khi camera m\u1EDF phi\xEAn quay): ch\u1EA1y l\u1EA1i xong m\u1EDBi ph\xE1t.
86
86
  if (ctx.state === 'running') { play(); } else { ctx.resume().then(play).catch(function () {}); }
87
87
  } catch (e) {}
88
- })(); true;`,Cs=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),On=(e,t)=>{if(typeof e!="string"||!e)throw new f("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},li=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:l,app_id:s,instance_id:c,options:a,emit:p,isActive:d,playBeep:m})=>{var C,x,j,A,G,Q,me,Y;let u=a==null?void 0:a.handlers,S={app_id:s,instance_id:c,close:l},v=()=>{var h;(h=a==null?void 0:a.haptic)==null||h.call(a,"impactLight"),m==null||m()},D=()=>new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Uo(t);return Ht(e,()=>Vo(h,d))}case"speech.start":{if(!p)throw D();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new f("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let w of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[w])!==void 0){if(typeof t[w]!="boolean")throw new f("INVALID_PARAMS",`${w} ph\u1EA3i l\xE0 boolean`);h[w]=t[w]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new f("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let L=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",R=L==="voice"?(C=a==null?void 0:a.voice)!=null?C:a==null?void 0:a.speech:void 0;if(Or(c,R),R){kr(c,R);try{return await R.start({owner:c,app_id:s,mode:L,options:h,emit:p,isActive:d!=null?d:(()=>!0)})}catch(w){throw Rr(c,R),w}}return Lr(c,h,p,d)}case"speech.stop":{let h=Ir(c);return h?h.stop(c):Dr(c)}case St.scan:return zr(c,go(t),d,v);case St.start:{if(!p)throw D();return $r(c,go(t),p,d,v)}case St.stop:return Wr(c);case"uploadFiles":{let{task_id:h,...L}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new f("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return nr(Go(L),{instance_id:c,app_id:s,getContext:r,task_id:h,config:a==null?void 0:a.upload,emit:p,exclusivePick:R=>Ht("uploadFiles.pick",R)})}case"uploadFiles.cancel":tr(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Zo(a==null?void 0:a.upload);case"getBiometricAvailability":return((x=a==null?void 0:a.biometrics)!=null?x:await Jn()).getAvailability();case"authenticateBiometric":{let h=On(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new f("INVALID_PARAMS","reason must contain 1\u2013200 characters");let L=t==null?void 0:t.cancelButtonText;if(L!==void 0&&(typeof L!="string"||!L.trim()||L.length>80))throw new f("INVALID_PARAMS","Invalid cancelButtonText");return Ht(e,async()=>{var w;return((w=a==null?void 0:a.biometrics)!=null?w:await Jn()).authenticate({reason:h,cancelButtonText:L})})}case"requestPayment":{let h=u==null?void 0:u.requestPayment;if(!h)throw D();let L=t==null?void 0:t.amount;if(typeof L!="number"||!Number.isFinite(L)||L<=0)throw new f("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let R={...t,amount:L,currency:On(t==null?void 0:t.currency,"currency")};return Ht(e,()=>h(R,S))}case"printImage":{let h=u==null?void 0:u.printImage;if(!h)throw D();let L=On(t==null?void 0:t.image,"image");await Ht(e,()=>h({image:L},S));return}case"openScreen":if(!(u!=null&&u.openScreen))throw D();await u.openScreen({screen:On(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},S);return;case"closeApp":l();return;case"openWebview":{let h=String((j=t==null?void 0:t.url)!=null?j:"");if(!/^https?:\/\//i.test(h))throw new f("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(a!=null&&a.openUrl?a.openUrl(h):qt.Linking.openURL(h));return}case"openLink":{let h=String((A=t==null?void 0:t.url)!=null?A:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new f("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(a!=null&&a.openUrl?a.openUrl(h):qt.Linking.openURL(h))}catch(L){throw new f("NOT_SUPPORTED",String((Q=(G=L==null?void 0:L.message)!=null?G:L)!=null?Q:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=rr(t);if(!h||(d==null?void 0:d())===!1)return;a!=null&&a.showToast?a.showToast(h.message,{type:h.type}):ir(h.message,h.type);return}case"changelog.openPopup":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;return(d==null?void 0:d())===!1?{shown:!1}:{shown:await _t(h,{force:(t==null?void 0:t.force)===!0})}}case"changelog.openHistory":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;(d==null?void 0:d())!==!1&&xn(h);return}case"haptic":{let h=Cs.has(t==null?void 0:t.type)?t.type:"selection";(me=a==null?void 0:a.haptic)==null||me.call(a,h);return}case"getSystemInfo":return{platform:qt.Platform.OS==="ios"?"ios":"android",appVersion:(Y=a==null?void 0:a.app_version)!=null?Y:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let w=n().access_token;if(!w)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}if(h!=="partner"&&h!=="chatbox")throw new f("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let L=ii[h];if(!o().includes(L))throw new f("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${L} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let R=h==="partner"?n().partner_token:n().chatbox_token;if(!R)throw new f("HOST_ERROR",`Kh\xF4ng c\xF3 ${L}`);return R}case"getUserInfo":{let h=n().user;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new f("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Wt=new Map,ci=(e,t)=>(Wt.set(e,t),()=>{Wt.get(e)===t&&Wt.delete(e)}),In=(e,t)=>{let n=Wt.get(e);return n?n(t):!1},pi=e=>{let t=0;return Wt.forEach(n=>{n(e)&&(t+=1)}),t};var Dn=1,Es="retion.ai.agent",Ao="retion.ai.message",So="retion.ai.stopped",Mo="retion.ai.payload_meta",vo="retion.ai.payload_meta_result",Ln=new Map,gi=null,Fn="[miniapp:agent]",ui=e=>{try{let t=JSON.stringify(e);return t&&t.length>300?`${t.slice(0,300)}\u2026`:t}catch{return String(e)}},wo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ts=e=>{try{let t=JSON.parse(e);return wo(t)?t:null}catch{return null}},Ps=(e,t)=>In(e,JSON.stringify({v:Dn,...t})),di=(e,t)=>{var r;let n=(r=Ln.get(e))!=null?r:"",o=pi(JSON.stringify({v:Dn,app_id:n,agent_id:e,...t}));return console.log(Fn,`${String(t.type)} \u2192 ${o} WebView`,`app_id=${n||"(ch\u01B0a bi\u1EBFt)"}`,`agent_id=${e||"(tr\u1ED1ng)"}`),o},hi=(e,t,n)=>{let o=Ts(e);if(!o)return!1;if(o.type===Es){let a=typeof o.agent_id=="string"?o.agent_id:"",p=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id;return a&&(Ln.get(a)!==p&&console.log(Fn,"ghi nh\u1EADn agent",a,"\u2192 app",p),Ln.set(a,p),gi=a),!1}if(o.type!==Mo)return!1;let r=typeof o.request_id=="string"?o.request_id:"",i=a=>{console.log(Fn,"payload_meta_result \u2192",t.instance_id,r,ui(a)),r&&Ps(t.instance_id,{type:vo,request_id:r,...a})};if(!n)return i({ok:!1,error:"unsupported"}),!0;if(!wo(o.payload_meta))return i({ok:!1,error:"invalid"}),!0;console.log(Fn,"payload_meta \u2190",t.instance_id,r,ui(o.payload_meta));let l=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id,s=typeof o.agent_id=="string"&&o.agent_id?o.agent_id:void 0,c=typeof o.text=="string"?o.text:"";return Promise.resolve().then(()=>n.sendPayloadMeta({app_id:l,agent_id:s,text:c,payload_meta:o.payload_meta})).then(a=>i({...wo(a)?a:null,ok:!!(a!=null&&a.ok)})).catch(a=>{console.warn("[miniapp] agent sendPayloadMeta l\u1ED7i",a),i({ok:!1,error:"send_failed"})}),!0},fi=e=>e.subscribe({message:({agent_id:t,fb_client_id:n,raw:o})=>{di(t!=null?t:"",{type:Ao,fb_client_id:n,raw:o})},stopped:({agent_id:t,source:n})=>{di(t||gi||"",{type:So,source:n})}}),mi=e=>{var t;return(t=Ln.get(e))!=null?t:null};var K=require("react"),b=require("react-native");var P=require("react/jsx-runtime"),jt="#22C55E",ks="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",Rs=2,Un=18,Os=1600,Gt=14,Is=2e3,_i=.38,Fs=40,yi=2,Ls=8,Ds=2e3,Ns=250,vt=2e3,Us=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:Gt},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:Gt},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:Gt},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:Gt}],bi=({color:e})=>(0,P.jsx)(P.Fragment,{children:Us.map((t,n)=>(0,P.jsx)(b.View,{style:[T.corner,t,{borderColor:e}]},n))}),Nn=({style:e,children:t,...n})=>{let o=(0,K.useRef)(new b.Animated.Value(1)).current,r=i=>b.Animated.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return(0,P.jsx)(b.Pressable,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:(0,P.jsx)(b.Animated.View,{style:[e,{transform:[{scale:o}]}],children:t})})},Co=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var on,rn;let{vision:r,types:i,mode:l,layout:s,hint:c,glass_view:a,absolute:p}=e,d=s===Se.top,m=(0,K.useRef)(new b.Animated.Value(0)).current,u=r.useCameraDevice("back"),S=(0,K.useRef)(new b.Animated.Value(1)).current,[v,D]=(0,K.useState)(!1),[C,x]=(0,K.useState)(1),j=(0,K.useRef)(null),[A,G]=(0,K.useState)(()=>{let{width:k,height:ie}=b.Dimensions.get("window");return{width:k,height:d?ie*_i:ie,window_y:0}}),Q=J(ae,k=>k.last_value),me=J(ae,k=>k.hit_tick),Y=J(ae,k=>k.scan_count),h=J(ae,k=>k.notice),L=J(ae,k=>k.is_picking),R=(0,K.useRef)(null),w=Mt(),be=w.top,te=(0,K.useRef)(new b.Animated.Value(0)).current,H=(0,K.useRef)(new b.Animated.Value(0)).current,ge=(0,K.useRef)(new b.Animated.Value(0)).current,Ie=(0,K.useRef)(n);Ie.current=n,(0,K.useEffect)(()=>{if(!t)return;m.setValue(A.height);let k=b.Animated.timing(m,{toValue:0,duration:Ns,easing:b.Easing.out(b.Easing.cubic),useNativeDriver:!1});return k.start(({finished:ie})=>{var g;ie&&((g=Ie.current)==null||g.call(Ie))}),()=>k.stop()},[t,m]);let We=Math.round(A.width*(d?.8:.78)),re=Math.round(d?A.height*.46:We*.78),Fe=Math.round((A.height-re)/2),ne=Math.round((A.width-We)/2),_e=r.useCodeScanner({codeTypes:i,onCodeScanned:(0,K.useCallback)(k=>mo(k),[])});(0,K.useEffect)(()=>{let k=b.BackHandler.addEventListener("hardwareBackPress",()=>(fo(),!0));return()=>k.remove()},[]);let tt=(0,K.useRef)(me);(0,K.useEffect)(()=>{if(me===tt.current)return;te.setValue(1),ge.setValue(1);let k=b.Animated.parallel([b.Animated.timing(te,{toValue:0,duration:450,useNativeDriver:!0}),b.Animated.sequence([b.Animated.delay(Is),b.Animated.timing(ge,{toValue:0,duration:250,useNativeDriver:!0})])]);return k.start(),()=>k.stop()},[me,te,ge]),(0,K.useEffect)(()=>{let k=g=>b.Animated.timing(H,{toValue:g,duration:Os,easing:b.Easing.inOut(b.Easing.quad),useNativeDriver:!0}),ie=b.Animated.loop(b.Animated.sequence([k(1),k(0)]));return ie.start(),()=>ie.stop()},[H]);let Tt=(0,K.useCallback)(()=>{b.Animated.timing(S,{toValue:0,duration:220,useNativeDriver:!0}).start()},[S]);(0,K.useEffect)(()=>{let k=setTimeout(Tt,Ds);return()=>clearTimeout(k)},[Tt]);let[en,tn]=(0,K.useState)(!1);(0,K.useEffect)(()=>{let k=requestAnimationFrame(()=>{k=requestAnimationFrame(()=>tn(!0))});return()=>cancelAnimationFrame(k)},[]);let je=!!(u!=null&&u.hasTorch),Ge=(on=u==null?void 0:u.neutralZoom)!=null?on:1,nt=u?Math.min(u.maxZoom/Ge,Ls):1,Wn=Ge*Math.min(C,nt),gt=k=>{var _;let{touches:ie}=k.nativeEvent;if(ie.length!==2){j.current=null;return}let g=Math.hypot(ie[0].pageX-ie[1].pageX,ie[0].pageY-ie[1].pageY);(_=j.current)!=null||(j.current={distance:g,level:C}),x(Math.max(1,Math.min(nt,j.current.level*(g/j.current.distance))))},nn=(0,P.jsx)(b.Text,{style:[T.hint,!!h&&T.hint_notice],numberOfLines:1,children:(rn=h!=null?h:c)!=null?rn:ks});return(0,P.jsx)(b.Animated.View,{ref:R,onTouchMove:gt,onTouchEnd:()=>{j.current=null},pointerEvents:t?"none":"auto",style:d?[T.top,p&&T.top_absolute,t&&{height:m}]:T.full,onLayout:({nativeEvent:{layout:k}})=>{var ie;t||(o==null||o(k.height),(ie=R.current)==null||ie.measureInWindow((g,_)=>{G({width:k.width,height:k.height,window_y:_||0})}))},children:(0,P.jsxs)(b.View,{style:t?[T.content_closing,{height:A.height}]:T.content,children:[u&&en&&(0,P.jsx)(r.Camera,{style:b.StyleSheet.absoluteFill,device:u,isActive:!L,codeScanner:_e,torch:v&&je?"on":"off",zoom:Wn,onPreviewStarted:Tt,onError:k=>jr(k.message)}),(0,P.jsx)(b.Animated.View,{style:[T.preview_cover,{opacity:S}],pointerEvents:"none"}),A.height>0&&(0,P.jsxs)(b.View,{style:T.overlay,pointerEvents:"none",children:[(0,P.jsx)(b.View,{style:[T.dim_ring,{top:Fe-vt,left:ne-vt,width:We+vt*2,height:re+vt*2}]}),(0,P.jsxs)(b.View,{style:{position:"absolute",top:Fe,left:ne,width:We,height:re},children:[(0,P.jsx)(bi,{color:"#FFFFFF"}),(0,P.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:te}],children:(0,P.jsx)(bi,{color:jt})}),(0,P.jsxs)(b.Animated.View,{style:[T.scan_line_wrap,{transform:[{translateY:H.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,re-Un)]})}]}],children:[(0,P.jsx)(b.View,{style:T.scan_glow_outer}),(0,P.jsx)(b.View,{style:T.scan_glow_inner}),(0,P.jsx)(b.View,{style:T.scan_line})]})]}),(0,P.jsx)(b.View,{style:[T.hint_slot,d?{top:0,height:Fe-6,justifyContent:"flex-end"}:{top:Fe+re+20}],children:nn}),l===Qe.continuous&&!!Q&&(0,P.jsx)(b.Animated.View,{style:[T.result_slot,{top:d?Fe+re-Fs:Fe+re+52},{opacity:ge}],children:(0,P.jsxs)(b.View,{style:T.result,children:[(0,P.jsx)(b.View,{style:T.check_badge,children:(0,P.jsx)(b.View,{style:T.check_mark})}),(0,P.jsx)(b.Text,{style:T.result_text,numberOfLines:1,children:Q}),(0,P.jsxs)(b.Text,{style:T.result_count,children:["\xB7 ",Y," m\xE3"]})]})})]}),A.height>0&&(0,P.jsx)(b.View,{style:[T.close_slot,d?T.close_slot_top:{top:Math.max(12,be-A.window_y+12)}],children:(0,P.jsxs)(Nn,{style:[T.close_button,!!a&&T.glass_surface],onPress:fo,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&(0,P.jsx)(a,{style:T.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,P.jsx)(b.View,{style:[T.close_bar,T.close_bar_a]}),(0,P.jsx)(b.View,{style:[T.close_bar,T.close_bar_b]})]})}),(0,P.jsx)(b.View,{style:[T.toolbar_wrap,!d&&{bottom:w.bottom+20}],pointerEvents:"box-none",children:(0,P.jsxs)(b.View,{style:[T.toolbar,!!a&&T.glass_surface],children:[a&&(0,P.jsx)(a,{style:T.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,P.jsx)(Nn,{style:T.tool,onPress:Gr,disabled:L,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:(0,P.jsxs)(b.View,{style:T.image_icon,children:[(0,P.jsx)(b.View,{style:T.image_icon_dot}),(0,P.jsx)(b.View,{style:T.image_icon_hill})]})}),!!u&&nt>=yi&&(0,P.jsx)(Nn,{style:[T.tool,C>1&&T.tool_on],onPress:()=>x(k=>k>1?1:yi),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:(0,P.jsxs)(b.Text,{style:[T.zoom_text,C>1&&T.zoom_text_on],children:[Math.round(C*10)/10,"x"]})}),je&&(0,P.jsx)(Nn,{style:[T.tool,v&&T.tool_on],onPress:()=>D(k=>!k),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:v},children:(0,P.jsx)(b.Text,{style:[T.torch_icon,v&&T.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},Vs="rgba(0,0,0,0.5)",xo=50,T=b.StyleSheet.create({top:{height:`${_i*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:vt,borderColor:Vs,borderRadius:vt+Gt},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:Un,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Un,borderRadius:Un/2,backgroundColor:jt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:jt,opacity:.2},scan_line:{height:Rs,borderRadius:1,backgroundColor:jt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:xo,height:xo,borderRadius:xo/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:jt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});var Ee=require("react"),I=require("react-native");var ee=require("react/jsx-runtime"),Eo={[ve.info]:"#3B82F6",[ve.success]:"#22C55E",[ve.error]:"#EF4444"},wi=-120,Vn=I.Platform.OS==="android",Ai=({type:e})=>e===ve.success?(0,ee.jsx)(I.View,{style:ue.check_mark}):e===ve.error?(0,ee.jsxs)(ee.Fragment,{children:[(0,ee.jsx)(I.View,{style:[ue.cross_bar,ue.cross_a]}),(0,ee.jsx)(I.View,{style:[ue.cross_bar,ue.cross_b]})]}):(0,ee.jsxs)(ee.Fragment,{children:[(0,ee.jsx)(I.View,{style:ue.info_dot}),(0,ee.jsx)(I.View,{style:ue.info_bar})]}),Si=()=>{let e=J(It,m=>m.message),t=J(It,m=>m.type),n=J(It,m=>m.tick),o=(0,Ee.useRef)(new I.Animated.Value(wi)).current,r=(0,Ee.useRef)(new I.Animated.Value(0)).current,i=(0,Ee.useRef)(new I.Animated.Value(.92)).current,l=(0,Ee.useRef)(new I.Animated.Value(0)).current,[s,c]=(0,Ee.useState)(),[a,p]=(0,Ee.useState)(!1);(0,Ee.useEffect)(()=>{let m=!0;return Bt().then(u=>{m&&u&&c(()=>u)}),()=>{m=!1}},[]);let d=(0,Ee.useRef)(n);return(0,Ee.useEffect)(()=>{if(n===d.current)return;I.AccessibilityInfo.announceForAccessibility(e),p(!0),l.setValue(0),i.setValue(.92);let m=I.Animated.sequence([I.Animated.parallel([I.Animated.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),I.Animated.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),I.Animated.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),I.Animated.sequence([I.Animated.delay(90),I.Animated.spring(l,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),I.Animated.delay(or[t]),I.Animated.parallel([I.Animated.timing(o,{toValue:wi,duration:240,useNativeDriver:!0}),I.Animated.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return m.start(({finished:u})=>{u&&p(!1)}),()=>m.stop()},[n]),a?(0,ee.jsx)(I.View,{style:[ue.layer,{top:Mt().top+(Vn?12:8)}],pointerEvents:"none",children:(0,ee.jsxs)(I.Animated.View,{style:[ue.toast,Vn&&ue.toast_android,!!s&&ue.toast_glass,{opacity:s?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[s&&(0,ee.jsx)(s,{style:ue.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),Vn?(0,ee.jsx)(I.Animated.View,{style:[ue.badge_halo,{backgroundColor:`${Eo[t]}33`,transform:[{scale:l}]}],children:(0,ee.jsx)(I.View,{style:[ue.badge,{backgroundColor:Eo[t]}],children:(0,ee.jsx)(Ai,{type:t})})}):(0,ee.jsx)(I.Animated.View,{style:[ue.badge,{backgroundColor:Eo[t],transform:[{scale:l}]}],children:(0,ee.jsx)(Ai,{type:t})}),(0,ee.jsx)(I.Text,{style:[ue.message,Vn&&ue.message_android],numberOfLines:2,children:e})]})}):null},ue=I.StyleSheet.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:I.StyleSheet.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});var q=require("react/jsx-runtime"),To=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Mi=0,Bs=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Hs=e=>{let[t,n]=(0,M.useState)(0);return(0,M.useEffect)(()=>{if(!e||F.Platform.OS!=="ios"){n(0);return}let o=F.Keyboard.addListener("keyboardWillChangeFrame",i=>n(Math.max(0,i.endCoordinates.height))),r=F.Keyboard.addListener("keyboardWillHide",()=>n(0));return()=>{o.remove(),r.remove()}},[e]),t},qs=M.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:l,bridge:s,opaque_background:c,allow_embedded_miniapps:a,keyboard_mode:p,onWebLoadEnd:d})=>{var k,ie;let m=F.Platform.OS==="ios",u=m&&p!=="scroll",S=Hs(m&&p==="resize"&&t),v=(0,M.useRef)(null),D=(0,M.useRef)(!1),C=J(ce,g=>g.instances[e]),x=C==null?void 0:C.app.app_id,j=C==null?void 0:C.app.manifest_url,A=C==null?void 0:C.context,G=C==null?void 0:C.url_params,Q=J(ae,g=>{var _;return((_=g.active)==null?void 0:_.owner)===e?g.active:null}),[me,Y]=(0,M.useState)(null),[h,L]=(0,M.useState)(Q);Q!==h&&(L(Q),Q?Y(null):(h==null?void 0:h.layout)===Se.top&&Y(h));let R=(Q==null?void 0:Q.layout)===Se.top?Q:me,[w,be]=(0,M.useState)(()=>x?$(x):null),[te,H]=(0,M.useState)(!1),[ge,Ie]=(0,M.useState)(0),[We,re]=(0,M.useState)(0),[Fe,ne]=(0,M.useState)(!1),_e=(0,M.useRef)(null),tt=g=>{_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>{_e.current=null,ne(!0)},g)};(0,M.useEffect)(()=>()=>{_e.current&&clearTimeout(_e.current)},[]),(0,M.useEffect)(()=>{if(!x||!t&&w)return;let g=!0;return H(!1),(async()=>{let _=$(x),we=_?await Ve(_):!1;if(!g||(be(we?ke=>!ke||ke.version!==_.version||ke.permissions.join(",")!==_.permissions.join(",")?_:ke:null),__DEV__&&Date.now()-Mi>1e4&&(Mi=Date.now(),await bn()),!g))return;let Je=await Nt(x),ot=Je!==void 0?Je:j?await ur(x,j):$(x);if(g){if(!ot){H(!0);return}be(ke=>ke!=null?ke:ot)}})(),()=>{g=!1}},[t,x,j,ge]),(0,M.useEffect)(()=>ci(e,g=>v.current?(v.current.postMessage(g),!0):!1),[e]);let Tt=J(B,g=>{let _=x?g.downloads[x]:void 0;return(_==null?void 0:_.status)==="installed"?_.version:void 0});(0,M.useEffect)(()=>{if(t||!x||!w)return;let g=$(x);if(!g||g.version===w.version)return;let _=!0;return Ve(g).then(we=>{!_||!we||(ye(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",w.version,"\u2192",g.version),be(g))}),()=>{_=!1}},[t,x,Tt,w==null?void 0:w.version]);let en=J(B,g=>{var _;return x&&(_=g.apply_ticks[x])!=null?_:0});(0,M.useEffect)(()=>{if(!en||!x)return;let g=$(x);if(!g||g.version===(w==null?void 0:w.version))return;let _=!0;return Ve(g).then(we=>{!_||!we||(ye(`webview:${e}`,"c\u1EADp nh\u1EADt",w==null?void 0:w.version,"\u2192",g.version),ne(!1),be(g))}),()=>{_=!1}},[en]),(0,M.useEffect)(()=>{var we;let g=(we=U().keep_alive)==null?void 0:we.idle_close_ms;if(t||!g||g<=0)return;let _=setTimeout(()=>{dn(e)},g);return()=>clearTimeout(_)},[t,e]),(0,M.useEffect)(()=>{r>0&&(H(!1),ne(!1),re(g=>g+1),Ie(g=>g+1))},[r]);let tn=(0,M.useRef)(t);(0,M.useEffect)(()=>{var g;tn.current!==t&&(tn.current=t,D.current&&((g=v.current)==null||g.injectJavaScript(ti(t?"resumed":"paused"))))},[t]);let je=`${(k=w==null?void 0:w.version)!=null?k:"none"}:${(ie=w==null?void 0:w.permissions.join(","))!=null?ie:""}:${We}`,Ge=(0,M.useMemo)(()=>JSON.stringify([A!=null?A:{},G!=null?G:{}]),[A,G]),nt=(0,M.useMemo)(()=>{var g;return si(G!=null?G:{},(g=w==null?void 0:w.permissions)!=null?g:[])},[Ge,w==null?void 0:w.permissions]),Wn=(0,M.useMemo)(()=>ri(A!=null?A:{},nt,{keyboard_mode:u?p:void 0})+Zr()+ei()+(U().debug?Qr():""),[nt]),gt=(0,M.useRef)(null),nn=(0,M.useRef)(null);(0,M.useEffect)(()=>{var _,we,Je;if(!w)return;if(nn.current!==je){nn.current=je,gt.current=Ge;return}if(gt.current===Ge)return;let g=((we=JSON.parse((_=gt.current)!=null?_:"[]")[0])!=null?we:{}).org_id;if(gt.current=Ge,g===(A==null?void 0:A.org_id)&&D.current){ne(!1),tt(1500),(Je=v.current)==null||Je.injectJavaScript(ni(A!=null?A:{},nt));return}ne(!1),re(ot=>ot+1)},[Ge,w,je]),(0,M.useEffect)(()=>(t||(Ne(e),Ze(e),it(e)),()=>{Ne(e),Ze(e),it(e)}),[t,e,je,r]),(0,M.useEffect)(()=>{let g=F.AppState.addEventListener("change",_=>{_==="background"&&!Fr()&&Ne(e),_==="background"&&!Br()&&Ze(e)});return()=>g.remove()},[e]);let on=(0,M.useCallback)(async g=>{var we,Je,ot,ke,jn,Ro;let _=Jr(g.nativeEvent.data);if(!_){if(x&&hi(g.nativeEvent.data,{app_id:x,instance_id:e},s==null?void 0:s.agent))return;if(x&&(s!=null&&s.onWebEvent))try{Promise.resolve(s.onWebEvent(g.nativeEvent.data,{app_id:x,instance_id:e})).catch(Z=>{console.warn("[miniapp] onWebEvent l\u1ED7i",x,Z)})}catch(Z){console.warn("[miniapp] onWebEvent l\u1ED7i",x,Z)}return}if(_.method==="log"){let{level:Z,text:oe}=_;ye(`web:${e}`,Z!=null?Z:"log",oe!=null?oe:"");return}if(_.method==="pong"){_e.current||ne(!0);return}if(_.method==="touchAtTop"){i.emit(!!_.at_top);return}if(_.method==="contextApplied"){_e.current&&clearTimeout(_e.current),_e.current=null,ne(!0);return}if(_.method==="ready"){D.current=!0,ne(!0);let Z=(we=ce.getState().instances[e])==null?void 0:we.context;Z&&((Je=v.current)==null||Je.injectJavaScript(bo(Z)));return}try{let Z=await li(_,{getHostData:()=>{var oe,Me;return(Me=(oe=ce.getState().instances[e])==null?void 0:oe.host_data)!=null?Me:{}},getPermissions:()=>{var oe,Me;return x?(Me=(oe=$(x))==null?void 0:oe.permissions)!=null?Me:[]:[]},getContext:()=>{var oe,Me;return(Me=(oe=ce.getState().instances[e])==null?void 0:oe.context)!=null?Me:{}},is_dark:o,close:mt,app_id:x!=null?x:"",instance_id:e,options:s,emit:(oe,Me)=>{var Oo;(Oo=v.current)==null||Oo.injectJavaScript(Xr(oe,Me))},playBeep:(ot=s==null?void 0:s.playScannerBeep)!=null?ot:(()=>{var oe;(oe=v.current)==null||oe.injectJavaScript(ai())}),isActive:()=>ce.getState().active_key===e&&F.AppState.currentState!=="background"});_.id&&((ke=v.current)==null||ke.injectJavaScript(Kr(_.id,Z)))}catch(Z){if(!_.id)return;let oe=Z==null?void 0:Z.code,Me=Z instanceof f?Z:new f(typeof oe=="string"?oe:"HOST_ERROR",String((jn=Z==null?void 0:Z.message)!=null?jn:Z));(Ro=v.current)==null||Ro.injectJavaScript(Yr(_.id,Me))}},[e,o,x,i,s]),rn=(0,M.useCallback)(()=>{H(!1),re(g=>g+1),Ie(g=>g+1)},[]);return(0,q.jsxs)(F.View,{style:[F.StyleSheet.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&Te.behind],pointerEvents:t?"auto":"none",children:[R&&(0,q.jsx)(Co,{scanner:R,closing:R===me,onClosed:()=>{var g;Y(null),R.absolute&&((g=v.current)==null||g.injectJavaScript(_o(0)))},onHeight:R.absolute?g=>{var _;return(_=v.current)==null?void 0:_.injectJavaScript(_o(g))}:void 0}),w?(0,q.jsx)(xi.default,{ref:v,source:{uri:w.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${a?eo():w.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Wn,onMessage:on,onShouldStartLoadWithRequest:g=>{let _=g.url;return g.isTopFrame===!1||!/^https?:\/\//i.test(_)?!0:(Promise.resolve(s!=null&&s.openUrl?s.openUrl(_):F.Linking.openURL(_)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",scrollEnabled:!u,onLoadStart:g=>{Ne(e),Ze(e),it(e),ye(`webview:${e}`,"load start",To(g.nativeEvent.url)),D.current=!1,ne(!1)},onError:g=>{Ne(e),Ze(e),it(e),ye(`webview:${e}`,"load error",To(g.nativeEvent.url),g.nativeEvent.description),H(!0),ne(!1)},onLoadEnd:g=>{let _=g.nativeEvent.url;ye(`webview:${e}`,"load end",To(_)),x&&(d==null||d({app_id:x,instance_id:e,url:_})),tt(1500)},onContentProcessDidTerminate:()=>{Ne(e),Ze(e),it(e),D.current=!1,ne(!1),re(g=>g+1)},onRenderProcessGone:()=>(Ne(e),Ze(e),it(e),D.current=!1,ne(!1),re(g=>g+1),!0),style:[Te.webview,S>0&&{marginBottom:S}]},je):null,(Q==null?void 0:Q.layout)===Se.full&&(0,q.jsx)(Co,{scanner:Q}),C&&(0,q.jsx)($s,{visible:!w||!Fe,interactive:te,children:(0,q.jsx)(zs,{splash:l,app:C.app,is_dark:o,error:te,has_bundle:!!w,retry:rn})})]})}),zs=M.default.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let l=e,s=yt(t.app_id),c=o?"error":!r&&(s==null?void 0:s.status)==="downloading"?"downloading":"loading";return(0,q.jsx)(l,{app:t,is_dark:n,status:c,progress:c==="downloading"?s==null?void 0:s.progress:void 0,retry:i})}),$s=({visible:e,interactive:t,children:n})=>{let o=(0,M.useRef)(new F.Animated.Value(e?1:0)).current,[r,i]=(0,M.useState)(e);return(0,M.useEffect)(()=>{if(e){i(!0),o.setValue(1);return}let l=F.Animated.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return l.start(({finished:s})=>{s&&i(!1)}),()=>l.stop()},[e,o]),r?(0,q.jsx)(F.Animated.View,{style:[F.StyleSheet.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},Po=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return(0,q.jsxs)(F.View,{style:[Te.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,q.jsx)(F.View,{style:[Te.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,q.jsx)(F.Image,{source:{uri:e.icon},style:Te.splash_icon_image}):(0,q.jsx)(F.Text,{style:Te.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,q.jsx)(F.Text,{style:[Te.splash_name,{color:i}],children:e.name}),n==="error"?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(F.Text,{style:Te.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,q.jsx)(F.TouchableOpacity,{activeOpacity:.7,style:[Te.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,q.jsx)(F.Text,{style:[Te.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(F.ActivityIndicator,{style:Te.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,q.jsxs)(F.Text,{style:Te.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},vi=(e,t)=>{let n=(0,M.useRef)(t),o=(0,M.useRef)(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},Ws=({container:e,splash:t=Po,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:l=!1,keyboard_mode:s="scroll",onWebLoadEnd:c})=>{vi("container",e),vi("splash",t);let a=e,p=J(ce,A=>A.active_key),d=(0,M.useRef)(p);p&&(d.current=p);let m=J(ce,A=>Object.keys(A.instances).join("|")),u=J(ce,A=>{var G;return A.active_key?(G=A.instances[A.active_key])==null?void 0:G.app.name:void 0}),S=(0,M.useMemo)(()=>m?m.split("|"):[],[m]),[v,D]=(0,M.useState)({}),C=(0,M.useRef)(Bs()).current,x=o==null?void 0:o.agent;(0,M.useEffect)(()=>x?fi(x):void 0,[x]),(0,M.useEffect)(()=>{if(!p||!r)return;let A=F.BackHandler.addEventListener("hardwareBackPress",()=>(mt(),!0));return()=>A.remove()},[p,r]);let j=(0,M.useCallback)(()=>{let A=ce.getState().active_key;A&&D(G=>({...G,[A]:(G[A]||0)+1}))},[]);return S.length?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(a,{visible:!!p,title:u!=null?u:"",is_dark:n,close:mt,reload:j,subscribeWebAtTop:C.subscribe,children:S.map(A=>(0,q.jsx)(qs,{instance_key:A,is_active:p===A,is_front:(p!=null?p:d.current)===A,is_dark:n,reload_tick:v[A]||0,web_at_top:C,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:l,keyboard_mode:s,onWebLoadEnd:c},A))}),(0,q.jsx)(Si,{})]}):null},Te=F.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"}}),Ci=M.default.memo(Ws);var dt=he(require("react"));var $e=require("react"),E=require("react-native");var de=require("react-native");var js=/\*\*(.+?)\*\*|`([^`]+)`|\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,Jt=e=>{var o;let t=[],n=0;for(let r of e.matchAll(js)){let i=(o=r.index)!=null?o:0;i>n&&t.push({type:"text",text:e.slice(n,i)}),r[1]!==void 0?t.push({type:"bold",text:r[1]}):r[2]!==void 0?t.push({type:"code",text:r[2]}):t.push({type:"link",text:r[3],url:r[4]}),n=i+r[0].length}return n<e.length&&t.push({type:"text",text:e.slice(n)}),t},Ei=e=>Jt(e).map(t=>t.text).join("");var et=require("react-native");var xt=require("react"),ki=require("react/jsx-runtime"),Bn={changelog_title:"C\xF3 g\xEC m\u1EDBi",changelog_ok:"\u0110\xE3 hi\u1EC3u",changelog_view_all:"Xem t\u1EA5t c\u1EA3 c\u1EADp nh\u1EADt",changelog_more:"+{count} thay \u0111\u1ED5i kh\xE1c",history_title:"L\u1ECBch s\u1EED c\u1EADp nh\u1EADt",history_empty:"Ch\u01B0a c\xF3 ghi ch\xFA c\u1EADp nh\u1EADt.",history_error:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c l\u1ECBch s\u1EED c\u1EADp nh\u1EADt.",retry:"Th\u1EED l\u1EA1i",update_title:"\u0110\xE3 c\xF3 b\u1EA3n c\u1EADp nh\u1EADt",updating_title:"\u0110ang c\u1EADp nh\u1EADt\u2026",update_message:`Phi\xEAn b\u1EA3n {next} \u0111\xE3 s\u1EB5n s\xE0ng (hi\u1EC7n t\u1EA1i {current}).
89
- Vui l\xF2ng c\u1EADp nh\u1EADt \u0111\u1EC3 ti\u1EBFp t\u1EE5c s\u1EED d\u1EE5ng.`,update_failed:"C\u1EADp nh\u1EADt kh\xF4ng th\xE0nh c\xF4ng. Ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng r\u1ED3i th\u1EED l\u1EA1i.",update_now:"C\u1EADp nh\u1EADt ngay",updating_hint:"Vui l\xF2ng kh\xF4ng t\u1EAFt \u1EE9ng d\u1EE5ng",date_locale:"vi-VN"},Hn=(e,t)=>e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n),qn=[{key:"new",label:"M\u1EDBi",color:"#007AFF",bg:"#E5F1FF"},{key:"fix",label:"S\u1EEDa l\u1ED7i",color:"#C4320A",bg:"#FFF1EB"},{key:"improve",label:"C\u1EA3i thi\u1EC7n",color:"#067647",bg:"#E7F7EE"}],Ue={primary:"#007AFF",on_primary:"#FFFFFF",background:"#F2F2F7",surface:"#FFFFFF",text:"#1C1C1E",text_secondary:"#666666",hint:"#AEAEB2",overlay:"rgba(0, 0, 0, 0.6)",divider:"rgba(60, 60, 67, 0.18)",radius:28,button_radius:12,button_height:50},Gs={primary:"#0A84FF",on_primary:"#FFFFFF",background:"#000000",surface:"#1C1C1E",text:"#FFFFFF",text_secondary:"#A1A1AA",hint:"#636366",overlay:"rgba(0, 0, 0, 0.7)",divider:"rgba(84, 84, 88, 0.6)",radius:28,button_radius:12,button_height:50},Js={new:{color:"#64B5FF",bg:"rgba(10, 132, 255, 0.18)"},fix:{color:"#FF9F7A",bg:"rgba(255, 112, 67, 0.18)"},improve:{color:"#5FD39A",bg:"rgba(48, 209, 88, 0.18)"}},ko=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Kt=(e={},t)=>{let{kinds:n,dark:o=!1,...r}=e;return{...o?Gs:Ue,...ko(r),dark:o,labels:{...Bn,...ko(t!=null?t:{})},kinds:qn.map(i=>{var l;return{...i,...o?Js[i.key]:null,...i.key==="new"&&e.primary?{color:e.primary}:null,...ko((l=n==null?void 0:n[i.key])!=null?l:{})}})}},Ti=(0,xt.createContext)(void 0),Ks=Kt(),ct=({theme:e,labels:t,children:n})=>{let o=(0,xt.useMemo)(()=>Kt(e,t),[e,t]);return(0,ki.jsx)(Ti.Provider,{value:o,children:n})},Pe=()=>{var e;return(e=(0,xt.useContext)(Ti))!=null?e:Ks},Yt=e=>({new:e.flatMap(t=>t.changelog.new),fix:e.flatMap(t=>t.changelog.fix),improve:e.flatMap(t=>t.changelog.improve)}),Pi=(e,t)=>{let n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString(t)};var W={blue:Ue.primary,track:"#E5E5EA",overlay:Ue.overlay,shadow:"#000000",title:Ue.text,sub_title:Ue.text_secondary,error:"#D92D20",hint:Ue.hint,surface:Ue.surface,background:Ue.background},Ri=et.Platform.select({ios:{shadowColor:W.shadow,shadowOffset:{width:0,height:10},shadowOpacity:.1,shadowRadius:20},android:{elevation:10}}),y=et.StyleSheet.create({overlay:{flex:1,backgroundColor:W.overlay,justifyContent:"center",alignItems:"center"},container:{width:"85%",maxWidth:340,backgroundColor:W.surface,padding:24,borderRadius:28,alignItems:"center",...Ri},sheet:{width:"88%",maxWidth:380,maxHeight:"78%",backgroundColor:W.surface,borderRadius:28,overflow:"hidden",...Ri},sheet_head:{alignItems:"center",paddingTop:24,paddingHorizontal:22,paddingBottom:4},sheet_name:{fontSize:13,color:W.sub_title,marginTop:4,maxWidth:"100%"},version_pill:{flexDirection:"row",alignItems:"center",gap:6,marginTop:10,paddingHorizontal:12,paddingVertical:5,borderRadius:999,backgroundColor:W.background},version_old:{fontSize:13,color:W.sub_title,fontVariant:["tabular-nums"]},version_arrow:{fontSize:13,color:W.hint},version_new:{fontSize:13,fontWeight:"700",color:W.blue,fontVariant:["tabular-nums"]},sheet_foot:{paddingHorizontal:22,paddingTop:4,paddingBottom:18},sheet_foot_divider:{borderTopWidth:et.StyleSheet.hairlineWidth,borderTopColor:"rgba(60, 60, 67, 0.18)"},logo:{width:64,height:64,borderRadius:16,marginBottom:20},title:{fontSize:20,fontWeight:"700",color:W.title,textAlign:"center"},sub_title:{fontSize:13,color:W.sub_title,textAlign:"center",lineHeight:18,marginTop:6},gap:{marginBottom:15},error_text:{fontSize:12,textAlign:"center",color:W.error,lineHeight:17,marginBottom:15},progress_section:{width:"100%",alignItems:"center",paddingVertical:8,marginTop:8,gap:12},progress_text:{fontSize:18,fontWeight:"700",color:W.blue},progress_track:{width:"100%",height:6,borderRadius:3,backgroundColor:W.track,overflow:"hidden"},progress_fill:{height:"100%",borderRadius:3,backgroundColor:W.blue},loading_hint:{fontSize:12,color:W.hint,textAlign:"center"},scroll:{flexGrow:0,flexShrink:1},scroll_content:{paddingHorizontal:22,paddingTop:16,paddingBottom:16},groups:{gap:18},group:{gap:8},group_head:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:2},group_count:{fontSize:12,fontWeight:"600",color:W.hint},dot:{width:5,height:5,borderRadius:3,marginTop:8},more:{fontSize:14,fontWeight:"500",color:W.blue,paddingLeft:17,paddingTop:2},badge:{alignSelf:"flex-start",paddingHorizontal:10,paddingVertical:3,borderRadius:999},badge_text:{fontSize:12,fontWeight:"700"},item:{flexDirection:"row",gap:10,paddingLeft:2},item_text:{flex:1,fontSize:15,lineHeight:21,color:W.title},md_bold:{fontWeight:"700"},md_code:{fontFamily:et.Platform.select({ios:"Menlo",default:"monospace"}),fontSize:13,backgroundColor:"#F2F2F7",color:"#3A3A3C"},md_link:{color:W.blue,textDecorationLine:"underline"},full:{width:"100%"},btn_primary:{marginTop:14,backgroundColor:W.blue,paddingVertical:14,borderRadius:12,alignItems:"center"},btn_primary_text:{color:"white",fontWeight:"600",fontSize:16},btn_secondary:{paddingTop:12,alignItems:"center"},link:{color:W.blue,fontSize:15,fontWeight:"600"},history:{flex:1,backgroundColor:W.background},float_header:{position:"absolute",top:0,left:0,right:0},header_row:{flexDirection:"row",alignItems:"center",paddingHorizontal:16,paddingTop:2,paddingBottom:8},header_title:{position:"absolute",top:2,bottom:8,alignItems:"center",justifyContent:"center"},history_title:{fontSize:15,fontWeight:"500",color:"#1C1C1E"},history_sub:{fontSize:11,color:"#71717A",marginTop:1},back_btn:{alignItems:"center",justifyContent:"center"},back_btn_fallback:{backgroundColor:W.surface,...et.Platform.select({ios:{shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8},default:{borderWidth:et.StyleSheet.hairlineWidth*2,borderColor:"rgba(0, 0, 0, 0.08)"}})},icon_layer:{position:"absolute",top:0,left:0,right:0,bottom:0,alignItems:"center",justifyContent:"center"},fade:{position:"absolute",top:0,left:0,right:0},chevron:{width:11,height:11,borderLeftWidth:2.2,borderBottomWidth:2.2,borderColor:Ue.text,transform:[{rotate:"45deg"}],marginLeft:4},pressed:{opacity:.6,transform:[{scale:.94}]},history_list:{padding:16,gap:12},card:{backgroundColor:W.surface,borderRadius:16,padding:16,gap:12},card_head:{flexDirection:"row",justifyContent:"space-between",alignItems:"baseline"},version:{fontSize:16,fontWeight:"700",color:W.title},date:{fontSize:13,color:W.sub_title},loading:{marginTop:40},center:{alignItems:"center",marginTop:40,gap:12},empty:{marginTop:40}});var fe=require("react/jsx-runtime"),zn=({text:e,style:t})=>{let n=Pe();return(0,fe.jsx)(de.Text,{style:t,children:Jt(e.replace(/^(?:[-*•]\s+)+/,"")).map((o,r)=>{switch(o.type){case"bold":return(0,fe.jsx)(de.Text,{style:y.md_bold,children:o.text},r);case"code":return(0,fe.jsx)(de.Text,{style:[y.md_code,{backgroundColor:n.background,color:n.text}],children:o.text},r);case"link":return(0,fe.jsx)(de.Text,{style:[y.md_link,{color:n.primary}],accessibilityRole:"link",onPress:()=>{de.Linking.openURL(o.url).catch(()=>{})},children:o.text},r);default:return o.text}})})},pt=({changelog:e,max_items:t,onMore:n})=>{let o=Pe();return(0,fe.jsx)(de.View,{style:y.groups,children:o.kinds.filter(r=>e[r.key].length).map(r=>{let i=e[r.key],l=t?i.slice(0,t):i,s=i.length-l.length;return(0,fe.jsxs)(de.View,{style:y.group,children:[(0,fe.jsxs)(de.View,{style:y.group_head,children:[(0,fe.jsx)(de.View,{style:[y.badge,{backgroundColor:r.bg}],children:(0,fe.jsx)(de.Text,{style:[y.badge_text,{color:r.color}],children:r.label})}),(0,fe.jsx)(de.Text,{style:[y.group_count,{color:o.hint}],children:i.length})]}),l.map((c,a)=>(0,fe.jsxs)(de.View,{style:y.item,children:[(0,fe.jsx)(de.View,{style:[y.dot,{backgroundColor:r.color}]}),(0,fe.jsx)(zn,{text:c,style:[y.item_text,{color:o.text}]})]},a)),s>0&&(0,fe.jsx)(de.Text,{style:[y.more,{color:o.primary}],onPress:n,suppressHighlighting:!0,children:Hn(o.labels.changelog_more,{count:s})})]},r.key)})})};var Ct=require("react"),N=require("react-native");var z=require("react/jsx-runtime"),$n,Ys=()=>($n!=null||($n=Promise.all([N.Platform.OS==="ios"?import("expo-image").then(e=>e.Image).catch(()=>{}):Promise.resolve(void 0),import("expo-linear-gradient").then(e=>e.LinearGradient).catch(()=>{})]).then(([e,t])=>({ExpoImage:e,LinearGradient:t}))),$n),Xs=()=>{let[e,t]=(0,Ct.useState)({});return(0,Ct.useEffect)(()=>{let n=!0;return Ys().then(o=>{n&&t(o)}),()=>{n=!1}},[]),e},Qs="#1C1C1E",Zs=e=>/^#[0-9a-f]{6}$/i.test(e),ea=()=>{let[e,t]=(0,Ct.useState)();return(0,Ct.useEffect)(()=>{let n=!0;return Bt().then(o=>{n&&o&&t(()=>o)}),()=>{n=!1}},[]),e},ta=({onPress:e,size:t,GlassView:n,ExpoImage:o})=>{let r=Pe(),i=r.dark?"#FFFFFF":Qs;return(0,z.jsxs)(N.Pressable,{onPress:e,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"Quay l\u1EA1i",style:({pressed:l})=>[y.back_btn,{width:t,height:t,borderRadius:t/2},!n&&y.back_btn_fallback,!n&&r.dark&&{backgroundColor:"#3F3F46",shadowOpacity:0},!n&&l&&y.pressed],children:[n&&(0,z.jsx)(n,{style:[N.StyleSheet.absoluteFill,{borderRadius:t/2}],glassEffectStyle:"regular",colorScheme:r.dark?"dark":"light",isInteractive:!0}),(0,z.jsx)(N.View,{pointerEvents:"none",style:y.icon_layer,children:o?(0,z.jsx)(o,{source:"sf:chevron.left",transition:0,contentFit:"contain",style:{width:20,height:20,fontSize:20,color:i}}):(0,z.jsx)(N.View,{style:[y.chevron,{borderColor:i}]})})]})},Et=({app_id:e,name:t,onBack:n,renderHeader:o})=>{let r=Pe(),i=Mt(),l=ea(),{ExpoImage:s,LinearGradient:c}=Xs(),a=l?46:42,p=o?0:i.top+a+10,{versions:d,loading:m,error:u,reload:S}=Sn(e);return(0,z.jsxs)(N.View,{style:[y.history,{backgroundColor:r.background}],children:[o&&(0,z.jsx)(N.View,{style:{paddingTop:i.top},children:o({title:r.labels.history_title,subtitle:t,onBack:n})}),m&&!d.length?(0,z.jsx)(N.ActivityIndicator,{style:[y.loading,{marginTop:p+40}],color:r.primary}):u&&!d.length?(0,z.jsxs)(N.View,{style:[y.center,{marginTop:p+40}],children:[(0,z.jsx)(N.Text,{style:[y.sub_title,{color:r.text_secondary}],children:r.labels.history_error}),(0,z.jsx)(N.TouchableOpacity,{onPress:S,children:(0,z.jsx)(N.Text,{style:[y.link,{color:r.primary}],children:r.labels.retry})})]}):(0,z.jsxs)(N.ScrollView,{contentContainerStyle:[y.history_list,{paddingTop:p+8,paddingBottom:i.bottom+24}],scrollIndicatorInsets:{top:p},children:[d.map(v=>(0,z.jsxs)(N.View,{style:[y.card,{backgroundColor:r.surface,borderRadius:Math.max(r.radius-12,0)}],children:[(0,z.jsxs)(N.View,{style:y.card_head,children:[(0,z.jsxs)(N.Text,{style:[y.version,{color:r.text}],children:["v",v.version]}),(0,z.jsx)(N.Text,{style:[y.date,{color:r.text_secondary}],children:Pi(v.created_at,r.labels.date_locale)})]}),(0,z.jsx)(pt,{changelog:v.changelog})]},v.version)),!d.length&&(0,z.jsx)(N.Text,{style:[y.sub_title,y.empty,{color:r.text_secondary}],children:r.labels.history_empty})]}),!o&&(0,z.jsxs)(N.View,{pointerEvents:"box-none",style:[y.float_header,{paddingTop:i.top}],children:[c&&Zs(r.background)?(0,z.jsx)(c,{pointerEvents:"none",colors:[`${r.background}F5`,`${r.background}E6`,`${r.background}B3`,`${r.background}00`],locations:[0,.45,.75,1],style:[y.fade,{height:p+28}]}):(0,z.jsx)(N.View,{pointerEvents:"none",style:y.fade,children:na.map((v,D)=>(0,z.jsx)(N.View,{style:{height:D===0?p:4,backgroundColor:r.background,opacity:v}},D))}),(0,z.jsxs)(N.View,{style:y.header_row,children:[(0,z.jsx)(ta,{onPress:n,size:a,GlassView:l,ExpoImage:s}),(0,z.jsxs)(N.View,{pointerEvents:"none",style:[y.header_title,{left:a+24,right:a+24}],children:[(0,z.jsx)(N.Text,{style:[y.history_title,{color:r.text}],numberOfLines:1,children:r.labels.history_title}),(0,z.jsx)(N.Text,{style:[y.history_sub,{color:r.text_secondary}],numberOfLines:1,children:t})]})]})]})]})},na=[.96,.9,.8,.68,.55,.42,.3,.18,.08];var O=require("react/jsx-runtime"),Oi=e=>({backgroundColor:e.primary,borderRadius:e.button_radius,height:e.button_height,paddingVertical:0,justifyContent:"center"}),oa=4,Xt=({request:e,changelog:t,onClose:n,renderHistoryHeader:o,renderActions:r})=>{var m;let i=Pe(),[l,s]=(0,$e.useState)(!1),[c,a]=(0,$e.useState)(0),[p,d]=(0,$e.useState)(0);return(0,O.jsx)(E.Modal,{visible:!0,transparent:!l,animationType:l?"slide":"fade",statusBarTranslucent:!0,onRequestClose:l?()=>s(!1):n,children:l?(0,O.jsx)(Et,{app_id:e.app_id,name:e.name,onBack:()=>s(!1),renderHeader:o}):(0,O.jsxs)(E.View,{style:[y.overlay,{backgroundColor:i.overlay}],children:[(0,O.jsx)(E.Pressable,{style:E.StyleSheet.absoluteFill,onPress:n,accessibilityLabel:"\u0110\xF3ng"}),(0,O.jsxs)(E.View,{style:[y.sheet,{backgroundColor:i.surface,borderRadius:i.radius}],children:[(0,O.jsxs)(E.View,{style:y.sheet_head,children:[(0,O.jsx)(E.Text,{style:[y.title,{color:i.text}],children:i.labels.changelog_title}),(0,O.jsx)(E.Text,{style:[y.sheet_name,{color:i.text_secondary}],numberOfLines:1,children:e.name}),(0,O.jsxs)(E.View,{style:[y.version_pill,{backgroundColor:i.background}],children:[(0,O.jsx)(E.Text,{style:[y.version_old,{color:i.text_secondary}],children:`v${e.from}`}),(0,O.jsx)(E.Text,{style:[y.version_arrow,{color:i.hint}],children:"\u2192"}),(0,O.jsx)(E.Text,{style:[y.version_new,{color:i.primary}],children:`v${e.to}`})]})]}),(0,O.jsx)(E.ScrollView,{style:y.scroll,contentContainerStyle:y.scroll_content,onContentSizeChange:(u,S)=>a(S),onLayout:u=>d(u.nativeEvent.layout.height),children:(0,O.jsx)(pt,{changelog:t,max_items:oa,onMore:()=>s(!0)})}),(0,O.jsx)(E.View,{style:[y.sheet_foot,c>p+1&&[y.sheet_foot_divider,{borderTopColor:i.divider}]],children:r?r({onClose:n,onViewAll:()=>s(!0),labels:i.labels}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.TouchableOpacity,{style:[y.btn_primary,Oi(i)],activeOpacity:.8,onPress:n,children:(0,O.jsx)(E.Text,{style:[y.btn_primary_text,{color:i.on_primary}],children:i.labels.changelog_ok})}),(0,O.jsx)(E.TouchableOpacity,{style:y.btn_secondary,onPress:()=>s(!0),children:(0,O.jsx)(E.Text,{style:[y.link,{color:(m=i.secondary)!=null?m:i.primary}],children:i.labels.changelog_view_all})})]})})]})]})})},Qt=({update:e,is_updating:t,progress:n,has_failed:o,onUpdate:r,logo:i,renderAction:l})=>{let s=Pe(),c=(0,$e.useRef)(new E.Animated.Value(0)).current,a=(0,$e.useRef)(new E.Animated.Value(30)).current;return(0,$e.useEffect)(()=>{E.Animated.parallel([E.Animated.timing(c,{toValue:1,duration:400,useNativeDriver:!0}),E.Animated.spring(a,{toValue:0,friction:8,tension:40,useNativeDriver:!0})]).start()},[c,a]),(0,O.jsx)(E.Modal,{visible:!0,transparent:!0,animationType:"none",statusBarTranslucent:!0,onRequestClose:()=>{},children:(0,O.jsx)(E.View,{style:[y.overlay,{backgroundColor:s.overlay}],children:(0,O.jsxs)(E.Animated.View,{style:[y.container,{backgroundColor:s.surface,borderRadius:s.radius},{opacity:c,transform:[{translateY:a}]}],children:[i&&(0,O.jsx)(E.Image,{source:i,style:y.logo}),(0,O.jsx)(E.Text,{style:[y.title,{color:s.text}],children:t?s.labels.updating_title:s.labels.update_title}),!t&&(0,O.jsx)(E.Text,{style:[y.sub_title,y.gap,{color:s.text_secondary}],children:Hn(s.labels.update_message,{next:e.next_version,current:e.current_version})}),!t&&o&&(0,O.jsx)(E.Text,{style:y.error_text,children:s.labels.update_failed}),t?(0,O.jsxs)(E.View,{style:y.progress_section,children:[(0,O.jsxs)(E.Text,{style:[y.progress_text,{color:s.primary}],children:[n,"%"]}),(0,O.jsx)(E.View,{style:[y.progress_track,{backgroundColor:s.background}],children:(0,O.jsx)(E.View,{style:[y.progress_fill,{backgroundColor:s.primary,width:`${n}%`}]})}),(0,O.jsx)(E.Text,{style:[y.loading_hint,{color:s.hint}],children:s.labels.updating_hint})]}):l?(0,O.jsx)(E.View,{style:y.full,children:l({onUpdate:r,has_failed:o,label:o?s.labels.retry:s.labels.update_now})}):(0,O.jsx)(E.TouchableOpacity,{style:[y.btn_primary,y.full,Oi(s)],activeOpacity:.8,onPress:r,children:(0,O.jsx)(E.Text,{style:[y.btn_primary_text,{color:s.on_primary}],children:o?s.labels.retry:s.labels.update_now})})]})})})},Zt=({app_id:e,name:t,onClose:n,renderHistoryHeader:o})=>(0,O.jsx)(E.Modal,{visible:!0,animationType:"slide",statusBarTranslucent:!0,onRequestClose:n,children:(0,O.jsx)(Et,{app_id:e,name:t,onBack:n,renderHeader:o})});var ut=require("react/jsx-runtime"),ra=({app_ids:e,shouldShowUpdate:t,logo:n,renderUpdate:o,renderChangelog:r,theme:i,renderHistoryHeader:l,labels:s,renderChangelogActions:c,renderUpdateAction:a})=>{var Q,me;let p=J(B,Y=>Y.updates),m=((Q=e!=null?e:U().manual_update)!=null?Q:[]).map(Y=>p[Y]).find(Y=>!!Y&&(!t||t(Y))),u=yt(m==null?void 0:m.app_id),[S,v]=(0,dt.useState)(!1),[D,C]=(0,dt.useState)(!1),x=(0,dt.useRef)(!1),j=vn(),A=En(),G=async()=>{if(!m||x.current)return;x.current=!0,v(!0),C(!1);let Y=await _n(m.app_id);x.current=!1,v(!1),C(!Y)};if(m){let Y=(u==null?void 0:u.status)==="updating"?Math.round(((me=u.progress)!=null?me:0)*100):0,h={update:m,is_updating:S,progress:Y,has_failed:D,onUpdate:G};return(0,ut.jsx)(ct,{theme:i,labels:s,children:o?o(h):(0,ut.jsx)(Qt,{...h,logo:n,renderAction:a})})}if(j){let Y={request:j,changelog:Yt(j.versions),onClose:Mn};return(0,ut.jsx)(ct,{theme:i,labels:s,children:r?r(Y):(0,ut.jsx)(Xt,{...Y,renderHistoryHeader:l,renderActions:c})})}return A?(0,ut.jsx)(ct,{theme:i,labels:s,children:(0,ut.jsx)(Zt,{...A,onClose:Cn,renderHistoryHeader:l})}):null},Ii=dt.default.memo(ra);0&&(module.exports={AGENT_BRIDGE_VERSION,AGENT_MESSAGE_EVENT,AGENT_PAYLOAD_META_EVENT,AGENT_PAYLOAD_META_RESULT_EVENT,AGENT_STOPPED_EVENT,CodeType,DEFAULT_MINIAPP_UPDATES_LABELS,DefaultMiniAppChangelogHistoryModal,DefaultMiniAppChangelogPrompt,DefaultMiniAppSplash,DefaultMiniAppUpdatePrompt,MINIAPP_CHANGELOG_KINDS,MINIAPP_PLATFORM_URL,MiniAppChangelogGroups,MiniAppChangelogHistory,MiniAppChangelogText,MiniAppHost,MiniAppHostError,MiniAppUpdates,MiniAppUpdatesThemeProvider,ScannerEndReason,ScannerEvent,ScannerLayout,ScannerMethod,ToastType,closeMiniApp,closeMiniAppChangelogHistory,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,dismissMiniAppChangelog,ensureMiniApp,fetchMiniAppChangelog,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppChangelogSeen,getMiniAppIdByAgentId,getMiniAppStatuses,getMiniAppUpdate,getPendingChangelog,installBundledMiniApp,markMiniAppChangelogSeen,mergeMiniAppChangelog,onMiniAppEvent,openMiniApp,parseInlineMarkdown,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,resolveMiniAppUpdatesTheme,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,showMiniAppChangelog,showMiniAppChangelogHistory,stripInlineMarkdown,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppChangelog,useMiniAppChangelogHistoryRequest,useMiniAppChangelogRequest,useMiniAppDownload,useMiniAppDownloadsPaused,useMiniAppUpdatesTheme});
88
+ })(); true;`,Cs=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),On=(e,t)=>{if(typeof e!="string"||!e)throw new f("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},li=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:l,app_id:s,instance_id:c,options:a,emit:p,isActive:d,playBeep:m})=>{var C,x,j,A,G,Q,me,Y;let u=a==null?void 0:a.handlers,S={app_id:s,instance_id:c,close:l},v=()=>{var h;(h=a==null?void 0:a.haptic)==null||h.call(a,"impactLight"),m==null||m()},D=()=>new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Uo(t);return Ht(e,()=>Vo(h,d))}case"speech.start":{if(!p)throw D();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new f("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let w of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[w])!==void 0){if(typeof t[w]!="boolean")throw new f("INVALID_PARAMS",`${w} ph\u1EA3i l\xE0 boolean`);h[w]=t[w]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new f("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let L=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",R=L==="voice"?(C=a==null?void 0:a.voice)!=null?C:a==null?void 0:a.speech:void 0;if(Or(c,R),R){kr(c,R);try{return await R.start({owner:c,app_id:s,mode:L,options:h,emit:p,isActive:d!=null?d:(()=>!0)})}catch(w){throw Rr(c,R),w}}return Lr(c,h,p,d)}case"speech.stop":{let h=Ir(c);return h?h.stop(c):Dr(c)}case St.scan:return zr(c,uo(t),d,v);case St.start:{if(!p)throw D();return $r(c,uo(t),p,d,v)}case St.stop:return Wr(c);case"uploadFiles":{let{task_id:h,...L}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new f("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return nr(Go(L),{instance_id:c,app_id:s,getContext:r,task_id:h,config:a==null?void 0:a.upload,emit:p,exclusivePick:R=>Ht("uploadFiles.pick",R)})}case"uploadFiles.cancel":tr(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Zo(a==null?void 0:a.upload);case"getBiometricAvailability":return((x=a==null?void 0:a.biometrics)!=null?x:await Gn()).getAvailability();case"authenticateBiometric":{let h=On(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new f("INVALID_PARAMS","reason must contain 1\u2013200 characters");let L=t==null?void 0:t.cancelButtonText;if(L!==void 0&&(typeof L!="string"||!L.trim()||L.length>80))throw new f("INVALID_PARAMS","Invalid cancelButtonText");return Ht(e,async()=>{var w;return((w=a==null?void 0:a.biometrics)!=null?w:await Gn()).authenticate({reason:h,cancelButtonText:L})})}case"requestPayment":{let h=u==null?void 0:u.requestPayment;if(!h)throw D();let L=t==null?void 0:t.amount;if(typeof L!="number"||!Number.isFinite(L)||L<=0)throw new f("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let R={...t,amount:L,currency:On(t==null?void 0:t.currency,"currency")};return Ht(e,()=>h(R,S))}case"printImage":{let h=u==null?void 0:u.printImage;if(!h)throw D();let L=On(t==null?void 0:t.image,"image");await Ht(e,()=>h({image:L},S));return}case"openScreen":if(!(u!=null&&u.openScreen))throw D();await u.openScreen({screen:On(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},S);return;case"closeApp":l();return;case"openWebview":{let h=String((j=t==null?void 0:t.url)!=null?j:"");if(!/^https?:\/\//i.test(h))throw new f("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(a!=null&&a.openUrl?a.openUrl(h):qt.Linking.openURL(h));return}case"openLink":{let h=String((A=t==null?void 0:t.url)!=null?A:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new f("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(a!=null&&a.openUrl?a.openUrl(h):qt.Linking.openURL(h))}catch(L){throw new f("NOT_SUPPORTED",String((Q=(G=L==null?void 0:L.message)!=null?G:L)!=null?Q:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=rr(t);if(!h||(d==null?void 0:d())===!1)return;a!=null&&a.showToast?a.showToast(h.message,{type:h.type}):ir(h.message,h.type);return}case"changelog.openPopup":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;return(d==null?void 0:d())===!1?{shown:!1}:{shown:await bt(h,{force:(t==null?void 0:t.force)===!0})}}case"changelog.openHistory":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;(d==null?void 0:d())!==!1&&xn(h);return}case"haptic":{let h=Cs.has(t==null?void 0:t.type)?t.type:"selection";(me=a==null?void 0:a.haptic)==null||me.call(a,h);return}case"getSystemInfo":return{platform:qt.Platform.OS==="ios"?"ios":"android",appVersion:(Y=a==null?void 0:a.app_version)!=null?Y:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let w=n().access_token;if(!w)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}if(h!=="partner"&&h!=="chatbox")throw new f("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let L=ii[h];if(!o().includes(L))throw new f("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${L} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let R=h==="partner"?n().partner_token:n().chatbox_token;if(!R)throw new f("HOST_ERROR",`Kh\xF4ng c\xF3 ${L}`);return R}case"getUserInfo":{let h=n().user;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new f("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var In=new Map,ci=(e,t)=>(In.set(e,t),()=>{In.get(e)===t&&In.delete(e)}),Fn=(e,t)=>{let n=In.get(e);return n?n(t):!1};var wo=1,Es="retion.ai.agent",Ao="retion.ai.message",So="retion.ai.stopped",Mo="retion.ai.payload_meta",vo="retion.ai.payload_meta_result",Ln=new Map,di=null,Ts="[miniapp:agent]",Wt=(...e)=>{globalThis.__DEV__&&console.log(Ts,...e)},pi=e=>{try{let t=JSON.stringify(e);return t&&t.length>300?`${t.slice(0,300)}\u2026`:t}catch{return String(e)}},bo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ps=e=>{try{let t=JSON.parse(e);return bo(t)?t:null}catch{return null}},gi=(e,t)=>Fn(e,JSON.stringify({v:wo,...t})),ui=(e,t)=>{let n=e?Ln.get(e):void 0;if(!n)return Wt(`${String(t.type)}: ch\u01B0a mini app n\xE0o b\xE1o agent ${e||"(tr\u1ED1ng)"} \u2192 kh\xF4ng g\u1EEDi`),0;let o=0;return n.instances.forEach(r=>{gi(r,{app_id:n.app_id,agent_id:e,...t})&&(o+=1)}),Wt(`${String(t.type)} \u2192 ${o} WebView`,`app_id=${n.app_id}`,`agent_id=${e}`),o},hi=(e,t,n)=>{let o=Ps(e);if(!o)return!1;if(o.type===Es){let a=typeof o.agent_id=="string"?o.agent_id:"",p=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id;if(a){let d=Ln.get(a);d&&d.app_id===p?d.instances.add(t.instance_id):(Wt("ghi nh\u1EADn agent",a,"\u2192 app",p,"WebView",t.instance_id),Ln.set(a,{app_id:p,instances:new Set([t.instance_id])})),di=a}return!1}if(o.type!==Mo)return!1;let r=typeof o.request_id=="string"?o.request_id:"",i=a=>{Wt("payload_meta_result \u2192",t.instance_id,r,pi(a)),r&&gi(t.instance_id,{type:vo,request_id:r,...a})};if(!n)return i({ok:!1,error:"unsupported"}),!0;if(!bo(o.payload_meta))return i({ok:!1,error:"invalid"}),!0;Wt("payload_meta \u2190",t.instance_id,r,pi(o.payload_meta));let l=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id,s=typeof o.agent_id=="string"&&o.agent_id?o.agent_id:void 0,c=typeof o.text=="string"?o.text:"";return Promise.resolve().then(()=>n.sendPayloadMeta({app_id:l,agent_id:s,text:c,payload_meta:o.payload_meta})).then(a=>i({...bo(a)?a:null,ok:!!(a!=null&&a.ok)})).catch(a=>{console.warn("[miniapp] agent sendPayloadMeta l\u1ED7i",a),i({ok:!1,error:"send_failed"})}),!0},fi=e=>e.subscribe({message:({agent_id:t,fb_client_id:n,raw:o})=>{ui(t!=null?t:"",{type:Ao,fb_client_id:n,raw:o})},stopped:({agent_id:t,source:n})=>{ui(t||di||"",{type:So,source:n})}}),mi=e=>{var t,n;return(n=(t=Ln.get(e))==null?void 0:t.app_id)!=null?n:null};var K=require("react"),_=require("react-native");var P=require("react/jsx-runtime"),jt="#22C55E",ks="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",Rs=2,Nn=18,Os=1600,Gt=14,Is=2e3,bi=.38,Fs=40,yi=2,Ls=8,Ds=2e3,Ns=250,vt=2e3,Us=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:Gt},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:Gt},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:Gt},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:Gt}],_i=({color:e})=>(0,P.jsx)(P.Fragment,{children:Us.map((t,n)=>(0,P.jsx)(_.View,{style:[T.corner,t,{borderColor:e}]},n))}),Dn=({style:e,children:t,...n})=>{let o=(0,K.useRef)(new _.Animated.Value(1)).current,r=i=>_.Animated.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return(0,P.jsx)(_.Pressable,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:(0,P.jsx)(_.Animated.View,{style:[e,{transform:[{scale:o}]}],children:t})})},Co=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var on,rn;let{vision:r,types:i,mode:l,layout:s,hint:c,glass_view:a,absolute:p}=e,d=s===Se.top,m=(0,K.useRef)(new _.Animated.Value(0)).current,u=r.useCameraDevice("back"),S=(0,K.useRef)(new _.Animated.Value(1)).current,[v,D]=(0,K.useState)(!1),[C,x]=(0,K.useState)(1),j=(0,K.useRef)(null),[A,G]=(0,K.useState)(()=>{let{width:k,height:ie}=_.Dimensions.get("window");return{width:k,height:d?ie*bi:ie,window_y:0}}),Q=J(ae,k=>k.last_value),me=J(ae,k=>k.hit_tick),Y=J(ae,k=>k.scan_count),h=J(ae,k=>k.notice),L=J(ae,k=>k.is_picking),R=(0,K.useRef)(null),w=Mt(),_e=w.top,te=(0,K.useRef)(new _.Animated.Value(0)).current,H=(0,K.useRef)(new _.Animated.Value(0)).current,ge=(0,K.useRef)(new _.Animated.Value(0)).current,Ie=(0,K.useRef)(n);Ie.current=n,(0,K.useEffect)(()=>{if(!t)return;m.setValue(A.height);let k=_.Animated.timing(m,{toValue:0,duration:Ns,easing:_.Easing.out(_.Easing.cubic),useNativeDriver:!1});return k.start(({finished:ie})=>{var g;ie&&((g=Ie.current)==null||g.call(Ie))}),()=>k.stop()},[t,m]);let We=Math.round(A.width*(d?.8:.78)),re=Math.round(d?A.height*.46:We*.78),Fe=Math.round((A.height-re)/2),ne=Math.round((A.width-We)/2),be=r.useCodeScanner({codeTypes:i,onCodeScanned:(0,K.useCallback)(k=>fo(k),[])});(0,K.useEffect)(()=>{let k=_.BackHandler.addEventListener("hardwareBackPress",()=>(ho(),!0));return()=>k.remove()},[]);let tt=(0,K.useRef)(me);(0,K.useEffect)(()=>{if(me===tt.current)return;te.setValue(1),ge.setValue(1);let k=_.Animated.parallel([_.Animated.timing(te,{toValue:0,duration:450,useNativeDriver:!0}),_.Animated.sequence([_.Animated.delay(Is),_.Animated.timing(ge,{toValue:0,duration:250,useNativeDriver:!0})])]);return k.start(),()=>k.stop()},[me,te,ge]),(0,K.useEffect)(()=>{let k=g=>_.Animated.timing(H,{toValue:g,duration:Os,easing:_.Easing.inOut(_.Easing.quad),useNativeDriver:!0}),ie=_.Animated.loop(_.Animated.sequence([k(1),k(0)]));return ie.start(),()=>ie.stop()},[H]);let Tt=(0,K.useCallback)(()=>{_.Animated.timing(S,{toValue:0,duration:220,useNativeDriver:!0}).start()},[S]);(0,K.useEffect)(()=>{let k=setTimeout(Tt,Ds);return()=>clearTimeout(k)},[Tt]);let[en,tn]=(0,K.useState)(!1);(0,K.useEffect)(()=>{let k=requestAnimationFrame(()=>{k=requestAnimationFrame(()=>tn(!0))});return()=>cancelAnimationFrame(k)},[]);let je=!!(u!=null&&u.hasTorch),Ge=(on=u==null?void 0:u.neutralZoom)!=null?on:1,nt=u?Math.min(u.maxZoom/Ge,Ls):1,$n=Ge*Math.min(C,nt),gt=k=>{var b;let{touches:ie}=k.nativeEvent;if(ie.length!==2){j.current=null;return}let g=Math.hypot(ie[0].pageX-ie[1].pageX,ie[0].pageY-ie[1].pageY);(b=j.current)!=null||(j.current={distance:g,level:C}),x(Math.max(1,Math.min(nt,j.current.level*(g/j.current.distance))))},nn=(0,P.jsx)(_.Text,{style:[T.hint,!!h&&T.hint_notice],numberOfLines:1,children:(rn=h!=null?h:c)!=null?rn:ks});return(0,P.jsx)(_.Animated.View,{ref:R,onTouchMove:gt,onTouchEnd:()=>{j.current=null},pointerEvents:t?"none":"auto",style:d?[T.top,p&&T.top_absolute,t&&{height:m}]:T.full,onLayout:({nativeEvent:{layout:k}})=>{var ie;t||(o==null||o(k.height),(ie=R.current)==null||ie.measureInWindow((g,b)=>{G({width:k.width,height:k.height,window_y:b||0})}))},children:(0,P.jsxs)(_.View,{style:t?[T.content_closing,{height:A.height}]:T.content,children:[u&&en&&(0,P.jsx)(r.Camera,{style:_.StyleSheet.absoluteFill,device:u,isActive:!L,codeScanner:be,torch:v&&je?"on":"off",zoom:$n,onPreviewStarted:Tt,onError:k=>jr(k.message)}),(0,P.jsx)(_.Animated.View,{style:[T.preview_cover,{opacity:S}],pointerEvents:"none"}),A.height>0&&(0,P.jsxs)(_.View,{style:T.overlay,pointerEvents:"none",children:[(0,P.jsx)(_.View,{style:[T.dim_ring,{top:Fe-vt,left:ne-vt,width:We+vt*2,height:re+vt*2}]}),(0,P.jsxs)(_.View,{style:{position:"absolute",top:Fe,left:ne,width:We,height:re},children:[(0,P.jsx)(_i,{color:"#FFFFFF"}),(0,P.jsx)(_.Animated.View,{style:[_.StyleSheet.absoluteFill,{opacity:te}],children:(0,P.jsx)(_i,{color:jt})}),(0,P.jsxs)(_.Animated.View,{style:[T.scan_line_wrap,{transform:[{translateY:H.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,re-Nn)]})}]}],children:[(0,P.jsx)(_.View,{style:T.scan_glow_outer}),(0,P.jsx)(_.View,{style:T.scan_glow_inner}),(0,P.jsx)(_.View,{style:T.scan_line})]})]}),(0,P.jsx)(_.View,{style:[T.hint_slot,d?{top:0,height:Fe-6,justifyContent:"flex-end"}:{top:Fe+re+20}],children:nn}),l===Qe.continuous&&!!Q&&(0,P.jsx)(_.Animated.View,{style:[T.result_slot,{top:d?Fe+re-Fs:Fe+re+52},{opacity:ge}],children:(0,P.jsxs)(_.View,{style:T.result,children:[(0,P.jsx)(_.View,{style:T.check_badge,children:(0,P.jsx)(_.View,{style:T.check_mark})}),(0,P.jsx)(_.Text,{style:T.result_text,numberOfLines:1,children:Q}),(0,P.jsxs)(_.Text,{style:T.result_count,children:["\xB7 ",Y," m\xE3"]})]})})]}),A.height>0&&(0,P.jsx)(_.View,{style:[T.close_slot,d?T.close_slot_top:{top:Math.max(12,_e-A.window_y+12)}],children:(0,P.jsxs)(Dn,{style:[T.close_button,!!a&&T.glass_surface],onPress:ho,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&(0,P.jsx)(a,{style:T.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,P.jsx)(_.View,{style:[T.close_bar,T.close_bar_a]}),(0,P.jsx)(_.View,{style:[T.close_bar,T.close_bar_b]})]})}),(0,P.jsx)(_.View,{style:[T.toolbar_wrap,!d&&{bottom:w.bottom+20}],pointerEvents:"box-none",children:(0,P.jsxs)(_.View,{style:[T.toolbar,!!a&&T.glass_surface],children:[a&&(0,P.jsx)(a,{style:T.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,P.jsx)(Dn,{style:T.tool,onPress:Gr,disabled:L,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:(0,P.jsxs)(_.View,{style:T.image_icon,children:[(0,P.jsx)(_.View,{style:T.image_icon_dot}),(0,P.jsx)(_.View,{style:T.image_icon_hill})]})}),!!u&&nt>=yi&&(0,P.jsx)(Dn,{style:[T.tool,C>1&&T.tool_on],onPress:()=>x(k=>k>1?1:yi),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:(0,P.jsxs)(_.Text,{style:[T.zoom_text,C>1&&T.zoom_text_on],children:[Math.round(C*10)/10,"x"]})}),je&&(0,P.jsx)(Dn,{style:[T.tool,v&&T.tool_on],onPress:()=>D(k=>!k),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:v},children:(0,P.jsx)(_.Text,{style:[T.torch_icon,v&&T.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},Vs="rgba(0,0,0,0.5)",xo=50,T=_.StyleSheet.create({top:{height:`${bi*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:vt,borderColor:Vs,borderRadius:vt+Gt},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:Nn,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Nn,borderRadius:Nn/2,backgroundColor:jt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:jt,opacity:.2},scan_line:{height:Rs,borderRadius:1,backgroundColor:jt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:xo,height:xo,borderRadius:xo/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:jt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});var Ee=require("react"),I=require("react-native");var ee=require("react/jsx-runtime"),Eo={[ve.info]:"#3B82F6",[ve.success]:"#22C55E",[ve.error]:"#EF4444"},wi=-120,Un=I.Platform.OS==="android",Ai=({type:e})=>e===ve.success?(0,ee.jsx)(I.View,{style:ue.check_mark}):e===ve.error?(0,ee.jsxs)(ee.Fragment,{children:[(0,ee.jsx)(I.View,{style:[ue.cross_bar,ue.cross_a]}),(0,ee.jsx)(I.View,{style:[ue.cross_bar,ue.cross_b]})]}):(0,ee.jsxs)(ee.Fragment,{children:[(0,ee.jsx)(I.View,{style:ue.info_dot}),(0,ee.jsx)(I.View,{style:ue.info_bar})]}),Si=()=>{let e=J(It,m=>m.message),t=J(It,m=>m.type),n=J(It,m=>m.tick),o=(0,Ee.useRef)(new I.Animated.Value(wi)).current,r=(0,Ee.useRef)(new I.Animated.Value(0)).current,i=(0,Ee.useRef)(new I.Animated.Value(.92)).current,l=(0,Ee.useRef)(new I.Animated.Value(0)).current,[s,c]=(0,Ee.useState)(),[a,p]=(0,Ee.useState)(!1);(0,Ee.useEffect)(()=>{let m=!0;return Bt().then(u=>{m&&u&&c(()=>u)}),()=>{m=!1}},[]);let d=(0,Ee.useRef)(n);return(0,Ee.useEffect)(()=>{if(n===d.current)return;I.AccessibilityInfo.announceForAccessibility(e),p(!0),l.setValue(0),i.setValue(.92);let m=I.Animated.sequence([I.Animated.parallel([I.Animated.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),I.Animated.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),I.Animated.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),I.Animated.sequence([I.Animated.delay(90),I.Animated.spring(l,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),I.Animated.delay(or[t]),I.Animated.parallel([I.Animated.timing(o,{toValue:wi,duration:240,useNativeDriver:!0}),I.Animated.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return m.start(({finished:u})=>{u&&p(!1)}),()=>m.stop()},[n]),a?(0,ee.jsx)(I.View,{style:[ue.layer,{top:Mt().top+(Un?12:8)}],pointerEvents:"none",children:(0,ee.jsxs)(I.Animated.View,{style:[ue.toast,Un&&ue.toast_android,!!s&&ue.toast_glass,{opacity:s?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[s&&(0,ee.jsx)(s,{style:ue.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),Un?(0,ee.jsx)(I.Animated.View,{style:[ue.badge_halo,{backgroundColor:`${Eo[t]}33`,transform:[{scale:l}]}],children:(0,ee.jsx)(I.View,{style:[ue.badge,{backgroundColor:Eo[t]}],children:(0,ee.jsx)(Ai,{type:t})})}):(0,ee.jsx)(I.Animated.View,{style:[ue.badge,{backgroundColor:Eo[t],transform:[{scale:l}]}],children:(0,ee.jsx)(Ai,{type:t})}),(0,ee.jsx)(I.Text,{style:[ue.message,Un&&ue.message_android],numberOfLines:2,children:e})]})}):null},ue=I.StyleSheet.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:I.StyleSheet.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});var q=require("react/jsx-runtime"),To=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Mi=0,Bs=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Hs=e=>{let[t,n]=(0,M.useState)(0);return(0,M.useEffect)(()=>{if(!e||F.Platform.OS!=="ios"){n(0);return}let o=F.Keyboard.addListener("keyboardWillChangeFrame",i=>n(Math.max(0,i.endCoordinates.height))),r=F.Keyboard.addListener("keyboardWillHide",()=>n(0));return()=>{o.remove(),r.remove()}},[e]),t},qs=M.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:l,bridge:s,opaque_background:c,allow_embedded_miniapps:a,keyboard_mode:p,onWebLoadEnd:d})=>{var k,ie;let m=F.Platform.OS==="ios",u=m&&p!=="scroll",S=Hs(m&&p==="resize"&&t),v=(0,M.useRef)(null),D=(0,M.useRef)(!1),C=J(ce,g=>g.instances[e]),x=C==null?void 0:C.app.app_id,j=C==null?void 0:C.app.manifest_url,A=C==null?void 0:C.context,G=C==null?void 0:C.url_params,Q=J(ae,g=>{var b;return((b=g.active)==null?void 0:b.owner)===e?g.active:null}),[me,Y]=(0,M.useState)(null),[h,L]=(0,M.useState)(Q);Q!==h&&(L(Q),Q?Y(null):(h==null?void 0:h.layout)===Se.top&&Y(h));let R=(Q==null?void 0:Q.layout)===Se.top?Q:me,[w,_e]=(0,M.useState)(()=>x?$(x):null),[te,H]=(0,M.useState)(!1),[ge,Ie]=(0,M.useState)(0),[We,re]=(0,M.useState)(0),[Fe,ne]=(0,M.useState)(!1),be=(0,M.useRef)(null),tt=g=>{be.current&&clearTimeout(be.current),be.current=setTimeout(()=>{be.current=null,ne(!0)},g)};(0,M.useEffect)(()=>()=>{be.current&&clearTimeout(be.current)},[]),(0,M.useEffect)(()=>{if(!x||!t&&w)return;let g=!0;return H(!1),(async()=>{let b=$(x),we=b?await Ve(b):!1;if(!g||(_e(we?ke=>!ke||ke.version!==b.version||ke.permissions.join(",")!==b.permissions.join(",")?b:ke:null),__DEV__&&Date.now()-Mi>1e4&&(Mi=Date.now(),await _n()),!g))return;let Je=await Nt(x),ot=Je!==void 0?Je:j?await ur(x,j):$(x);if(g){if(!ot){H(!0);return}_e(ke=>ke!=null?ke:ot)}})(),()=>{g=!1}},[t,x,j,ge]),(0,M.useEffect)(()=>ci(e,g=>v.current?(v.current.postMessage(g),!0):!1),[e]);let Tt=J(B,g=>{let b=x?g.downloads[x]:void 0;return(b==null?void 0:b.status)==="installed"?b.version:void 0});(0,M.useEffect)(()=>{if(t||!x||!w)return;let g=$(x);if(!g||g.version===w.version)return;let b=!0;return Ve(g).then(we=>{!b||!we||(ye(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",w.version,"\u2192",g.version),_e(g))}),()=>{b=!1}},[t,x,Tt,w==null?void 0:w.version]);let en=J(B,g=>{var b;return x&&(b=g.apply_ticks[x])!=null?b:0});(0,M.useEffect)(()=>{if(!en||!x)return;let g=$(x);if(!g||g.version===(w==null?void 0:w.version))return;let b=!0;return Ve(g).then(we=>{!b||!we||(ye(`webview:${e}`,"c\u1EADp nh\u1EADt",w==null?void 0:w.version,"\u2192",g.version),ne(!1),_e(g))}),()=>{b=!1}},[en]),(0,M.useEffect)(()=>{var we;let g=(we=U().keep_alive)==null?void 0:we.idle_close_ms;if(t||!g||g<=0)return;let b=setTimeout(()=>{dn(e)},g);return()=>clearTimeout(b)},[t,e]),(0,M.useEffect)(()=>{r>0&&(H(!1),ne(!1),re(g=>g+1),Ie(g=>g+1))},[r]);let tn=(0,M.useRef)(t);(0,M.useEffect)(()=>{var g;tn.current!==t&&(tn.current=t,D.current&&((g=v.current)==null||g.injectJavaScript(ti(t?"resumed":"paused"))))},[t]);let je=`${(k=w==null?void 0:w.version)!=null?k:"none"}:${(ie=w==null?void 0:w.permissions.join(","))!=null?ie:""}:${We}`,Ge=(0,M.useMemo)(()=>JSON.stringify([A!=null?A:{},G!=null?G:{}]),[A,G]),nt=(0,M.useMemo)(()=>{var g;return si(G!=null?G:{},(g=w==null?void 0:w.permissions)!=null?g:[])},[Ge,w==null?void 0:w.permissions]),$n=(0,M.useMemo)(()=>ri(A!=null?A:{},nt,{keyboard_mode:u?p:void 0})+Zr()+ei()+(U().debug?Qr():""),[nt]),gt=(0,M.useRef)(null),nn=(0,M.useRef)(null);(0,M.useEffect)(()=>{var b,we,Je;if(!w)return;if(nn.current!==je){nn.current=je,gt.current=Ge;return}if(gt.current===Ge)return;let g=((we=JSON.parse((b=gt.current)!=null?b:"[]")[0])!=null?we:{}).org_id;if(gt.current=Ge,g===(A==null?void 0:A.org_id)&&D.current){ne(!1),tt(1500),(Je=v.current)==null||Je.injectJavaScript(ni(A!=null?A:{},nt));return}ne(!1),re(ot=>ot+1)},[Ge,w,je]),(0,M.useEffect)(()=>(t||(Ne(e),Ze(e),it(e)),()=>{Ne(e),Ze(e),it(e)}),[t,e,je,r]),(0,M.useEffect)(()=>{let g=F.AppState.addEventListener("change",b=>{b==="background"&&!Fr()&&Ne(e),b==="background"&&!Br()&&Ze(e)});return()=>g.remove()},[e]);let on=(0,M.useCallback)(async g=>{var we,Je,ot,ke,Wn,Ro;let b=Jr(g.nativeEvent.data);if(!b){if(x&&hi(g.nativeEvent.data,{app_id:x,instance_id:e},s==null?void 0:s.agent))return;if(x&&(s!=null&&s.onWebEvent))try{Promise.resolve(s.onWebEvent(g.nativeEvent.data,{app_id:x,instance_id:e})).catch(Z=>{console.warn("[miniapp] onWebEvent l\u1ED7i",x,Z)})}catch(Z){console.warn("[miniapp] onWebEvent l\u1ED7i",x,Z)}return}if(b.method==="log"){let{level:Z,text:oe}=b;ye(`web:${e}`,Z!=null?Z:"log",oe!=null?oe:"");return}if(b.method==="pong"){be.current||ne(!0);return}if(b.method==="touchAtTop"){i.emit(!!b.at_top);return}if(b.method==="contextApplied"){be.current&&clearTimeout(be.current),be.current=null,ne(!0);return}if(b.method==="ready"){D.current=!0,ne(!0);let Z=(we=ce.getState().instances[e])==null?void 0:we.context;Z&&((Je=v.current)==null||Je.injectJavaScript(yo(Z)));return}try{let Z=await li(b,{getHostData:()=>{var oe,Me;return(Me=(oe=ce.getState().instances[e])==null?void 0:oe.host_data)!=null?Me:{}},getPermissions:()=>{var oe,Me;return x?(Me=(oe=$(x))==null?void 0:oe.permissions)!=null?Me:[]:[]},getContext:()=>{var oe,Me;return(Me=(oe=ce.getState().instances[e])==null?void 0:oe.context)!=null?Me:{}},is_dark:o,close:mt,app_id:x!=null?x:"",instance_id:e,options:s,emit:(oe,Me)=>{var Oo;(Oo=v.current)==null||Oo.injectJavaScript(Xr(oe,Me))},playBeep:(ot=s==null?void 0:s.playScannerBeep)!=null?ot:(()=>{var oe;(oe=v.current)==null||oe.injectJavaScript(ai())}),isActive:()=>ce.getState().active_key===e&&F.AppState.currentState!=="background"});b.id&&((ke=v.current)==null||ke.injectJavaScript(Kr(b.id,Z)))}catch(Z){if(!b.id)return;let oe=Z==null?void 0:Z.code,Me=Z instanceof f?Z:new f(typeof oe=="string"?oe:"HOST_ERROR",String((Wn=Z==null?void 0:Z.message)!=null?Wn:Z));(Ro=v.current)==null||Ro.injectJavaScript(Yr(b.id,Me))}},[e,o,x,i,s]),rn=(0,M.useCallback)(()=>{H(!1),re(g=>g+1),Ie(g=>g+1)},[]);return(0,q.jsxs)(F.View,{style:[F.StyleSheet.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&Te.behind],pointerEvents:t?"auto":"none",children:[R&&(0,q.jsx)(Co,{scanner:R,closing:R===me,onClosed:()=>{var g;Y(null),R.absolute&&((g=v.current)==null||g.injectJavaScript(_o(0)))},onHeight:R.absolute?g=>{var b;return(b=v.current)==null?void 0:b.injectJavaScript(_o(g))}:void 0}),w?(0,q.jsx)(xi.default,{ref:v,source:{uri:w.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${a?Zn():w.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:$n,onMessage:on,onShouldStartLoadWithRequest:g=>{let b=g.url;return g.isTopFrame===!1||!/^https?:\/\//i.test(b)?!0:(Promise.resolve(s!=null&&s.openUrl?s.openUrl(b):F.Linking.openURL(b)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",scrollEnabled:!u,onLoadStart:g=>{Ne(e),Ze(e),it(e),ye(`webview:${e}`,"load start",To(g.nativeEvent.url)),D.current=!1,ne(!1)},onError:g=>{Ne(e),Ze(e),it(e),ye(`webview:${e}`,"load error",To(g.nativeEvent.url),g.nativeEvent.description),H(!0),ne(!1)},onLoadEnd:g=>{let b=g.nativeEvent.url;ye(`webview:${e}`,"load end",To(b)),x&&(d==null||d({app_id:x,instance_id:e,url:b})),tt(1500)},onContentProcessDidTerminate:()=>{Ne(e),Ze(e),it(e),D.current=!1,ne(!1),re(g=>g+1)},onRenderProcessGone:()=>(Ne(e),Ze(e),it(e),D.current=!1,ne(!1),re(g=>g+1),!0),style:[Te.webview,S>0&&{marginBottom:S}]},je):null,(Q==null?void 0:Q.layout)===Se.full&&(0,q.jsx)(Co,{scanner:Q}),C&&(0,q.jsx)($s,{visible:!w||!Fe,interactive:te,children:(0,q.jsx)(zs,{splash:l,app:C.app,is_dark:o,error:te,has_bundle:!!w,retry:rn})})]})}),zs=M.default.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let l=e,s=yt(t.app_id),c=o?"error":!r&&(s==null?void 0:s.status)==="downloading"?"downloading":"loading";return(0,q.jsx)(l,{app:t,is_dark:n,status:c,progress:c==="downloading"?s==null?void 0:s.progress:void 0,retry:i})}),$s=({visible:e,interactive:t,children:n})=>{let o=(0,M.useRef)(new F.Animated.Value(e?1:0)).current,[r,i]=(0,M.useState)(e);return(0,M.useEffect)(()=>{if(e){i(!0),o.setValue(1);return}let l=F.Animated.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return l.start(({finished:s})=>{s&&i(!1)}),()=>l.stop()},[e,o]),r?(0,q.jsx)(F.Animated.View,{style:[F.StyleSheet.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},Po=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return(0,q.jsxs)(F.View,{style:[Te.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,q.jsx)(F.View,{style:[Te.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,q.jsx)(F.Image,{source:{uri:e.icon},style:Te.splash_icon_image}):(0,q.jsx)(F.Text,{style:Te.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,q.jsx)(F.Text,{style:[Te.splash_name,{color:i}],children:e.name}),n==="error"?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(F.Text,{style:Te.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,q.jsx)(F.TouchableOpacity,{activeOpacity:.7,style:[Te.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,q.jsx)(F.Text,{style:[Te.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(F.ActivityIndicator,{style:Te.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,q.jsxs)(F.Text,{style:Te.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},vi=(e,t)=>{let n=(0,M.useRef)(t),o=(0,M.useRef)(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},Ws=({container:e,splash:t=Po,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:l=!1,keyboard_mode:s="scroll",onWebLoadEnd:c})=>{vi("container",e),vi("splash",t);let a=e,p=J(ce,A=>A.active_key),d=(0,M.useRef)(p);p&&(d.current=p);let m=J(ce,A=>Object.keys(A.instances).join("|")),u=J(ce,A=>{var G;return A.active_key?(G=A.instances[A.active_key])==null?void 0:G.app.name:void 0}),S=(0,M.useMemo)(()=>m?m.split("|"):[],[m]),[v,D]=(0,M.useState)({}),C=(0,M.useRef)(Bs()).current,x=o==null?void 0:o.agent;(0,M.useEffect)(()=>x?fi(x):void 0,[x]),(0,M.useEffect)(()=>{if(!p||!r)return;let A=F.BackHandler.addEventListener("hardwareBackPress",()=>(mt(),!0));return()=>A.remove()},[p,r]);let j=(0,M.useCallback)(()=>{let A=ce.getState().active_key;A&&D(G=>({...G,[A]:(G[A]||0)+1}))},[]);return S.length?(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(a,{visible:!!p,title:u!=null?u:"",is_dark:n,close:mt,reload:j,subscribeWebAtTop:C.subscribe,children:S.map(A=>(0,q.jsx)(qs,{instance_key:A,is_active:p===A,is_front:(p!=null?p:d.current)===A,is_dark:n,reload_tick:v[A]||0,web_at_top:C,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:l,keyboard_mode:s,onWebLoadEnd:c},A))}),(0,q.jsx)(Si,{})]}):null},Te=F.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"}}),Ci=M.default.memo(Ws);var dt=he(require("react"));var $e=require("react"),E=require("react-native");var de=require("react-native");var js=/\*\*(.+?)\*\*|`([^`]+)`|\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,Jt=e=>{var o;let t=[],n=0;for(let r of e.matchAll(js)){let i=(o=r.index)!=null?o:0;i>n&&t.push({type:"text",text:e.slice(n,i)}),r[1]!==void 0?t.push({type:"bold",text:r[1]}):r[2]!==void 0?t.push({type:"code",text:r[2]}):t.push({type:"link",text:r[3],url:r[4]}),n=i+r[0].length}return n<e.length&&t.push({type:"text",text:e.slice(n)}),t},Ei=e=>Jt(e).map(t=>t.text).join("");var et=require("react-native");var xt=require("react"),ki=require("react/jsx-runtime"),Vn={changelog_title:"C\xF3 g\xEC m\u1EDBi",changelog_ok:"\u0110\xE3 hi\u1EC3u",changelog_view_all:"Xem t\u1EA5t c\u1EA3 c\u1EADp nh\u1EADt",changelog_more:"+{count} thay \u0111\u1ED5i kh\xE1c",history_title:"L\u1ECBch s\u1EED c\u1EADp nh\u1EADt",history_empty:"Ch\u01B0a c\xF3 ghi ch\xFA c\u1EADp nh\u1EADt.",history_error:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c l\u1ECBch s\u1EED c\u1EADp nh\u1EADt.",retry:"Th\u1EED l\u1EA1i",update_title:"\u0110\xE3 c\xF3 b\u1EA3n c\u1EADp nh\u1EADt",updating_title:"\u0110ang c\u1EADp nh\u1EADt\u2026",update_message:`Phi\xEAn b\u1EA3n {next} \u0111\xE3 s\u1EB5n s\xE0ng (hi\u1EC7n t\u1EA1i {current}).
89
+ Vui l\xF2ng c\u1EADp nh\u1EADt \u0111\u1EC3 ti\u1EBFp t\u1EE5c s\u1EED d\u1EE5ng.`,update_failed:"C\u1EADp nh\u1EADt kh\xF4ng th\xE0nh c\xF4ng. Ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng r\u1ED3i th\u1EED l\u1EA1i.",update_now:"C\u1EADp nh\u1EADt ngay",updating_hint:"Vui l\xF2ng kh\xF4ng t\u1EAFt \u1EE9ng d\u1EE5ng",date_locale:"vi-VN"},Bn=(e,t)=>e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n),Hn=[{key:"new",label:"M\u1EDBi",color:"#007AFF",bg:"#E5F1FF"},{key:"fix",label:"S\u1EEDa l\u1ED7i",color:"#C4320A",bg:"#FFF1EB"},{key:"improve",label:"C\u1EA3i thi\u1EC7n",color:"#067647",bg:"#E7F7EE"}],Ue={primary:"#007AFF",on_primary:"#FFFFFF",background:"#F2F2F7",surface:"#FFFFFF",text:"#1C1C1E",text_secondary:"#666666",hint:"#AEAEB2",overlay:"rgba(0, 0, 0, 0.6)",divider:"rgba(60, 60, 67, 0.18)",radius:28,button_radius:12,button_height:50},Gs={primary:"#0A84FF",on_primary:"#FFFFFF",background:"#000000",surface:"#1C1C1E",text:"#FFFFFF",text_secondary:"#A1A1AA",hint:"#636366",overlay:"rgba(0, 0, 0, 0.7)",divider:"rgba(84, 84, 88, 0.6)",radius:28,button_radius:12,button_height:50},Js={new:{color:"#64B5FF",bg:"rgba(10, 132, 255, 0.18)"},fix:{color:"#FF9F7A",bg:"rgba(255, 112, 67, 0.18)"},improve:{color:"#5FD39A",bg:"rgba(48, 209, 88, 0.18)"}},ko=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Kt=(e={},t)=>{let{kinds:n,dark:o=!1,...r}=e;return{...o?Gs:Ue,...ko(r),dark:o,labels:{...Vn,...ko(t!=null?t:{})},kinds:Hn.map(i=>{var l;return{...i,...o?Js[i.key]:null,...i.key==="new"&&e.primary?{color:e.primary}:null,...ko((l=n==null?void 0:n[i.key])!=null?l:{})}})}},Ti=(0,xt.createContext)(void 0),Ks=Kt(),ct=({theme:e,labels:t,children:n})=>{let o=(0,xt.useMemo)(()=>Kt(e,t),[e,t]);return(0,ki.jsx)(Ti.Provider,{value:o,children:n})},Pe=()=>{var e;return(e=(0,xt.useContext)(Ti))!=null?e:Ks},Yt=e=>({new:e.flatMap(t=>t.changelog.new),fix:e.flatMap(t=>t.changelog.fix),improve:e.flatMap(t=>t.changelog.improve)}),Pi=(e,t)=>{let n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString(t)};var W={blue:Ue.primary,track:"#E5E5EA",overlay:Ue.overlay,shadow:"#000000",title:Ue.text,sub_title:Ue.text_secondary,error:"#D92D20",hint:Ue.hint,surface:Ue.surface,background:Ue.background},Ri=et.Platform.select({ios:{shadowColor:W.shadow,shadowOffset:{width:0,height:10},shadowOpacity:.1,shadowRadius:20},android:{elevation:10}}),y=et.StyleSheet.create({overlay:{flex:1,backgroundColor:W.overlay,justifyContent:"center",alignItems:"center"},container:{width:"85%",maxWidth:340,backgroundColor:W.surface,padding:24,borderRadius:28,alignItems:"center",...Ri},sheet:{width:"88%",maxWidth:380,maxHeight:"78%",backgroundColor:W.surface,borderRadius:28,overflow:"hidden",...Ri},sheet_head:{alignItems:"center",paddingTop:24,paddingHorizontal:22,paddingBottom:4},sheet_name:{fontSize:13,color:W.sub_title,marginTop:4,maxWidth:"100%"},version_pill:{flexDirection:"row",alignItems:"center",gap:6,marginTop:10,paddingHorizontal:12,paddingVertical:5,borderRadius:999,backgroundColor:W.background},version_old:{fontSize:13,color:W.sub_title,fontVariant:["tabular-nums"]},version_arrow:{fontSize:13,color:W.hint},version_new:{fontSize:13,fontWeight:"700",color:W.blue,fontVariant:["tabular-nums"]},sheet_foot:{paddingHorizontal:22,paddingTop:4,paddingBottom:18},sheet_foot_divider:{borderTopWidth:et.StyleSheet.hairlineWidth,borderTopColor:"rgba(60, 60, 67, 0.18)"},logo:{width:64,height:64,borderRadius:16,marginBottom:20},title:{fontSize:20,fontWeight:"700",color:W.title,textAlign:"center"},sub_title:{fontSize:13,color:W.sub_title,textAlign:"center",lineHeight:18,marginTop:6},gap:{marginBottom:15},error_text:{fontSize:12,textAlign:"center",color:W.error,lineHeight:17,marginBottom:15},progress_section:{width:"100%",alignItems:"center",paddingVertical:8,marginTop:8,gap:12},progress_text:{fontSize:18,fontWeight:"700",color:W.blue},progress_track:{width:"100%",height:6,borderRadius:3,backgroundColor:W.track,overflow:"hidden"},progress_fill:{height:"100%",borderRadius:3,backgroundColor:W.blue},loading_hint:{fontSize:12,color:W.hint,textAlign:"center"},scroll:{flexGrow:0,flexShrink:1},scroll_content:{paddingHorizontal:22,paddingTop:16,paddingBottom:16},groups:{gap:18},group:{gap:8},group_head:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:2},group_count:{fontSize:12,fontWeight:"600",color:W.hint},dot:{width:5,height:5,borderRadius:3,marginTop:8},more:{fontSize:14,fontWeight:"500",color:W.blue,paddingLeft:17,paddingTop:2},badge:{alignSelf:"flex-start",paddingHorizontal:10,paddingVertical:3,borderRadius:999},badge_text:{fontSize:12,fontWeight:"700"},item:{flexDirection:"row",gap:10,paddingLeft:2},item_text:{flex:1,fontSize:15,lineHeight:21,color:W.title},md_bold:{fontWeight:"700"},md_code:{fontFamily:et.Platform.select({ios:"Menlo",default:"monospace"}),fontSize:13,backgroundColor:"#F2F2F7",color:"#3A3A3C"},md_link:{color:W.blue,textDecorationLine:"underline"},full:{width:"100%"},btn_primary:{marginTop:14,backgroundColor:W.blue,paddingVertical:14,borderRadius:12,alignItems:"center"},btn_primary_text:{color:"white",fontWeight:"600",fontSize:16},btn_secondary:{paddingTop:12,alignItems:"center"},link:{color:W.blue,fontSize:15,fontWeight:"600"},history:{flex:1,backgroundColor:W.background},float_header:{position:"absolute",top:0,left:0,right:0},header_row:{flexDirection:"row",alignItems:"center",paddingHorizontal:16,paddingTop:2,paddingBottom:8},header_title:{position:"absolute",top:2,bottom:8,alignItems:"center",justifyContent:"center"},history_title:{fontSize:15,fontWeight:"500",color:"#1C1C1E"},history_sub:{fontSize:11,color:"#71717A",marginTop:1},back_btn:{alignItems:"center",justifyContent:"center"},back_btn_fallback:{backgroundColor:W.surface,...et.Platform.select({ios:{shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8},default:{borderWidth:et.StyleSheet.hairlineWidth*2,borderColor:"rgba(0, 0, 0, 0.08)"}})},icon_layer:{position:"absolute",top:0,left:0,right:0,bottom:0,alignItems:"center",justifyContent:"center"},fade:{position:"absolute",top:0,left:0,right:0},chevron:{width:11,height:11,borderLeftWidth:2.2,borderBottomWidth:2.2,borderColor:Ue.text,transform:[{rotate:"45deg"}],marginLeft:4},pressed:{opacity:.6,transform:[{scale:.94}]},history_list:{padding:16,gap:12},card:{backgroundColor:W.surface,borderRadius:16,padding:16,gap:12},card_head:{flexDirection:"row",justifyContent:"space-between",alignItems:"baseline"},version:{fontSize:16,fontWeight:"700",color:W.title},date:{fontSize:13,color:W.sub_title},loading:{marginTop:40},center:{alignItems:"center",marginTop:40,gap:12},empty:{marginTop:40}});var fe=require("react/jsx-runtime"),qn=({text:e,style:t})=>{let n=Pe();return(0,fe.jsx)(de.Text,{style:t,children:Jt(e.replace(/^(?:[-*•]\s+)+/,"")).map((o,r)=>{switch(o.type){case"bold":return(0,fe.jsx)(de.Text,{style:y.md_bold,children:o.text},r);case"code":return(0,fe.jsx)(de.Text,{style:[y.md_code,{backgroundColor:n.background,color:n.text}],children:o.text},r);case"link":return(0,fe.jsx)(de.Text,{style:[y.md_link,{color:n.primary}],accessibilityRole:"link",onPress:()=>{de.Linking.openURL(o.url).catch(()=>{})},children:o.text},r);default:return o.text}})})},pt=({changelog:e,max_items:t,onMore:n})=>{let o=Pe();return(0,fe.jsx)(de.View,{style:y.groups,children:o.kinds.filter(r=>e[r.key].length).map(r=>{let i=e[r.key],l=t?i.slice(0,t):i,s=i.length-l.length;return(0,fe.jsxs)(de.View,{style:y.group,children:[(0,fe.jsxs)(de.View,{style:y.group_head,children:[(0,fe.jsx)(de.View,{style:[y.badge,{backgroundColor:r.bg}],children:(0,fe.jsx)(de.Text,{style:[y.badge_text,{color:r.color}],children:r.label})}),(0,fe.jsx)(de.Text,{style:[y.group_count,{color:o.hint}],children:i.length})]}),l.map((c,a)=>(0,fe.jsxs)(de.View,{style:y.item,children:[(0,fe.jsx)(de.View,{style:[y.dot,{backgroundColor:r.color}]}),(0,fe.jsx)(qn,{text:c,style:[y.item_text,{color:o.text}]})]},a)),s>0&&(0,fe.jsx)(de.Text,{style:[y.more,{color:o.primary}],onPress:n,suppressHighlighting:!0,children:Bn(o.labels.changelog_more,{count:s})})]},r.key)})})};var Ct=require("react"),N=require("react-native");var z=require("react/jsx-runtime"),zn,Ys=()=>(zn!=null||(zn=Promise.all([N.Platform.OS==="ios"?import("expo-image").then(e=>e.Image).catch(()=>{}):Promise.resolve(void 0),import("expo-linear-gradient").then(e=>e.LinearGradient).catch(()=>{})]).then(([e,t])=>({ExpoImage:e,LinearGradient:t}))),zn),Xs=()=>{let[e,t]=(0,Ct.useState)({});return(0,Ct.useEffect)(()=>{let n=!0;return Ys().then(o=>{n&&t(o)}),()=>{n=!1}},[]),e},Qs="#1C1C1E",Zs=e=>/^#[0-9a-f]{6}$/i.test(e),ea=()=>{let[e,t]=(0,Ct.useState)();return(0,Ct.useEffect)(()=>{let n=!0;return Bt().then(o=>{n&&o&&t(()=>o)}),()=>{n=!1}},[]),e},ta=({onPress:e,size:t,GlassView:n,ExpoImage:o})=>{let r=Pe(),i=r.dark?"#FFFFFF":Qs;return(0,z.jsxs)(N.Pressable,{onPress:e,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"Quay l\u1EA1i",style:({pressed:l})=>[y.back_btn,{width:t,height:t,borderRadius:t/2},!n&&y.back_btn_fallback,!n&&r.dark&&{backgroundColor:"#3F3F46",shadowOpacity:0},!n&&l&&y.pressed],children:[n&&(0,z.jsx)(n,{style:[N.StyleSheet.absoluteFill,{borderRadius:t/2}],glassEffectStyle:"regular",colorScheme:r.dark?"dark":"light",isInteractive:!0}),(0,z.jsx)(N.View,{pointerEvents:"none",style:y.icon_layer,children:o?(0,z.jsx)(o,{source:"sf:chevron.left",transition:0,contentFit:"contain",style:{width:20,height:20,fontSize:20,color:i}}):(0,z.jsx)(N.View,{style:[y.chevron,{borderColor:i}]})})]})},Et=({app_id:e,name:t,onBack:n,renderHeader:o})=>{let r=Pe(),i=Mt(),l=ea(),{ExpoImage:s,LinearGradient:c}=Xs(),a=l?46:42,p=o?0:i.top+a+10,{versions:d,loading:m,error:u,reload:S}=Sn(e);return(0,z.jsxs)(N.View,{style:[y.history,{backgroundColor:r.background}],children:[o&&(0,z.jsx)(N.View,{style:{paddingTop:i.top},children:o({title:r.labels.history_title,subtitle:t,onBack:n})}),m&&!d.length?(0,z.jsx)(N.ActivityIndicator,{style:[y.loading,{marginTop:p+40}],color:r.primary}):u&&!d.length?(0,z.jsxs)(N.View,{style:[y.center,{marginTop:p+40}],children:[(0,z.jsx)(N.Text,{style:[y.sub_title,{color:r.text_secondary}],children:r.labels.history_error}),(0,z.jsx)(N.TouchableOpacity,{onPress:S,children:(0,z.jsx)(N.Text,{style:[y.link,{color:r.primary}],children:r.labels.retry})})]}):(0,z.jsxs)(N.ScrollView,{contentContainerStyle:[y.history_list,{paddingTop:p+8,paddingBottom:i.bottom+24}],scrollIndicatorInsets:{top:p},children:[d.map(v=>(0,z.jsxs)(N.View,{style:[y.card,{backgroundColor:r.surface,borderRadius:Math.max(r.radius-12,0)}],children:[(0,z.jsxs)(N.View,{style:y.card_head,children:[(0,z.jsxs)(N.Text,{style:[y.version,{color:r.text}],children:["v",v.version]}),(0,z.jsx)(N.Text,{style:[y.date,{color:r.text_secondary}],children:Pi(v.created_at,r.labels.date_locale)})]}),(0,z.jsx)(pt,{changelog:v.changelog})]},v.version)),!d.length&&(0,z.jsx)(N.Text,{style:[y.sub_title,y.empty,{color:r.text_secondary}],children:r.labels.history_empty})]}),!o&&(0,z.jsxs)(N.View,{pointerEvents:"box-none",style:[y.float_header,{paddingTop:i.top}],children:[c&&Zs(r.background)?(0,z.jsx)(c,{pointerEvents:"none",colors:[`${r.background}F5`,`${r.background}E6`,`${r.background}B3`,`${r.background}00`],locations:[0,.45,.75,1],style:[y.fade,{height:p+28}]}):(0,z.jsx)(N.View,{pointerEvents:"none",style:y.fade,children:na.map((v,D)=>(0,z.jsx)(N.View,{style:{height:D===0?p:4,backgroundColor:r.background,opacity:v}},D))}),(0,z.jsxs)(N.View,{style:y.header_row,children:[(0,z.jsx)(ta,{onPress:n,size:a,GlassView:l,ExpoImage:s}),(0,z.jsxs)(N.View,{pointerEvents:"none",style:[y.header_title,{left:a+24,right:a+24}],children:[(0,z.jsx)(N.Text,{style:[y.history_title,{color:r.text}],numberOfLines:1,children:r.labels.history_title}),(0,z.jsx)(N.Text,{style:[y.history_sub,{color:r.text_secondary}],numberOfLines:1,children:t})]})]})]})]})},na=[.96,.9,.8,.68,.55,.42,.3,.18,.08];var O=require("react/jsx-runtime"),Oi=e=>({backgroundColor:e.primary,borderRadius:e.button_radius,height:e.button_height,paddingVertical:0,justifyContent:"center"}),oa=4,Xt=({request:e,changelog:t,onClose:n,renderHistoryHeader:o,renderActions:r})=>{var m;let i=Pe(),[l,s]=(0,$e.useState)(!1),[c,a]=(0,$e.useState)(0),[p,d]=(0,$e.useState)(0);return(0,O.jsx)(E.Modal,{visible:!0,transparent:!l,animationType:l?"slide":"fade",statusBarTranslucent:!0,onRequestClose:l?()=>s(!1):n,children:l?(0,O.jsx)(Et,{app_id:e.app_id,name:e.name,onBack:()=>s(!1),renderHeader:o}):(0,O.jsxs)(E.View,{style:[y.overlay,{backgroundColor:i.overlay}],children:[(0,O.jsx)(E.Pressable,{style:E.StyleSheet.absoluteFill,onPress:n,accessibilityLabel:"\u0110\xF3ng"}),(0,O.jsxs)(E.View,{style:[y.sheet,{backgroundColor:i.surface,borderRadius:i.radius}],children:[(0,O.jsxs)(E.View,{style:y.sheet_head,children:[(0,O.jsx)(E.Text,{style:[y.title,{color:i.text}],children:i.labels.changelog_title}),(0,O.jsx)(E.Text,{style:[y.sheet_name,{color:i.text_secondary}],numberOfLines:1,children:e.name}),(0,O.jsxs)(E.View,{style:[y.version_pill,{backgroundColor:i.background}],children:[(0,O.jsx)(E.Text,{style:[y.version_old,{color:i.text_secondary}],children:`v${e.from}`}),(0,O.jsx)(E.Text,{style:[y.version_arrow,{color:i.hint}],children:"\u2192"}),(0,O.jsx)(E.Text,{style:[y.version_new,{color:i.primary}],children:`v${e.to}`})]})]}),(0,O.jsx)(E.ScrollView,{style:y.scroll,contentContainerStyle:y.scroll_content,onContentSizeChange:(u,S)=>a(S),onLayout:u=>d(u.nativeEvent.layout.height),children:(0,O.jsx)(pt,{changelog:t,max_items:oa,onMore:()=>s(!0)})}),(0,O.jsx)(E.View,{style:[y.sheet_foot,c>p+1&&[y.sheet_foot_divider,{borderTopColor:i.divider}]],children:r?r({onClose:n,onViewAll:()=>s(!0),labels:i.labels}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.TouchableOpacity,{style:[y.btn_primary,Oi(i)],activeOpacity:.8,onPress:n,children:(0,O.jsx)(E.Text,{style:[y.btn_primary_text,{color:i.on_primary}],children:i.labels.changelog_ok})}),(0,O.jsx)(E.TouchableOpacity,{style:y.btn_secondary,onPress:()=>s(!0),children:(0,O.jsx)(E.Text,{style:[y.link,{color:(m=i.secondary)!=null?m:i.primary}],children:i.labels.changelog_view_all})})]})})]})]})})},Qt=({update:e,is_updating:t,progress:n,has_failed:o,onUpdate:r,logo:i,renderAction:l})=>{let s=Pe(),c=(0,$e.useRef)(new E.Animated.Value(0)).current,a=(0,$e.useRef)(new E.Animated.Value(30)).current;return(0,$e.useEffect)(()=>{E.Animated.parallel([E.Animated.timing(c,{toValue:1,duration:400,useNativeDriver:!0}),E.Animated.spring(a,{toValue:0,friction:8,tension:40,useNativeDriver:!0})]).start()},[c,a]),(0,O.jsx)(E.Modal,{visible:!0,transparent:!0,animationType:"none",statusBarTranslucent:!0,onRequestClose:()=>{},children:(0,O.jsx)(E.View,{style:[y.overlay,{backgroundColor:s.overlay}],children:(0,O.jsxs)(E.Animated.View,{style:[y.container,{backgroundColor:s.surface,borderRadius:s.radius},{opacity:c,transform:[{translateY:a}]}],children:[i&&(0,O.jsx)(E.Image,{source:i,style:y.logo}),(0,O.jsx)(E.Text,{style:[y.title,{color:s.text}],children:t?s.labels.updating_title:s.labels.update_title}),!t&&(0,O.jsx)(E.Text,{style:[y.sub_title,y.gap,{color:s.text_secondary}],children:Bn(s.labels.update_message,{next:e.next_version,current:e.current_version})}),!t&&o&&(0,O.jsx)(E.Text,{style:y.error_text,children:s.labels.update_failed}),t?(0,O.jsxs)(E.View,{style:y.progress_section,children:[(0,O.jsxs)(E.Text,{style:[y.progress_text,{color:s.primary}],children:[n,"%"]}),(0,O.jsx)(E.View,{style:[y.progress_track,{backgroundColor:s.background}],children:(0,O.jsx)(E.View,{style:[y.progress_fill,{backgroundColor:s.primary,width:`${n}%`}]})}),(0,O.jsx)(E.Text,{style:[y.loading_hint,{color:s.hint}],children:s.labels.updating_hint})]}):l?(0,O.jsx)(E.View,{style:y.full,children:l({onUpdate:r,has_failed:o,label:o?s.labels.retry:s.labels.update_now})}):(0,O.jsx)(E.TouchableOpacity,{style:[y.btn_primary,y.full,Oi(s)],activeOpacity:.8,onPress:r,children:(0,O.jsx)(E.Text,{style:[y.btn_primary_text,{color:s.on_primary}],children:o?s.labels.retry:s.labels.update_now})})]})})})},Zt=({app_id:e,name:t,onClose:n,renderHistoryHeader:o})=>(0,O.jsx)(E.Modal,{visible:!0,animationType:"slide",statusBarTranslucent:!0,onRequestClose:n,children:(0,O.jsx)(Et,{app_id:e,name:t,onBack:n,renderHeader:o})});var ut=require("react/jsx-runtime"),ra=({app_ids:e,shouldShowUpdate:t,logo:n,renderUpdate:o,renderChangelog:r,theme:i,renderHistoryHeader:l,labels:s,renderChangelogActions:c,renderUpdateAction:a})=>{var Q,me;let p=J(B,Y=>Y.updates),m=((Q=e!=null?e:U().manual_update)!=null?Q:[]).map(Y=>p[Y]).find(Y=>!!Y&&(!t||t(Y))),u=yt(m==null?void 0:m.app_id),[S,v]=(0,dt.useState)(!1),[D,C]=(0,dt.useState)(!1),x=(0,dt.useRef)(!1),j=vn(),A=En(),G=async()=>{if(!m||x.current)return;x.current=!0,v(!0),C(!1);let Y=await bn(m.app_id);x.current=!1,v(!1),C(!Y)};if(m){let Y=(u==null?void 0:u.status)==="updating"?Math.round(((me=u.progress)!=null?me:0)*100):0,h={update:m,is_updating:S,progress:Y,has_failed:D,onUpdate:G};return(0,ut.jsx)(ct,{theme:i,labels:s,children:o?o(h):(0,ut.jsx)(Qt,{...h,logo:n,renderAction:a})})}if(j){let Y={request:j,changelog:Yt(j.versions),onClose:Mn};return(0,ut.jsx)(ct,{theme:i,labels:s,children:r?r(Y):(0,ut.jsx)(Xt,{...Y,renderHistoryHeader:l,renderActions:c})})}return A?(0,ut.jsx)(ct,{theme:i,labels:s,children:(0,ut.jsx)(Zt,{...A,onClose:Cn,renderHistoryHeader:l})}):null},Ii=dt.default.memo(ra);0&&(module.exports={AGENT_BRIDGE_VERSION,AGENT_MESSAGE_EVENT,AGENT_PAYLOAD_META_EVENT,AGENT_PAYLOAD_META_RESULT_EVENT,AGENT_STOPPED_EVENT,CodeType,DEFAULT_MINIAPP_UPDATES_LABELS,DefaultMiniAppChangelogHistoryModal,DefaultMiniAppChangelogPrompt,DefaultMiniAppSplash,DefaultMiniAppUpdatePrompt,MINIAPP_CHANGELOG_KINDS,MINIAPP_PLATFORM_URL,MiniAppChangelogGroups,MiniAppChangelogHistory,MiniAppChangelogText,MiniAppHost,MiniAppHostError,MiniAppUpdates,MiniAppUpdatesThemeProvider,ScannerEndReason,ScannerEvent,ScannerLayout,ScannerMethod,ToastType,closeMiniApp,closeMiniAppChangelogHistory,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,dismissMiniAppChangelog,ensureMiniApp,fetchMiniAppChangelog,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppChangelogSeen,getMiniAppIdByAgentId,getMiniAppStatuses,getMiniAppUpdate,getPendingChangelog,installBundledMiniApp,markMiniAppChangelogSeen,mergeMiniAppChangelog,onMiniAppEvent,openMiniApp,parseInlineMarkdown,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,resolveMiniAppUpdatesTheme,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,showMiniAppChangelog,showMiniAppChangelogHistory,stripInlineMarkdown,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppChangelog,useMiniAppChangelogHistoryRequest,useMiniAppChangelogRequest,useMiniAppDownload,useMiniAppDownloadsPaused,useMiniAppUpdatesTheme});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Mt="https://retion-miniapp-platform.vercel.app",nt=null,jo=new Set,Ji=e=>{nt=e,jo.forEach(t=>t())},R=()=>{if(!nt)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return nt},nn=e=>{jo.add(e),nt&&e()},ce=(...e)=>{nt!=null&&nt.debug&&console.log("[miniapp]",...e)};var Ki=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:l}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:s,contentLength:c})=>r==null?void 0:r(s,c)});return{promise:l.then(({statusCode:s})=>({status:s})),cancel:()=>e.stopDownload(i)}}}),Yi=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Oo,{useCallback as Po,useEffect as pe,useMemo as Cn,useRef as Ce,useState as Fe}from"react";import{AppState as Fi,ActivityIndicator as xa,Animated as Eo,BackHandler as Ca,Image as Ea,Keyboard as Li,Linking as Ta,Platform as Ui,StyleSheet as Io,Text as Kt,TouchableOpacity as Pa,View as ko}from"react-native";import ka from"react-native-webview";import{Linking as Yr,Platform as na}from"react-native";var Go=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),on,Nn=()=>(on||(on=import("react-native-biometrics").then(({default:e})=>Go(new e({allowDeviceCredentials:!1}))).catch(e=>{throw on=void 0,new f("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),on);import{PermissionsAndroid as ot,Platform as Xi}from"react-native";var Jo=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new f("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new f("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,l,s]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<l||c>s))throw new f("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${l}\u2013${s} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Ko=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,a)=>{r||(r=!0,clearTimeout(l),c?o(c):n(a))},l=setTimeout(()=>i(new f("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),s=()=>r?!1:t()?!0:(i(new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!s())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(s()){if(Xi.OS==="android"){let a=ot.PERMISSIONS.ACCESS_FINE_LOCATION,p=ot.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await ot.check(a);if(!s())return;let m=d||await ot.check(p);if(!s())return;if(!d&&!m){let u=await ot.requestMultiple([a,p]);if(!s())return;if(u[a]!==ot.RESULTS.GRANTED&&u[p]!==ot.RESULTS.GRANTED)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}s()&&c.getCurrentPosition(a=>{s()&&i(void 0,a)},a=>{var d;if(!s())return;let p=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[a.code])!=null?d:"LOCATION_ERROR";i(new f(p,a.message))},e)}})().catch(c=>i(c))});import{Platform as nr}from"react-native";var Un=20,Yo=20,or=/^[a-z][a-z0-9_-]{0,31}$/,Qi=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Zi=["low","medium","high"],Ge=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Q=e=>new f("INVALID_PARAMS",e),Et=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Xo=(e,t)=>{if(e===void 0)return{};if(!Ge(e)||Object.keys(e).length>Yo||Object.values(e).some(n=>typeof n!="string"))throw Q(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Yo} key)`);return e},rr=e=>{var n,o,r,i;if(e!==void 0&&!Ge(e))throw Q("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!or.test(t.source)))throw Q("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(l=>typeof l!="string"||!Qi.test(l))))throw Q("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Et(t.max_count,1,Un))throw Q(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Un}`);if(t.max_size!==void 0&&!Et(t.max_size,1,Number.MAX_SAFE_INTEGER))throw Q("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Et(t.concurrency,1,5))throw Q("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(l=>l.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:es(t.process),target:ts(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},es=e=>{if(e===void 0)return{};if(!Ge(e))throw Q("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Ge(n))throw Q("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Et(n[o],1,1e4))throw Q(`process.image.${o} 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 Q("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(!Ge(n))throw Q("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Et(n.max_duration,1,3600))throw Q("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Zi.includes(n.quality))throw Q("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},ts=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Ge(e))throw Q("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!or.test(t))throw Q("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Ge(e.params))throw Q("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw Q("upload.url ph\u1EA3i l\xE0 https");for(let l of["field_name","url_field"])if(e[l]!==void 0&&(typeof e[l]!="string"||!e[l]))throw Q(`upload.${l} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Xo(e.headers,"upload.headers"),form_data:Xo(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},ir=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},ns=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=ir(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},os=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},vt,rs=()=>(vt!=null||(vt=import("react-native-image-picker").catch(e=>{throw vt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),vt),Qo=e=>async({accept:t,max_count:n,process:o})=>{var c,a,p,d,m,u,A,S,P;let r=await rs(),i=os(t),l={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(a=o.image)==null?void 0:a.max_height,quality:(d=(p=o.image)==null?void 0:p.quality)!=null?d:.8,videoQuality:(u=(m=o.video)==null?void 0:m.quality)!=null?u:"medium",durationLimit:(A=o.video)==null?void 0:A.max_duration,assetRepresentationMode:"compatible"},s=e==="camera"?await r.launchCamera({...l,saveToPhotos:!1}):await r.launchImageLibrary({...l,selectionLimit:n});if(s.didCancel)return[];if(s.errorCode){let v=s.errorCode==="permission"?"PERMISSION_DENIED":s.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new f(v,(S=s.errorMessage)!=null?S:s.errorCode)}return((P=s.assets)!=null?P:[]).filter(v=>v.uri).map((v,M)=>{var U,w,V;return{uri:v.uri,name:(U=v.fileName)!=null?U:`file_${M+1}`,mime_type:(w=v.type)!=null?w:"application/octet-stream",size:v.fileSize,width:v.width,height:v.height,duration:v.duration,processed:!((V=v.type)!=null&&V.startsWith("video/"))||nr.OS==="ios"}})},is={"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"},ss={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},as=e=>async({accept:t,max_count:n})=>{var i,l,s,c;let o=t.map(a=>{var p;return(p=is[a])!=null?p:ss[a]}),r=!t.length||o.some(a=>!a||!e.types[a])?e.types.allFiles:[...new Set(o)].flatMap(a=>e.types[a]);try{let p=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,A)=>{var S,P,v;return{uri:u.uri,name:(S=u.name)!=null?S:`file_${A+1}`,mime_type:(P=u.type)!=null?P:"application/octet-stream",size:(v=u.size)!=null?v:void 0}});if(nr.OS!=="android"||!e.keepLocalCopy||!p.some(u=>u.uri.startsWith("content://")))return p;let d=await e.keepLocalCopy({files:p.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),m=new Map(d.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return p.map(u=>{var A;return{...u,uri:(A=m.get(u.uri))!=null?A:u.uri}})}catch(a){let p=a==null?void 0:a.code;if(p===((l=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?l:"OPERATION_CANCELED"))return[];throw p===((c=(s=e.errorCodes)==null?void 0:s.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new f("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):a}},xt,ls=async e=>(xt!=null||(xt=import("@react-native-documents/picker").then(t=>as(t)).catch(t=>{throw xt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await xt)(e)),sr={library:Qo("library"),camera:Qo("camera"),document:ls},Zo={type:"image",label:"\u1EA2nh",accept:["image/*"]},er={type:"video",label:"Video",accept:["video/*"]},tr={library:[Zo,er],camera:[Zo,er],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},Ct,ar=()=>(Ct!=null||(Ct=import("react-native-compressor").catch(()=>(Ct=void 0,null))),Ct),lr=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},cs=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),ps={low:640,medium:1280,high:1920},us=async(e,{image:t})=>{var o;if(!t||!cs.has(e.mime_type.toLowerCase()))return e;let n=await ar();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await lr(n,r,e.size),processed:!0}}catch{return e}},ds=async(e,{video:t})=>{var o;let n=await ar();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:ps[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await lr(n,r,e.size),processed:!0}}catch{return e}},gs={image:us,video:ds},hs=(e,t)=>t.split(".").reduce((n,o)=>Ge(n)?n[o]:void 0,e),cr=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new f("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let l=t;if(o.aborted){i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let s=new XMLHttpRequest,c=new FormData;Object.entries(l.form_data).forEach(([d,m])=>c.append(d,m)),c.append(l.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let a=()=>s.abort();o.addEventListener("abort",a);let p=d=>{o.removeEventListener("abort",a),d()};s.open("POST",l.url),Object.entries(l.headers).forEach(([d,m])=>s.setRequestHeader(d,m)),s.upload.onprogress=d=>n(d.loaded,d.total||e.size||0),s.onload=()=>p(()=>{let d=s.responseText;try{d=JSON.parse(s.responseText)}catch{}if(s.status<200||s.status>=300){i(new f("UPLOAD_FAILED",`HTTP ${s.status}`));return}let m=hs(d,l.url_field);if(typeof m!="string"||!m){i(new f("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${l.url_field}"`));return}r({url:m,response:d})}),s.onerror=()=>p(()=>i(new f("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),s.onabort=()=>p(()=>i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),s.send(c)}),pr=e=>{var o,r;let t={...sr};for(let[i,l]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))l?t[i]=l:delete t[i];let n={url:cr};for(let[i,l]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&l&&(n[i]=l);return{sources:t,targets:n}},ur=e=>{let{sources:t,targets:n}=pr(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===sr[i]&&tr[i]).map(i=>[i,tr[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Un}},sn=new Map,dr=(e,t)=>`${e}:${t}`,fs=0,gr=(e,t)=>{var n;typeof t=="string"&&((n=sn.get(dr(e,t)))==null||n.abort())},rt=e=>{for(let[t,n]of sn)t.startsWith(`${e}:`)&&n.abort()},rn=()=>new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),ms=(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)}},hr=async(e,t)=>{var c;let{sources:n,targets:o}=pr(t.config),r=n[e.source];if(!r)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let l=new AbortController,s=dr(t.instance_id,(c=t.task_id)!=null?c:`auto-${++fs}`);sn.set(s,l);try{return await ys(e,t,r,i,l.signal)}finally{sn.delete(s)}},ys=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:l,exclusivePick:s=d=>d()},c,a,p)=>{var H,h,T;let d={app_id:n!=null?n:"",instance_id:t,context:{...(H=o==null?void 0:o())!=null?H:{}}},m=(await s(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:d}))).slice(0,e.max_count);if(p.aborted)throw rn();if(!m.length)throw new f("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],A=m.filter(E=>ns(E,e.accept)?!0:(u.push({name:E.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${E.mime_type||ir(E.name)}`}),!1)),S=A.map(()=>0),P=A.map(E=>{var _;return(_=E.size)!=null?_:0}),v=0,M=0,U=(E=!1)=>{if(!l||!r)return;let _=Date.now();if(!E&&_-M<200)return;M=_;let ue=P.reduce((F,se)=>F+se,0),j=S.reduce((F,se)=>F+se,0);l("upload.progress",{task_id:r,loaded:j,total:ue,percent:ue?Math.min(100,Math.round(j/ue*100)):0,done_count:v,count:A.length})},w=[],V=0,z=async()=>{var E,_,ue;for(;V<A.length;){let j=V++,F=A[j];try{if(p.aborted)throw rn();let se=F.mime_type.startsWith("image/")?"image":F.mime_type.startsWith("video/")?"video":void 0,Pe=se&&!F.processed?(_=(E=i==null?void 0:i.processors)==null?void 0:E[se])!=null?_:gs[se]:void 0;if(Pe&&(F=await Pe(F,e.process),P[j]=(ue=F.size)!=null?ue:P[j],p.aborted))throw rn();if(e.max_size&&F.size&&F.size>e.max_size)throw new f("FILE_TOO_LARGE",`File ${F.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let ze=(de,Ze)=>{S[j]=de,Ze&&(P[j]=Ze),U()},Y=await a({file:F,target:e.target,onProgress:ze,signal:p,caller:d});if(typeof(Y==null?void 0:Y.url)!="string"||!Y.url)throw new f("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ke,...G}=Y;w[j]={url:ke,name:F.name,mime_type:F.mime_type,size:F.size,width:F.width,height:F.height,duration:F.duration,...Object.keys(G).length?{response:"response"in G?G.response:G}:{}},S[j]=P[j]}catch(se){u.push(ms(A[j].name,se))}finally{v++,U(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,A.length)},z)),p.aborted)throw rn();let le=w.filter(E=>!!E);if(!le.length){let E=u[0];throw new f((h=E==null?void 0:E.code)!=null?h:"UPLOAD_FAILED",(T=E==null?void 0:E.message)!=null?T:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:le,failed:u}};import{useRef as bs,useSyncExternalStore as _s}from"react";var Re=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},B=(e,t,n=Object.is)=>{let o=bs(null),r=()=>{let i=e.getState(),l=o.current;if(l&&l.state===i&&l.selector===t)return l.value;let s=t(i),c=l&&n(l.value,s)?l.value:s;return o.current={state:i,selector:t,value:c},c};return _s(e.subscribe,r)};var Me={info:"info",success:"success",error:"error"},ws=200,fr={info:2e3,success:2e3,error:3e3},Tt=Re({message:"",type:Me.info,tick:0}),mr=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,ws);return o?{message:o,type:Object.values(Me).includes(n)?n:Me.info}:null},yr=(e,t=Me.info)=>{Tt.setState(n=>({message:e,type:t,tick:n.tick+1}))};import{useCallback as zs,useEffect as $s,useState as gn}from"react";var Bn=e=>`bundle:${e}`,Hn=()=>`${R().file_system.document_dir}/miniapps`,qn=Hn,zn=(e,t,n="index.html",o=!1,r=[])=>{let i=`${qn()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Vn=e=>{var t;R().storage.setString(Bn(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},As=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,D=e=>{let t=R().storage.getString(Bn(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return zn(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Ue=e=>R().file_system.exists(e.entry_uri.replace("file://","")),$n=async e=>{let t=D(e.app_id);return(t==null?void 0:t.version)===e.version&&await Ue(t)},_r=async(e,t)=>{let n=R().file_system,o=`${qn()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},wr=async e=>{var t;await((t=kt[e])==null?void 0:t.catch(()=>{})),R().storage.setString(Bn(e),""),await R().file_system.remove(`${qn()}/${e}`).catch(()=>{})},pt=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},kt={},Ar=(e,t)=>{var i;let o=((i=kt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return kt[e]=r,r.then(()=>{kt[e]===r&&delete kt[e]}),o},Wn=(e,t)=>{var r,i;let n=e.split(".").map(l=>parseInt(l,10)||0),o=t.split(".").map(l=>parseInt(l,10)||0);for(let l=0;l<Math.max(n.length,o.length);l++){let s=((r=n[l])!=null?r:0)-((i=o[l])!=null?i:0);if(s)return s}return 0},Ss=({manifest:e,zip_path:t})=>Ar(e.app_id,async()=>{var i;let n=R().file_system,o=D(e.app_id);if(o&&Wn(o.version,e.version)>=0&&await Ue(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=zn(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),Vn(e),ce("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),_r(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),jn=(e,{base_url:t,onProgress:n}={})=>{let o=R().file_system,r=null,i=!1,l=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,s=()=>{if(i)throw new pt},c=async()=>{var d;s();let a=D(e.app_id);if((a==null?void 0:a.version)===e.version&&await o.exists(a.dir))return Vn(e),D(e.app_id);s();let p=o.download({url:t?As(t,e.bundle_url):e.bundle_url,to_file:l,onProgress:(m,u)=>{var S;let A=u>0?u:(S=e.size)!=null?S:0;A>0&&(n==null||n(Math.min(1,m/A)))}});r=p;try{let{status:m}=await p.promise;if(s(),m!==200)throw new Error(`bundle ${m}`);if(e.sha256)if(o.sha256){if(await o.sha256(l)!==e.sha256)throw new Error("sha256 mismatch")}else ce("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);s();let u=zn(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(l,u.dir),Vn(e),_r(e.app_id,[e.version,a==null?void 0:a.version].filter(Boolean)),u}catch(m){throw i?new pt:m}finally{r=null,o.remove(l).catch(()=>{})}};return{promise:Ar(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},Pt={},Ms=__DEV__?0:60*1e3,br={},Sr=(e,t)=>{var o,r;let n=D(e);return n&&Date.now()-((o=br[t])!=null?o:0)<Ms?Promise.resolve(n):((r=Pt[e])!=null||(Pt[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let l=await i.json(),s=await jn(l,{base_url:t}).promise;return br[t]=Date.now(),s})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),D(e))).finally(()=>{Pt[e]=void 0})),Pt[e])};var re=Re({active_key:null,instances:{}}),Mr=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var s;let l=(s=R().keep_alive)==null?void 0:s.max_webviews;re.setState(c=>{let a=t!=null?t:e.app_id,p={...c.instances,[a]:{key:a,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},d=Object.keys(p);return l&&l>0&&d.length>l&&d.filter(m=>m!==a).sort((m,u)=>p[m].last_used_at-p[u].last_used_at).slice(0,d.length-l).forEach(m=>{delete p[m]}),i?{active_key:a,instances:p}:{instances:p}})},vs=e=>Mr(e,!0),xs=e=>Mr(e,!1),Rt=()=>re.setState({active_key:null}),an=e=>{re.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var vr="catalog",Cs="paused_apps",Es="removed_apps",Ts=10*1e3,Ps=2,ks=3e3,Rs=()=>{var e;try{return JSON.parse((e=R().storage.getString(vr))!=null?e:"{}")}catch{return{}}},I=Re({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),xr=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},pn=new Set,Cr=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=R().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},xe=Cr(Cs),Ke=Cr(Es);nn(()=>{xe.load(),Ke.load();let e=Rs(),t={};Object.keys(e).filter(n=>!Ke.has(n)).forEach(n=>{let o=D(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:xe.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),I.setState({catalog:e,downloads:t})});var It=e=>B(I,t=>e?t.downloads[e]:void 0),Os=()=>B(I,e=>e.pause_reasons.length>0),ve=(...e)=>ce("queue",...e),te=[],Ve={},O=null,ln=new Set,it={},Gn=new Set,Be=e=>{Gn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Jn=e=>(Gn.add(e),()=>{Gn.delete(e)}),Is=()=>I.getState().downloads,he=(e,t)=>{let n=!!D(e),o=I.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};I.setState(l=>({downloads:{...l.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?Be({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Be({type:"progress",app_id:e,progress:i.progress,version:i.version})},cn=(e,t)=>{var n;(n=it[e])==null||n.forEach(o=>o(t)),delete it[e]},Fs=()=>I.getState().pause_reasons.length>0,Je=e=>{var s;if(O)return;let t=e?te.indexOf(e):Fs()?-1:te.findIndex(c=>!xe.has(c));if(t<0||t>=te.length)return;let[n]=te.splice(t,1),o=I.getState().catalog[n];if(!o){cn(n,D(n)),Je();return}let r=Date.now();Ve[n]=((s=Ve[n])!=null?s:0)+1,he(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,l=jn(o,{onProgress:c=>{let a=Math.floor(c*100);a!==i&&(i=a,he(n,{progress:a/100,version:o.version}))}});O={app_id:n,handle:l,forced:!!e},ve("start",n,o.version,e?"(forced)":""),l.promise.then(c=>{ve("installed",n,o.version,`${Date.now()-r}ms`),he(n,{status:"installed",progress:1,version:o.version}),cn(n,c)}).catch(c=>{var p;if(c instanceof pt){if(ln.has(n))return;ve("paused",n),Ve[n]-=1,te.unshift(n),he(n,{status:xe.has(n)?"paused":"queued",progress:0,version:o.version});return}let a=String((p=c==null?void 0:c.message)!=null?p:c);if(console.warn("[miniapp-queue] failed",n,a),Ve[n]<Ps){he(n,{status:"queued",progress:0,version:o.version,error:a}),setTimeout(()=>{var d;te.includes(n)||(O==null?void 0:O.app_id)===n||(te.push(n),Je((d=it[n])!=null&&d.length?n:void 0))},ks);return}he(n,{status:"failed",progress:0,version:o.version,error:a}),cn(n,D(n))}).finally(()=>{O=null;let c=te.find(a=>{var p;return(p=it[a])==null?void 0:p.length});Je(c)})},un=(e,{front:t=!1}={})=>{if((O==null?void 0:O.app_id)===e)return;let n=te.indexOf(e);if(n>=0){if(!t)return;te.splice(n,1)}t?te.unshift(e):te.push(e)},Ls=async e=>{let{host_id:t,client_token:n}=R(),o=new AbortController,r=setTimeout(()=>o.abort(),Ts);try{let i=`${Mt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,l=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!l.ok)throw new Error(`host list ${e} ${l.status}`);return(await l.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},Ot=null,Kn=()=>(Ot!=null||(Ot=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(Ls)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(I.getState().catalog).filter(c=>!o[c]);R().storage.setString(vr,JSON.stringify(o)),I.setState({catalog:o}),await Promise.all(r.map(c=>Er(c,{by_user:!1}))),r.forEach(c=>Ke.delete(c));let i=Object.keys(o).filter(c=>!Ke.has(c)),l=[],s={};for(let c of i.map(a=>o[a])){if(await $n(c)){he(c.app_id,{status:"installed",progress:1,version:c.version});continue}let a=D(c.app_id);if(xr(c.app_id)&&!pn.has(c.app_id)&&a&&await Ue(a)){he(c.app_id,{status:"installed",progress:1,version:a.version}),s[c.app_id]={app_id:c.app_id,current_version:a.version,next_version:c.version};continue}l.push(c)}return I.setState({updates:s}),l.forEach(c=>{Ve[c.app_id]=0,he(c.app_id,{status:xe.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),un(c.app_id)}),ve("catalog",i.length,"apps, outdated",l.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),Be({type:"sync_complete",app_ids:i,removed:r}),Object.values(s).forEach(c=>Be({type:"update_available",...c})),Je(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),Be({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{Ot=null}})()),Ot),Er=async(e,{by_user:t})=>{var r,i,l,s;if(t&&Ke.add(e),ln.has(e))return;ln.add(e),xe.delete(e);let n=te.indexOf(e);n>=0&&te.splice(n,1),(O==null?void 0:O.app_id)===e&&O.handle.cancel();let o=(s=(l=(r=I.getState().downloads[e])==null?void 0:r.version)!=null?l:(i=D(e))==null?void 0:i.version)!=null?s:"";he(e,{status:"uninstalling",progress:0,version:o}),await wr(e),an(e),I.setState(c=>{let a={...c.downloads};return delete a[e],{downloads:a}}),delete Ve[e],ln.delete(e),cn(e,null),ve("uninstalled",e,t?"(user)":"(not in list)"),Be({type:"uninstalled",app_id:e})},Ds=e=>Er(e,{by_user:!0}),Ns=e=>{let t=Ft(e);return t?(Ke.delete(e),(O==null?void 0:O.app_id)===e||te.includes(e)||(Ve[e]=0,he(e,{status:xe.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),un(e),Je(),ve("restore",e)),!0):!1},Us=e=>{if(xe.has(e))return;if(xe.add(e),ve("pause app",e),(O==null?void 0:O.app_id)===e&&!O.forced){O.handle.cancel();return}let t=I.getState().downloads[e];te.includes(e)&&t&&he(e,{status:"paused",progress:0,version:t.version})},Vs=e=>{if(!xe.delete(e))return;ve("resume app",e);let t=I.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!te.includes(e)&&Ft(e)&&(Ve[e]=0,un(e)),te.includes(e)&&t&&he(e,{status:"queued",progress:0,version:t.version}),Je()},Bs=e=>{let{pause_reasons:t}=I.getState();t.includes(e)||(I.setState({pause_reasons:[...t,e]}),ve("pause",e),t.length===0&&Be({type:"pause_change",paused:!0,reasons:[e]}),O&&!O.forced&&O.handle.cancel())},Hs=e=>{let{pause_reasons:t}=I.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);I.setState({pause_reasons:n}),ve("resume",e),n.length===0&&Be({type:"pause_change",paused:!1,reasons:n}),Je()},Tr=e=>I.getState().updates[e],Yn=async e=>{var n,o;let t=Tr(e);pn.add(e);try{let r=await dn(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=Ft(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(I.setState(l=>{var c;let s={...l.updates};return delete s[e],{updates:s,apply_ticks:{...l.apply_ticks,[e]:((c=l.apply_ticks[e])!=null?c:0)+1}}}),ve("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),Be({type:"update_applied",app_id:e,version:r.version}),!0)}finally{pn.delete(e)}},qs=()=>Object.values(I.getState().catalog).map(e=>({...e,installed:!!D(e.app_id),removed_by_user:Ke.has(e.app_id)})),Ft=e=>I.getState().catalog[e],dn=async e=>{let t=Ft(e);if(!t)return;if(xe.delete(e),Ke.delete(e),await $n(t))return D(e);let n=D(e);if(xr(e)&&!pn.has(e)&&n&&await Ue(n))return n;let o=new Promise(r=>{var i;((i=it[e])!=null?i:it[e]=[]).push(r)});return(O==null?void 0:O.app_id)===e?O.forced=!0:(Ve[e]=0,un(e,{front:!0}),O&&!O.forced?O.handle.cancel():Je(e)),o};var kr=e=>`changelog_seen:${e}`,Ws=10*1e3,Xn=e=>R().storage.getString(kr(e))||null,Nt=(e,t=(n=>(n=D(e))==null?void 0:n.version)())=>{t&&R().storage.setString(kr(e),t)},Qn=e=>{var o;let t=(o=D(e))==null?void 0:o.version;if(!t)return null;let n=Xn(e);return n?Wn(t,n)>0?{app_id:e,from:n,to:t}:null:(Nt(e,t),null)},js=e=>{var t,n,o;return(o=(n=(t=I.getState().catalog[e])==null?void 0:t.channel)!=null?n:R().channels[0])!=null?o:"production"},hn=async(e,{from:t,to:n,channel:o=js(e)}={})=>{let{client_token:r}=R(),i=new URLSearchParams({channel:o});t&&i.set("from",t),n&&i.set("to",n);let l=new AbortController,s=setTimeout(()=>l.abort(),Ws);try{let c=await fetch(`${Mt}/api/miniapps/${encodeURIComponent(e)}/changelog?${i}`,{headers:{Authorization:`Bearer ${r}`},signal:l.signal});if(!c.ok)throw new Error(`changelog ${e} ${c.status}`);return(await c.json()).versions}finally{clearTimeout(s)}},Zn=(e,{from:t,to:n,enabled:o=!0}={})=>{let[r,i]=gn([]),[l,s]=gn(!1),[c,a]=gn(),[p,d]=gn(0),m=zs(()=>d(u=>u+1),[]);return $s(()=>{if(!e||!o)return;let u=!0;return s(!0),a(void 0),hn(e,{from:t,to:n}).then(A=>{u&&i(A)}).catch(A=>{var S;u&&a(String((A==null?void 0:A.name)==="AbortError"?"timeout":(S=A==null?void 0:A.message)!=null?S:A))}).finally(()=>{u&&s(!1)}),()=>{u=!1}},[e,t,n,o,p]),{versions:r,loading:l,error:c,reload:m}},He=Re({request:null,history:null}),Lt=!1,eo=e=>{var t,n;return(n=(t=I.getState().catalog[e])==null?void 0:t.name)!=null?n:e},Gs=async e=>{var i,l,s,c;let t=(i=D(e))==null?void 0:i.version;if(!t)return null;let n=Qn(e),o=await hn(e,n?{from:n.from,to:n.to}:{to:t}),r=n&&o.length?o:o.slice(0,1);return r.length?{app_id:e,name:eo(e),from:(c=(s=n==null?void 0:n.from)!=null?s:(l=o[1])==null?void 0:l.version)!=null?c:r[0].version,to:t,versions:r}:null},Dt=async(e,{name:t,force:n=!1}={})=>{if(He.getState().request||Lt)return!1;if(n){Lt=!0;try{let r=await Gs(e);return r&&He.setState({request:{...r,name:t!=null?t:r.name}}),!!r}catch(r){return ce("changelog failed",e,r),!1}finally{Lt=!1}}let o=Qn(e);if(!o)return!1;Lt=!0;try{let r=await hn(e,{from:o.from,to:o.to});return r.length?(He.setState({request:{...o,name:t!=null?t:eo(e),versions:r}}),!0):(Nt(e,o.to),!1)}catch(r){return ce("changelog failed",e,r),!1}finally{Lt=!1}},to=()=>{let{request:e}=He.getState();e&&Nt(e.app_id,e.to),He.setState({request:null})},no=()=>B(He,e=>e.request),oo=(e,{name:t}={})=>{He.setState({history:{app_id:e,name:t!=null?t:eo(e)}})},ro=()=>He.setState({history:null}),io=()=>B(He,e=>e.history),Pr=!1;nn(()=>{if(Pr)return;Pr=!0;let e=()=>R().changelog!==!1;Jn(n=>{n.type==="status_change"&&n.state.status==="installed"&&!Xn(n.app_id)&&Nt(n.app_id,n.state.version),n.type==="update_applied"&&e()&&Dt(n.app_id)});let t=re.getState().active_key;re.subscribe(()=>{let{active_key:n,instances:o}=re.getState();if(n===t)return;t=n;let r=n?o[n]:void 0;r&&e()&&Dt(r.app.app_id,{name:r.app.name})})});import{Alert as Ks,Linking as Ys,Platform as Ut,StatusBar as Xs}from"react-native";import{AppState as Rr,Platform as ao}from"react-native";var be,ut=new Map,Or=(e,t)=>{var o;let n=(o=ut.get(e))!=null?o:new Set;n.add(t),ut.set(e,n)},Ir=(e,t)=>{let n=ut.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&ut.delete(e))},lo=new Map,Fr=(e,t)=>{lo.set(e,t)},Lr=e=>lo.get(e),Dr=()=>ao.OS==="android"&&!!(be!=null&&be.requesting_permission),Js=1500,fn=()=>new Promise(e=>{if(ao.OS!=="android"||Rr.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,Js),o=Rr.addEventListener("change",r=>{r==="active"&&t()})}),so=e=>{var t;if(be===e&&(be=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&ao.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Nr=async(e,t,n,o=()=>!0)=>{var i,l,s,c,a;if(be)throw new f("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};be=r;try{let p;try{p=await import("expo-speech-recognition")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=p.ExpoSpeechRecognitionModule;if(r.native=d,r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let m;try{m=await d.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await fn(),r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!m.granted)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new f("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(d.addListener("result",u=>{var A,S;be!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(S=(A=u.results[0])==null?void 0:A.transcript)!=null?S:""})}),d.addListener("error",u=>{be===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),d.addListener("end",()=>{be===r&&(so(r),n("speech.end"))})),r.started=!0,d.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(l=t.continuous)!=null?l:!0,interimResults:(s=t.interimResults)!=null?s:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(a=t.requiresOnDeviceRecognition)!=null?a:!1,iosCategory:{category:p.AVAudioSessionCategory.playAndRecord,categoryOptions:[p.AVAudioSessionCategoryOptions.defaultToSpeaker,p.AVAudioSessionCategoryOptions.allowBluetooth],mode:p.AVAudioSessionMode.measurement}})}catch(p){throw so(r),p}},Ur=e=>{let t=be;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},qe=e=>{lo.delete(e);let t=ut.get(e);ut.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=be;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{so(n)}};var Vr={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},ae={...Vr,all:Object.values(Vr)},Vt={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},po={result:"scanner.result",end:"scanner.end"},dt={user:"user",web:"web",closed:"closed",error:"error"},_e={top:"top",full:"full"},Ye={once:"once",continuous:"continuous"},Qs=1500,Br=6e4,q,Z=Re({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),qr=()=>Ut.OS==="android"&&!!(q!=null&&q.requesting_permission),uo=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},l={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(s=>ae.all.includes(s)))throw new f("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");l.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Br)throw new f("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Br}`);l.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new f("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");l.hint=o}if(r!==void 0){if(!Object.values(_e).includes(r))throw new f("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");l.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new f("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");l.absolute=i}return l},go=e=>q!==e?!1:(q=void 0,Z.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Zs=()=>Ks.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{Ys.openSettings().catch(()=>{})}}]),zr=async(e,t)=>{if(q)throw new f("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");q=e;let n=()=>{if(e.cancelled||!t())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let l=Ut.OS==="ios"&&r==="denied";e.requesting_permission=!0;let s;try{s=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await fn(),n(),s!=="granted")throw l&&Zs(),new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(l=>l.position==="back"))throw new f("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await Bt();n(),Z.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw go(e),o}},mn;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{mn=e==null?void 0:e.insets}).catch(()=>{});var gt=()=>{var e;return mn!=null?mn:{top:Ut.OS==="ios"?54:(e=Xs.currentHeight)!=null?e:0,bottom:Ut.OS==="ios"?34:48}},Bt=async()=>{if(Ut.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},$r=(e,t,n)=>{var o,r,i,l;return{owner:e,mode:t,types:(o=n.types)!=null?o:ae.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Qs,hint:n.hint,layout:t===Ye.once?_e.full:(i=n.layout)!=null?i:_e.top,absolute:t!==Ye.once&&((l=n.layout)!=null?l:_e.top)===_e.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},Wr=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let l=$r(e,Ye.once,t);l.onHit=o,l.resolve=r,l.reject=i,zr(l,n).catch(i)}),jr=(e,t,n,o=()=>!0,r)=>{let i=$r(e,Ye.continuous,t);return i.emit=n,i.onHit=r,zr(i,o)},yn=(e,t,n)=>{var o,r;if(!Z.getState().active){e.cancelled=!0;return}if(go(e)){if(e.mode===Ye.once){(o=e.reject)==null||o.call(e,t===dt.error?new f("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new f("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,po.end,n?{reason:t,message:n}:{reason:t})}},Gr=e=>{(q==null?void 0:q.owner)===e&&yn(q,dt.web)},Xe=e=>{(q==null?void 0:q.owner)===e&&yn(q,dt.closed)},ho=()=>{q&&yn(q,dt.user)},Jr=e=>{q&&yn(q,dt.error,e)},fo=(e,t=Date.now(),n=!1)=>{var r,i,l;let o=q;if(!(!o||!Z.getState().active))for(let{value:s,type:c}of e){if(!s)continue;let a=o.last_seen.get(s);if(o.last_seen.set(s,t),!(!n&&a!==void 0&&t-a<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Ye.once){go(o),(i=o.resolve)==null||i.call(o,{value:s,type:c});return}Z.setState(p=>({last_value:s,hit_tick:p.hit_tick+1,scan_count:p.scan_count+1,notice:null})),(l=o.emit)==null||l.call(o,po.result,{value:s,type:c})}}},ea={1:ae.code128,2:ae.code39,4:ae.code93,8:ae.codabar,16:ae.dataMatrix,32:ae.ean13,64:ae.ean8,128:ae.itf,256:ae.qr,512:ae.upcA,1024:ae.upcE,2048:ae.pdf417,4096:ae.aztec},ta=2500,Hr=2e3,co=e=>{Z.setState({notice:e}),setTimeout(()=>{Z.getState().notice===e&&Z.setState({notice:null})},ta)},Kr=async()=>{var t,n;let e=q;if(!(!e||Z.getState().is_picking)){e.requesting_permission=!0,Z.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:Hr,maxHeight:Hr}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||q!==e)return;if(r.errorCode||!i){co("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:l}=await import("@react-native-ml-kit/barcode-scanning"),s=await l.scan(i);if(q!==e)return;let c=s.map(({value:a,format:p})=>({value:a,code_type:ea[p]})).filter(({code_type:a})=>!a||e.types.includes(a)).map(({value:a,code_type:p})=>({value:a,type:p!=null?p:"unknown"}));if(!c.length){co("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}fo(c,Date.now(),!0)}catch{q===e&&co("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await fn(),e.requesting_permission=!1,q===e&&Z.setState({is_picking:!1})}}};var qt=1,f=class extends Error{constructor(n,o){super(o);this.code=n}},Xr=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===qt&&typeof t.method=="string"?t:null}catch{return null}},zt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Qr=(e,t)=>zt({id:e,result:t}),Zr=(e,t)=>zt({id:e,error:{code:t.code,message:t.message}}),ei=(e,t)=>zt({event:e,data:t}),yo=e=>zt({event:"context",data:e});var ti=()=>`(function () {
1
+ var Mt="https://retion-miniapp-platform.vercel.app",nt=null,Wo=new Set,Ji=e=>{nt=e,Wo.forEach(t=>t())},R=()=>{if(!nt)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return nt},nn=e=>{Wo.add(e),nt&&e()},ce=(...e)=>{nt!=null&&nt.debug&&console.log("[miniapp]",...e)};var Ki=(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(o=>o.map(r=>r.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,o)=>{await t(n,o)},download:({url:n,to_file:o,onProgress:r})=>{let{jobId:i,promise:l}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:s,contentLength:c})=>r==null?void 0:r(s,c)});return{promise:l.then(({statusCode:s})=>({status:s})),cancel:()=>e.stopDownload(i)}}}),Yi=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Ro,{useCallback as To,useEffect as pe,useMemo as Cn,useRef as Ce,useState as Fe}from"react";import{AppState as Fi,ActivityIndicator as xa,Animated as Co,BackHandler as Ca,Image as Ea,Keyboard as Li,Linking as Ta,Platform as Ui,StyleSheet as Oo,Text as Kt,TouchableOpacity as Pa,View as Po}from"react-native";import ka from"react-native-webview";import{Linking as Kr,Platform as na}from"react-native";var jo=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),on,Nn=()=>(on||(on=import("react-native-biometrics").then(({default:e})=>jo(new e({allowDeviceCredentials:!1}))).catch(e=>{throw on=void 0,new f("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),on);import{PermissionsAndroid as ot,Platform as Xi}from"react-native";var Go=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new f("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new f("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,l,s]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<l||c>s))throw new f("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${l}\u2013${s} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Jo=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,a)=>{r||(r=!0,clearTimeout(l),c?o(c):n(a))},l=setTimeout(()=>i(new f("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),s=()=>r?!1:t()?!0:(i(new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!s())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(s()){if(Xi.OS==="android"){let a=ot.PERMISSIONS.ACCESS_FINE_LOCATION,p=ot.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await ot.check(a);if(!s())return;let m=d||await ot.check(p);if(!s())return;if(!d&&!m){let u=await ot.requestMultiple([a,p]);if(!s())return;if(u[a]!==ot.RESULTS.GRANTED&&u[p]!==ot.RESULTS.GRANTED)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}s()&&c.getCurrentPosition(a=>{s()&&i(void 0,a)},a=>{var d;if(!s())return;let p=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[a.code])!=null?d:"LOCATION_ERROR";i(new f(p,a.message))},e)}})().catch(c=>i(c))});import{Platform as tr}from"react-native";var Un=20,Ko=20,nr=/^[a-z][a-z0-9_-]{0,31}$/,Qi=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Zi=["low","medium","high"],Ge=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Q=e=>new f("INVALID_PARAMS",e),Et=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Yo=(e,t)=>{if(e===void 0)return{};if(!Ge(e)||Object.keys(e).length>Ko||Object.values(e).some(n=>typeof n!="string"))throw Q(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Ko} key)`);return e},or=e=>{var n,o,r,i;if(e!==void 0&&!Ge(e))throw Q("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!nr.test(t.source)))throw Q("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(l=>typeof l!="string"||!Qi.test(l))))throw Q("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Et(t.max_count,1,Un))throw Q(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Un}`);if(t.max_size!==void 0&&!Et(t.max_size,1,Number.MAX_SAFE_INTEGER))throw Q("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Et(t.concurrency,1,5))throw Q("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((o=t.accept)!=null?o:[]).map(l=>l.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:es(t.process),target:ts(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},es=e=>{if(e===void 0)return{};if(!Ge(e))throw Q("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Ge(n))throw Q("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Et(n[o],1,1e4))throw Q(`process.image.${o} 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 Q("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(!Ge(n))throw Q("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Et(n.max_duration,1,3600))throw Q("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Zi.includes(n.quality))throw Q("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},ts=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Ge(e))throw Q("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!nr.test(t))throw Q("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Ge(e.params))throw Q("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(o=e.params)!=null?o:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw Q("upload.url ph\u1EA3i l\xE0 https");for(let l of["field_name","url_field"])if(e[l]!==void 0&&(typeof e[l]!="string"||!e[l]))throw Q(`upload.${l} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Yo(e.headers,"upload.headers"),form_data:Yo(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},rr=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},ns=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=rr(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},os=e=>{let t=e.length>0&&e.every(o=>o.startsWith("image/")),n=e.length>0&&e.every(o=>o.startsWith("video/"));return t?"image":n?"video":"mixed"},vt,rs=()=>(vt!=null||(vt=import("react-native-image-picker").catch(e=>{throw vt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),vt),Xo=e=>async({accept:t,max_count:n,process:o})=>{var c,a,p,d,m,u,A,S,P;let r=await rs(),i=os(t),l={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(a=o.image)==null?void 0:a.max_height,quality:(d=(p=o.image)==null?void 0:p.quality)!=null?d:.8,videoQuality:(u=(m=o.video)==null?void 0:m.quality)!=null?u:"medium",durationLimit:(A=o.video)==null?void 0:A.max_duration,assetRepresentationMode:"compatible"},s=e==="camera"?await r.launchCamera({...l,saveToPhotos:!1}):await r.launchImageLibrary({...l,selectionLimit:n});if(s.didCancel)return[];if(s.errorCode){let v=s.errorCode==="permission"?"PERMISSION_DENIED":s.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new f(v,(S=s.errorMessage)!=null?S:s.errorCode)}return((P=s.assets)!=null?P:[]).filter(v=>v.uri).map((v,M)=>{var U,w,V;return{uri:v.uri,name:(U=v.fileName)!=null?U:`file_${M+1}`,mime_type:(w=v.type)!=null?w:"application/octet-stream",size:v.fileSize,width:v.width,height:v.height,duration:v.duration,processed:!((V=v.type)!=null&&V.startsWith("video/"))||tr.OS==="ios"}})},is={"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"},ss={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},as=e=>async({accept:t,max_count:n})=>{var i,l,s,c;let o=t.map(a=>{var p;return(p=is[a])!=null?p:ss[a]}),r=!t.length||o.some(a=>!a||!e.types[a])?e.types.allFiles:[...new Set(o)].flatMap(a=>e.types[a]);try{let p=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,A)=>{var S,P,v;return{uri:u.uri,name:(S=u.name)!=null?S:`file_${A+1}`,mime_type:(P=u.type)!=null?P:"application/octet-stream",size:(v=u.size)!=null?v:void 0}});if(tr.OS!=="android"||!e.keepLocalCopy||!p.some(u=>u.uri.startsWith("content://")))return p;let d=await e.keepLocalCopy({files:p.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),m=new Map(d.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return p.map(u=>{var A;return{...u,uri:(A=m.get(u.uri))!=null?A:u.uri}})}catch(a){let p=a==null?void 0:a.code;if(p===((l=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?l:"OPERATION_CANCELED"))return[];throw p===((c=(s=e.errorCodes)==null?void 0:s.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new f("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):a}},xt,ls=async e=>(xt!=null||(xt=import("@react-native-documents/picker").then(t=>as(t)).catch(t=>{throw xt=void 0,new f("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await xt)(e)),ir={library:Xo("library"),camera:Xo("camera"),document:ls},Qo={type:"image",label:"\u1EA2nh",accept:["image/*"]},Zo={type:"video",label:"Video",accept:["video/*"]},er={library:[Qo,Zo],camera:[Qo,Zo],document:[{type:"any",label:"M\u1ECDi file",accept:[]},{type:"pdf",label:"PDF",accept:["application/pdf"]},{type:"word",label:"Word",accept:[".doc",".docx"]},{type:"excel",label:"Excel",accept:[".xls",".xlsx"]},{type:"powerpoint",label:"PowerPoint",accept:[".ppt",".pptx"]}]},Ct,sr=()=>(Ct!=null||(Ct=import("react-native-compressor").catch(()=>(Ct=void 0,null))),Ct),ar=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},cs=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),ps={low:640,medium:1280,high:1920},us=async(e,{image:t})=>{var o;if(!t||!cs.has(e.mime_type.toLowerCase()))return e;let n=await sr();if(!n)return e;try{let r=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(o=t.quality)!=null?o:.8,output:"jpg"});return{...e,uri:r,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await ar(n,r,e.size),processed:!0}}catch{return e}},ds=async(e,{video:t})=>{var o;let n=await sr();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:ps[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await ar(n,r,e.size),processed:!0}}catch{return e}},gs={image:us,video:ds},hs=(e,t)=>t.split(".").reduce((n,o)=>Ge(n)?n[o]:void 0,e),lr=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new f("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let l=t;if(o.aborted){i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let s=new XMLHttpRequest,c=new FormData;Object.entries(l.form_data).forEach(([d,m])=>c.append(d,m)),c.append(l.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let a=()=>s.abort();o.addEventListener("abort",a);let p=d=>{o.removeEventListener("abort",a),d()};s.open("POST",l.url),Object.entries(l.headers).forEach(([d,m])=>s.setRequestHeader(d,m)),s.upload.onprogress=d=>n(d.loaded,d.total||e.size||0),s.onload=()=>p(()=>{let d=s.responseText;try{d=JSON.parse(s.responseText)}catch{}if(s.status<200||s.status>=300){i(new f("UPLOAD_FAILED",`HTTP ${s.status}`));return}let m=hs(d,l.url_field);if(typeof m!="string"||!m){i(new f("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${l.url_field}"`));return}r({url:m,response:d})}),s.onerror=()=>p(()=>i(new f("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),s.onabort=()=>p(()=>i(new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),s.send(c)}),cr=e=>{var o,r;let t={...ir};for(let[i,l]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))l?t[i]=l:delete t[i];let n={url:lr};for(let[i,l]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&l&&(n[i]=l);return{sources:t,targets:n}},pr=e=>{let{sources:t,targets:n}=cr(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===ir[i]&&er[i]).map(i=>[i,er[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Un}},sn=new Map,ur=(e,t)=>`${e}:${t}`,fs=0,dr=(e,t)=>{var n;typeof t=="string"&&((n=sn.get(ur(e,t)))==null||n.abort())},rt=e=>{for(let[t,n]of sn)t.startsWith(`${e}:`)&&n.abort()},rn=()=>new f("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),ms=(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)}},gr=async(e,t)=>{var c;let{sources:n,targets:o}=cr(t.config),r=n[e.source];if(!r)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let i=o[e.target.target];if(!i)throw new f("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let l=new AbortController,s=ur(t.instance_id,(c=t.task_id)!=null?c:`auto-${++fs}`);sn.set(s,l);try{return await ys(e,t,r,i,l.signal)}finally{sn.delete(s)}},ys=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:l,exclusivePick:s=d=>d()},c,a,p)=>{var H,h,T;let d={app_id:n!=null?n:"",instance_id:t,context:{...(H=o==null?void 0:o())!=null?H:{}}},m=(await s(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:d}))).slice(0,e.max_count);if(p.aborted)throw rn();if(!m.length)throw new f("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],A=m.filter(E=>ns(E,e.accept)?!0:(u.push({name:E.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${E.mime_type||rr(E.name)}`}),!1)),S=A.map(()=>0),P=A.map(E=>{var b;return(b=E.size)!=null?b:0}),v=0,M=0,U=(E=!1)=>{if(!l||!r)return;let b=Date.now();if(!E&&b-M<200)return;M=b;let ue=P.reduce((F,se)=>F+se,0),j=S.reduce((F,se)=>F+se,0);l("upload.progress",{task_id:r,loaded:j,total:ue,percent:ue?Math.min(100,Math.round(j/ue*100)):0,done_count:v,count:A.length})},w=[],V=0,z=async()=>{var E,b,ue;for(;V<A.length;){let j=V++,F=A[j];try{if(p.aborted)throw rn();let se=F.mime_type.startsWith("image/")?"image":F.mime_type.startsWith("video/")?"video":void 0,Pe=se&&!F.processed?(b=(E=i==null?void 0:i.processors)==null?void 0:E[se])!=null?b:gs[se]:void 0;if(Pe&&(F=await Pe(F,e.process),P[j]=(ue=F.size)!=null?ue:P[j],p.aborted))throw rn();if(e.max_size&&F.size&&F.size>e.max_size)throw new f("FILE_TOO_LARGE",`File ${F.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let ze=(de,Ze)=>{S[j]=de,Ze&&(P[j]=Ze),U()},Y=await a({file:F,target:e.target,onProgress:ze,signal:p,caller:d});if(typeof(Y==null?void 0:Y.url)!="string"||!Y.url)throw new f("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ke,...G}=Y;w[j]={url:ke,name:F.name,mime_type:F.mime_type,size:F.size,width:F.width,height:F.height,duration:F.duration,...Object.keys(G).length?{response:"response"in G?G.response:G}:{}},S[j]=P[j]}catch(se){u.push(ms(A[j].name,se))}finally{v++,U(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,A.length)},z)),p.aborted)throw rn();let le=w.filter(E=>!!E);if(!le.length){let E=u[0];throw new f((h=E==null?void 0:E.code)!=null?h:"UPLOAD_FAILED",(T=E==null?void 0:E.message)!=null?T:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:le,failed:u}};import{useRef as _s,useSyncExternalStore as bs}from"react";var Re=e=>{let t=e,n=new Set;return{getState:()=>t,setState:o=>{let r=typeof o=="function"?o(t):o;t={...t,...r},n.forEach(i=>i())},subscribe:o=>(n.add(o),()=>{n.delete(o)})}},B=(e,t,n=Object.is)=>{let o=_s(null),r=()=>{let i=e.getState(),l=o.current;if(l&&l.state===i&&l.selector===t)return l.value;let s=t(i),c=l&&n(l.value,s)?l.value:s;return o.current={state:i,selector:t,value:c},c};return bs(e.subscribe,r)};var Me={info:"info",success:"success",error:"error"},ws=200,hr={info:2e3,success:2e3,error:3e3},Tt=Re({message:"",type:Me.info,tick:0}),fr=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,ws);return o?{message:o,type:Object.values(Me).includes(n)?n:Me.info}:null},mr=(e,t=Me.info)=>{Tt.setState(n=>({message:e,type:t,tick:n.tick+1}))};import{useCallback as zs,useEffect as $s,useState as gn}from"react";var Bn=e=>`bundle:${e}`,Hn=()=>`${R().file_system.document_dir}/miniapps`,qn=Hn,zn=(e,t,n="index.html",o=!1,r=[])=>{let i=`${qn()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Vn=e=>{var t;R().storage.setString(Bn(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},As=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,D=e=>{let t=R().storage.getString(Bn(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return zn(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Ue=e=>R().file_system.exists(e.entry_uri.replace("file://","")),$n=async e=>{let t=D(e.app_id);return(t==null?void 0:t.version)===e.version&&await Ue(t)},_r=async(e,t)=>{let n=R().file_system,o=`${qn()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},br=async e=>{var t;await((t=kt[e])==null?void 0:t.catch(()=>{})),R().storage.setString(Bn(e),""),await R().file_system.remove(`${qn()}/${e}`).catch(()=>{})},pt=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},kt={},wr=(e,t)=>{var i;let o=((i=kt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return kt[e]=r,r.then(()=>{kt[e]===r&&delete kt[e]}),o},Wn=(e,t)=>{var r,i;let n=e.split(".").map(l=>parseInt(l,10)||0),o=t.split(".").map(l=>parseInt(l,10)||0);for(let l=0;l<Math.max(n.length,o.length);l++){let s=((r=n[l])!=null?r:0)-((i=o[l])!=null?i:0);if(s)return s}return 0},Ss=({manifest:e,zip_path:t})=>wr(e.app_id,async()=>{var i;let n=R().file_system,o=D(e.app_id);if(o&&Wn(o.version,e.version)>=0&&await Ue(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=zn(e.app_id,e.version,e.entry,!!e.context_update,(i=e.permissions)!=null?i:[]);return await n.remove(r.dir).catch(()=>{}),await n.mkdir(r.dir),await n.unzip(t,r.dir),Vn(e),ce("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),_r(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),jn=(e,{base_url:t,onProgress:n}={})=>{let o=R().file_system,r=null,i=!1,l=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,s=()=>{if(i)throw new pt},c=async()=>{var d;s();let a=D(e.app_id);if((a==null?void 0:a.version)===e.version&&await o.exists(a.dir))return Vn(e),D(e.app_id);s();let p=o.download({url:t?As(t,e.bundle_url):e.bundle_url,to_file:l,onProgress:(m,u)=>{var S;let A=u>0?u:(S=e.size)!=null?S:0;A>0&&(n==null||n(Math.min(1,m/A)))}});r=p;try{let{status:m}=await p.promise;if(s(),m!==200)throw new Error(`bundle ${m}`);if(e.sha256)if(o.sha256){if(await o.sha256(l)!==e.sha256)throw new Error("sha256 mismatch")}else ce("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);s();let u=zn(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(l,u.dir),Vn(e),_r(e.app_id,[e.version,a==null?void 0:a.version].filter(Boolean)),u}catch(m){throw i?new pt:m}finally{r=null,o.remove(l).catch(()=>{})}};return{promise:wr(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},Pt={},Ms=__DEV__?0:60*1e3,yr={},Ar=(e,t)=>{var o,r;let n=D(e);return n&&Date.now()-((o=yr[t])!=null?o:0)<Ms?Promise.resolve(n):((r=Pt[e])!=null||(Pt[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let l=await i.json(),s=await jn(l,{base_url:t}).promise;return yr[t]=Date.now(),s})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),D(e))).finally(()=>{Pt[e]=void 0})),Pt[e])};var re=Re({active_key:null,instances:{}}),Sr=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var s;let l=(s=R().keep_alive)==null?void 0:s.max_webviews;re.setState(c=>{let a=t!=null?t:e.app_id,p={...c.instances,[a]:{key:a,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},d=Object.keys(p);return l&&l>0&&d.length>l&&d.filter(m=>m!==a).sort((m,u)=>p[m].last_used_at-p[u].last_used_at).slice(0,d.length-l).forEach(m=>{delete p[m]}),i?{active_key:a,instances:p}:{instances:p}})},vs=e=>Sr(e,!0),xs=e=>Sr(e,!1),Rt=()=>re.setState({active_key:null}),an=e=>{re.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Mr="catalog",Cs="paused_apps",Es="removed_apps",Ts=10*1e3,Ps=2,ks=3e3,Rs=()=>{var e;try{return JSON.parse((e=R().storage.getString(Mr))!=null?e:"{}")}catch{return{}}},I=Re({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),vr=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},pn=new Set,xr=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:o=>t.has(o),values:()=>[...t],add:o=>t.has(o)?!1:(t.add(o),n(),!0),delete:o=>t.delete(o)?(n(),!0):!1,load:()=>{var o;t.clear();try{let r=JSON.parse((o=R().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},xe=xr(Cs),Ke=xr(Es);nn(()=>{xe.load(),Ke.load();let e=Rs(),t={};Object.keys(e).filter(n=>!Ke.has(n)).forEach(n=>{let o=D(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:xe.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),I.setState({catalog:e,downloads:t})});var It=e=>B(I,t=>e?t.downloads[e]:void 0),Os=()=>B(I,e=>e.pause_reasons.length>0),ve=(...e)=>ce("queue",...e),te=[],Ve={},O=null,ln=new Set,it={},Gn=new Set,Be=e=>{Gn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Jn=e=>(Gn.add(e),()=>{Gn.delete(e)}),Is=()=>I.getState().downloads,he=(e,t)=>{let n=!!D(e),o=I.getState().downloads[e],r=t.status==="downloading"&&n?"updating":t.status,i={...o!=null?o:{status:"queued",progress:0},...t,...r?{status:r}:{},has_local:n};I.setState(l=>({downloads:{...l.downloads,[e]:i}})),(o==null?void 0:o.status)!==i.status||(o==null?void 0:o.version)!==i.version||(o==null?void 0:o.has_local)!==i.has_local?Be({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Be({type:"progress",app_id:e,progress:i.progress,version:i.version})},cn=(e,t)=>{var n;(n=it[e])==null||n.forEach(o=>o(t)),delete it[e]},Fs=()=>I.getState().pause_reasons.length>0,Je=e=>{var s;if(O)return;let t=e?te.indexOf(e):Fs()?-1:te.findIndex(c=>!xe.has(c));if(t<0||t>=te.length)return;let[n]=te.splice(t,1),o=I.getState().catalog[n];if(!o){cn(n,D(n)),Je();return}let r=Date.now();Ve[n]=((s=Ve[n])!=null?s:0)+1,he(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,l=jn(o,{onProgress:c=>{let a=Math.floor(c*100);a!==i&&(i=a,he(n,{progress:a/100,version:o.version}))}});O={app_id:n,handle:l,forced:!!e},ve("start",n,o.version,e?"(forced)":""),l.promise.then(c=>{ve("installed",n,o.version,`${Date.now()-r}ms`),he(n,{status:"installed",progress:1,version:o.version}),cn(n,c)}).catch(c=>{var p;if(c instanceof pt){if(ln.has(n))return;ve("paused",n),Ve[n]-=1,te.unshift(n),he(n,{status:xe.has(n)?"paused":"queued",progress:0,version:o.version});return}let a=String((p=c==null?void 0:c.message)!=null?p:c);if(console.warn("[miniapp-queue] failed",n,a),Ve[n]<Ps){he(n,{status:"queued",progress:0,version:o.version,error:a}),setTimeout(()=>{var d;te.includes(n)||(O==null?void 0:O.app_id)===n||(te.push(n),Je((d=it[n])!=null&&d.length?n:void 0))},ks);return}he(n,{status:"failed",progress:0,version:o.version,error:a}),cn(n,D(n))}).finally(()=>{O=null;let c=te.find(a=>{var p;return(p=it[a])==null?void 0:p.length});Je(c)})},un=(e,{front:t=!1}={})=>{if((O==null?void 0:O.app_id)===e)return;let n=te.indexOf(e);if(n>=0){if(!t)return;te.splice(n,1)}t?te.unshift(e):te.push(e)},Ls=async e=>{let{host_id:t,client_token:n}=R(),o=new AbortController,r=setTimeout(()=>o.abort(),Ts);try{let i=`${Mt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,l=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!l.ok)throw new Error(`host list ${e} ${l.status}`);return(await l.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},Ot=null,Kn=()=>(Ot!=null||(Ot=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(Ls)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(I.getState().catalog).filter(c=>!o[c]);R().storage.setString(Mr,JSON.stringify(o)),I.setState({catalog:o}),await Promise.all(r.map(c=>Cr(c,{by_user:!1}))),r.forEach(c=>Ke.delete(c));let i=Object.keys(o).filter(c=>!Ke.has(c)),l=[],s={};for(let c of i.map(a=>o[a])){if(await $n(c)){he(c.app_id,{status:"installed",progress:1,version:c.version});continue}let a=D(c.app_id);if(vr(c.app_id)&&!pn.has(c.app_id)&&a&&await Ue(a)){he(c.app_id,{status:"installed",progress:1,version:a.version}),s[c.app_id]={app_id:c.app_id,current_version:a.version,next_version:c.version};continue}l.push(c)}return I.setState({updates:s}),l.forEach(c=>{Ve[c.app_id]=0,he(c.app_id,{status:xe.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),un(c.app_id)}),ve("catalog",i.length,"apps, outdated",l.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),Be({type:"sync_complete",app_ids:i,removed:r}),Object.values(s).forEach(c=>Be({type:"update_available",...c})),Je(),{ok:!0,app_ids:i,removed:r}}catch(n){let o=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",o),Be({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{Ot=null}})()),Ot),Cr=async(e,{by_user:t})=>{var r,i,l,s;if(t&&Ke.add(e),ln.has(e))return;ln.add(e),xe.delete(e);let n=te.indexOf(e);n>=0&&te.splice(n,1),(O==null?void 0:O.app_id)===e&&O.handle.cancel();let o=(s=(l=(r=I.getState().downloads[e])==null?void 0:r.version)!=null?l:(i=D(e))==null?void 0:i.version)!=null?s:"";he(e,{status:"uninstalling",progress:0,version:o}),await br(e),an(e),I.setState(c=>{let a={...c.downloads};return delete a[e],{downloads:a}}),delete Ve[e],ln.delete(e),cn(e,null),ve("uninstalled",e,t?"(user)":"(not in list)"),Be({type:"uninstalled",app_id:e})},Ds=e=>Cr(e,{by_user:!0}),Ns=e=>{let t=Ft(e);return t?(Ke.delete(e),(O==null?void 0:O.app_id)===e||te.includes(e)||(Ve[e]=0,he(e,{status:xe.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),un(e),Je(),ve("restore",e)),!0):!1},Us=e=>{if(xe.has(e))return;if(xe.add(e),ve("pause app",e),(O==null?void 0:O.app_id)===e&&!O.forced){O.handle.cancel();return}let t=I.getState().downloads[e];te.includes(e)&&t&&he(e,{status:"paused",progress:0,version:t.version})},Vs=e=>{if(!xe.delete(e))return;ve("resume app",e);let t=I.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!te.includes(e)&&Ft(e)&&(Ve[e]=0,un(e)),te.includes(e)&&t&&he(e,{status:"queued",progress:0,version:t.version}),Je()},Bs=e=>{let{pause_reasons:t}=I.getState();t.includes(e)||(I.setState({pause_reasons:[...t,e]}),ve("pause",e),t.length===0&&Be({type:"pause_change",paused:!0,reasons:[e]}),O&&!O.forced&&O.handle.cancel())},Hs=e=>{let{pause_reasons:t}=I.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);I.setState({pause_reasons:n}),ve("resume",e),n.length===0&&Be({type:"pause_change",paused:!1,reasons:n}),Je()},Er=e=>I.getState().updates[e],Yn=async e=>{var n,o;let t=Er(e);pn.add(e);try{let r=await dn(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=Ft(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(I.setState(l=>{var c;let s={...l.updates};return delete s[e],{updates:s,apply_ticks:{...l.apply_ticks,[e]:((c=l.apply_ticks[e])!=null?c:0)+1}}}),ve("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),Be({type:"update_applied",app_id:e,version:r.version}),!0)}finally{pn.delete(e)}},qs=()=>Object.values(I.getState().catalog).map(e=>({...e,installed:!!D(e.app_id),removed_by_user:Ke.has(e.app_id)})),Ft=e=>I.getState().catalog[e],dn=async e=>{let t=Ft(e);if(!t)return;if(xe.delete(e),Ke.delete(e),await $n(t))return D(e);let n=D(e);if(vr(e)&&!pn.has(e)&&n&&await Ue(n))return n;let o=new Promise(r=>{var i;((i=it[e])!=null?i:it[e]=[]).push(r)});return(O==null?void 0:O.app_id)===e?O.forced=!0:(Ve[e]=0,un(e,{front:!0}),O&&!O.forced?O.handle.cancel():Je(e)),o};var Pr=e=>`changelog_seen:${e}`,Ws=10*1e3,Xn=e=>R().storage.getString(Pr(e))||null,Nt=(e,t=(n=>(n=D(e))==null?void 0:n.version)())=>{t&&R().storage.setString(Pr(e),t)},Qn=e=>{var o;let t=(o=D(e))==null?void 0:o.version;if(!t)return null;let n=Xn(e);return n?Wn(t,n)>0?{app_id:e,from:n,to:t}:null:(Nt(e,t),null)},js=e=>{var t,n,o;return(o=(n=(t=I.getState().catalog[e])==null?void 0:t.channel)!=null?n:R().channels[0])!=null?o:"production"},hn=async(e,{from:t,to:n,channel:o=js(e)}={})=>{let{client_token:r}=R(),i=new URLSearchParams({channel:o});t&&i.set("from",t),n&&i.set("to",n);let l=new AbortController,s=setTimeout(()=>l.abort(),Ws);try{let c=await fetch(`${Mt}/api/miniapps/${encodeURIComponent(e)}/changelog?${i}`,{headers:{Authorization:`Bearer ${r}`},signal:l.signal});if(!c.ok)throw new Error(`changelog ${e} ${c.status}`);return(await c.json()).versions}finally{clearTimeout(s)}},Zn=(e,{from:t,to:n,enabled:o=!0}={})=>{let[r,i]=gn([]),[l,s]=gn(!1),[c,a]=gn(),[p,d]=gn(0),m=zs(()=>d(u=>u+1),[]);return $s(()=>{if(!e||!o)return;let u=!0;return s(!0),a(void 0),hn(e,{from:t,to:n}).then(A=>{u&&i(A)}).catch(A=>{var S;u&&a(String((A==null?void 0:A.name)==="AbortError"?"timeout":(S=A==null?void 0:A.message)!=null?S:A))}).finally(()=>{u&&s(!1)}),()=>{u=!1}},[e,t,n,o,p]),{versions:r,loading:l,error:c,reload:m}},He=Re({request:null,history:null}),Lt=!1,eo=e=>{var t,n;return(n=(t=I.getState().catalog[e])==null?void 0:t.name)!=null?n:e},Gs=async e=>{var i,l,s,c;let t=(i=D(e))==null?void 0:i.version;if(!t)return null;let n=Qn(e),o=await hn(e,n?{from:n.from,to:n.to}:{to:t}),r=n&&o.length?o:o.slice(0,1);return r.length?{app_id:e,name:eo(e),from:(c=(s=n==null?void 0:n.from)!=null?s:(l=o[1])==null?void 0:l.version)!=null?c:r[0].version,to:t,versions:r}:null},Dt=async(e,{name:t,force:n=!1}={})=>{if(He.getState().request||Lt)return!1;if(n){Lt=!0;try{let r=await Gs(e);return r&&He.setState({request:{...r,name:t!=null?t:r.name}}),!!r}catch(r){return ce("changelog failed",e,r),!1}finally{Lt=!1}}let o=Qn(e);if(!o)return!1;Lt=!0;try{let r=await hn(e,{from:o.from,to:o.to});return r.length?(He.setState({request:{...o,name:t!=null?t:eo(e),versions:r}}),!0):(Nt(e,o.to),!1)}catch(r){return ce("changelog failed",e,r),!1}finally{Lt=!1}},to=()=>{let{request:e}=He.getState();e&&Nt(e.app_id,e.to),He.setState({request:null})},no=()=>B(He,e=>e.request),oo=(e,{name:t}={})=>{He.setState({history:{app_id:e,name:t!=null?t:eo(e)}})},ro=()=>He.setState({history:null}),io=()=>B(He,e=>e.history),Tr=!1;nn(()=>{if(Tr)return;Tr=!0;let e=()=>R().changelog!==!1;Jn(n=>{n.type==="status_change"&&n.state.status==="installed"&&!Xn(n.app_id)&&Nt(n.app_id,n.state.version),n.type==="update_applied"&&e()&&Dt(n.app_id)});let t=re.getState().active_key;re.subscribe(()=>{let{active_key:n,instances:o}=re.getState();if(n===t)return;t=n;let r=n?o[n]:void 0;r&&e()&&Dt(r.app.app_id,{name:r.app.name})})});import{Alert as Ks,Linking as Ys,Platform as Ut,StatusBar as Xs}from"react-native";import{AppState as kr,Platform as ao}from"react-native";var _e,ut=new Map,Rr=(e,t)=>{var o;let n=(o=ut.get(e))!=null?o:new Set;n.add(t),ut.set(e,n)},Or=(e,t)=>{let n=ut.get(e);n&&(t?n.delete(t):n.clear(),n.size===0&&ut.delete(e))},lo=new Map,Ir=(e,t)=>{lo.set(e,t)},Fr=e=>lo.get(e),Lr=()=>ao.OS==="android"&&!!(_e!=null&&_e.requesting_permission),Js=1500,fn=()=>new Promise(e=>{if(ao.OS!=="android"||kr.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,Js),o=kr.addEventListener("change",r=>{r==="active"&&t()})}),so=e=>{var t;if(_e===e&&(_e=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&ao.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Dr=async(e,t,n,o=()=>!0)=>{var i,l,s,c,a;if(_e)throw new f("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};_e=r;try{let p;try{p=await import("expo-speech-recognition")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=p.ExpoSpeechRecognitionModule;if(r.native=d,r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let m;try{m=await d.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await fn(),r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!m.granted)throw new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new f("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(r.cancelled||!o())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(d.addListener("result",u=>{var A,S;_e!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(S=(A=u.results[0])==null?void 0:A.transcript)!=null?S:""})}),d.addListener("error",u=>{_e===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),d.addListener("end",()=>{_e===r&&(so(r),n("speech.end"))})),r.started=!0,d.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(l=t.continuous)!=null?l:!0,interimResults:(s=t.interimResults)!=null?s:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(a=t.requiresOnDeviceRecognition)!=null?a:!1,iosCategory:{category:p.AVAudioSessionCategory.playAndRecord,categoryOptions:[p.AVAudioSessionCategoryOptions.defaultToSpeaker,p.AVAudioSessionCategoryOptions.allowBluetooth],mode:p.AVAudioSessionMode.measurement}})}catch(p){throw so(r),p}},Nr=e=>{let t=_e;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},qe=e=>{lo.delete(e);let t=ut.get(e);ut.delete(e),t==null||t.forEach(o=>{var r;try{(r=o.release)==null||r.call(o,e)}catch{}});let n=_e;if(!(!n||n.owner!==e||n.cancelled)&&(n.cancelled=!0,n.started))try{n.native.abort()}catch{so(n)}};var Ur={qr:"qr",ean13:"ean-13",ean8:"ean-8",upcA:"upc-a",upcE:"upc-e",code128:"code-128",code39:"code-39",code93:"code-93",codabar:"codabar",itf:"itf",pdf417:"pdf-417",aztec:"aztec",dataMatrix:"data-matrix"},ae={...Ur,all:Object.values(Ur)},Vt={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},po={result:"scanner.result",end:"scanner.end"},dt={user:"user",web:"web",closed:"closed",error:"error"},be={top:"top",full:"full"},Ye={once:"once",continuous:"continuous"},Qs=1500,Vr=6e4,q,Z=Re({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Hr=()=>Ut.OS==="android"&&!!(q!=null&&q.requesting_permission),uo=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r,absolute:i}=e!=null?e:{},l={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(s=>ae.all.includes(s)))throw new f("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");l.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Vr)throw new f("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Vr}`);l.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new f("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");l.hint=o}if(r!==void 0){if(!Object.values(be).includes(r))throw new f("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");l.layout=r}if(i!==void 0){if(typeof i!="boolean")throw new f("INVALID_PARAMS","absolute ph\u1EA3i l\xE0 boolean");l.absolute=i}return l},go=e=>q!==e?!1:(q=void 0,Z.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Zs=()=>Ks.alert("Ch\u01B0a c\u1EA5p quy\u1EC1n camera","H\xE3y b\u1EADt quy\u1EC1n camera trong C\xE0i \u0111\u1EB7t \u0111\u1EC3 qu\xE9t m\xE3.",[{text:"Hu\u1EF7",style:"cancel"},{text:"M\u1EDF C\xE0i \u0111\u1EB7t",onPress:()=>{Ys.openSettings().catch(()=>{})}}]),qr=async(e,t)=>{if(q)throw new f("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new f("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");q=e;let n=()=>{if(e.cancelled||!t())throw new f("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new f("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=o.Camera.getCameraPermissionStatus();if(r!=="granted"){let l=Ut.OS==="ios"&&r==="denied";e.requesting_permission=!0;let s;try{s=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await fn(),n(),s!=="granted")throw l&&Zs(),new f("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera")}if(!o.Camera.getAvailableCameraDevices().some(l=>l.position==="back"))throw new f("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await Bt();n(),Z.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,absolute:e.absolute,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw go(e),o}},mn;import("react-native-safe-area-context").then(({initialWindowMetrics:e})=>{mn=e==null?void 0:e.insets}).catch(()=>{});var gt=()=>{var e;return mn!=null?mn:{top:Ut.OS==="ios"?54:(e=Xs.currentHeight)!=null?e:0,bottom:Ut.OS==="ios"?34:48}},Bt=async()=>{if(Ut.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},zr=(e,t,n)=>{var o,r,i,l;return{owner:e,mode:t,types:(o=n.types)!=null?o:ae.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Qs,hint:n.hint,layout:t===Ye.once?be.full:(i=n.layout)!=null?i:be.top,absolute:t!==Ye.once&&((l=n.layout)!=null?l:be.top)===be.top&&n.absolute===!0,cancelled:!1,requesting_permission:!1,last_seen:new Map}},$r=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let l=zr(e,Ye.once,t);l.onHit=o,l.resolve=r,l.reject=i,qr(l,n).catch(i)}),Wr=(e,t,n,o=()=>!0,r)=>{let i=zr(e,Ye.continuous,t);return i.emit=n,i.onHit=r,qr(i,o)},yn=(e,t,n)=>{var o,r;if(!Z.getState().active){e.cancelled=!0;return}if(go(e)){if(e.mode===Ye.once){(o=e.reject)==null||o.call(e,t===dt.error?new f("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new f("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,po.end,n?{reason:t,message:n}:{reason:t})}},jr=e=>{(q==null?void 0:q.owner)===e&&yn(q,dt.web)},Xe=e=>{(q==null?void 0:q.owner)===e&&yn(q,dt.closed)},ho=()=>{q&&yn(q,dt.user)},Gr=e=>{q&&yn(q,dt.error,e)},fo=(e,t=Date.now(),n=!1)=>{var r,i,l;let o=q;if(!(!o||!Z.getState().active))for(let{value:s,type:c}of e){if(!s)continue;let a=o.last_seen.get(s);if(o.last_seen.set(s,t),!(!n&&a!==void 0&&t-a<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Ye.once){go(o),(i=o.resolve)==null||i.call(o,{value:s,type:c});return}Z.setState(p=>({last_value:s,hit_tick:p.hit_tick+1,scan_count:p.scan_count+1,notice:null})),(l=o.emit)==null||l.call(o,po.result,{value:s,type:c})}}},ea={1:ae.code128,2:ae.code39,4:ae.code93,8:ae.codabar,16:ae.dataMatrix,32:ae.ean13,64:ae.ean8,128:ae.itf,256:ae.qr,512:ae.upcA,1024:ae.upcE,2048:ae.pdf417,4096:ae.aztec},ta=2500,Br=2e3,co=e=>{Z.setState({notice:e}),setTimeout(()=>{Z.getState().notice===e&&Z.setState({notice:null})},ta)},Jr=async()=>{var t,n;let e=q;if(!(!e||Z.getState().is_picking)){e.requesting_permission=!0,Z.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:Br,maxHeight:Br}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||q!==e)return;if(r.errorCode||!i){co("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:l}=await import("@react-native-ml-kit/barcode-scanning"),s=await l.scan(i);if(q!==e)return;let c=s.map(({value:a,format:p})=>({value:a,code_type:ea[p]})).filter(({code_type:a})=>!a||e.types.includes(a)).map(({value:a,code_type:p})=>({value:a,type:p!=null?p:"unknown"}));if(!c.length){co("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}fo(c,Date.now(),!0)}catch{q===e&&co("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await fn(),e.requesting_permission=!1,q===e&&Z.setState({is_picking:!1})}}};var qt=1,f=class extends Error{constructor(n,o){super(o);this.code=n}},Yr=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===qt&&typeof t.method=="string"?t:null}catch{return null}},zt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Xr=(e,t)=>zt({id:e,result:t}),Qr=(e,t)=>zt({id:e,error:{code:t.code,message:t.message}}),Zr=(e,t)=>zt({event:e,data:t}),yo=e=>zt({event:"context",data:e});var ei=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -19,7 +19,7 @@ var Mt="https://retion-miniapp-platform.vercel.app",nt=null,jo=new Set,Ji=e=>{nt
19
19
  window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
20
20
  // Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
21
21
  post('info', ['[page] ' + location.pathname + location.hash]);
22
- })(); true;`,ni=()=>`(function () {
22
+ })(); true;`,ti=()=>`(function () {
23
23
  function atTop(el) {
24
24
  for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
25
25
  if (n.scrollTop > 0) { return false; }
@@ -38,7 +38,7 @@ var Mt="https://retion-miniapp-platform.vercel.app",nt=null,jo=new Set,Ji=e=>{nt
38
38
  var el = e.target === document ? document.documentElement : e.target;
39
39
  if (el && el.scrollTop > 0) { report(false); }
40
40
  }, { capture: true, passive: true });
41
- })(); true;`,oi=()=>`(function () {
41
+ })(); true;`,ni=()=>`(function () {
42
42
  if (window.__retionSafeAreaFrozen) { return; }
43
43
  window.__retionSafeAreaFrozen = true;
44
44
  var max = {};
@@ -59,14 +59,14 @@ var Mt="https://retion-miniapp-platform.vercel.app",nt=null,jo=new Set,Ji=e=>{nt
59
59
  },
60
60
  });
61
61
  };
62
- })(); true;`,ri=e=>zt({event:e}),ii=(e,t)=>{let n=si(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${yo(e)}`},si=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),ai=(e,t={},{keyboard_mode:n}={})=>{let o=si(t);return`window.__RETION_MINIAPP_HOST__ = ${JSON.stringify(n?{protocol:qt,keyboard_mode:n}:{protocol:qt})};
62
+ })(); true;`,oi=e=>zt({event:e}),ri=(e,t)=>{let n=ii(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${yo(e)}`},ii=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),si=(e,t={},{keyboard_mode:n}={})=>{let o=ii(t);return`window.__RETION_MINIAPP_HOST__ = ${JSON.stringify(n?{protocol:qt,keyboard_mode:n}:{protocol:qt})};
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${o?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(o)} + location.hash); } catch (e) {}`:""}
66
- true;`},li={partner:"partner_token",chatbox:"chatbox_token"},ci=(e,t)=>{let n={...e};for(let o of Object.values(li))t.includes(o)||delete n[o];return n},mo=new Set,Ht=async(e,t)=>{if(mo.has(e))throw new f("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);mo.add(e);try{return await t()}finally{mo.delete(e)}},bo=e=>`(function () {
66
+ true;`},ai={partner:"partner_token",chatbox:"chatbox_token"},li=(e,t)=>{let n={...e};for(let o of Object.values(ai))t.includes(o)||delete n[o];return n},mo=new Set,Ht=async(e,t)=>{if(mo.has(e))throw new f("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);mo.add(e);try{return await t()}finally{mo.delete(e)}},_o=e=>`(function () {
67
67
  window.__retionScannerHeight = ${Math.max(0,Math.round(e))};
68
68
  window.dispatchEvent(new Event('retionscannerheight'));
69
- })(); true;`,pi=()=>`(function () {
69
+ })(); true;`,ci=()=>`(function () {
70
70
  try {
71
71
  var AudioCtx = window.AudioContext || window.webkitAudioContext;
72
72
  if (!AudioCtx) { return; }
@@ -85,5 +85,5 @@ var Mt="https://retion-miniapp-platform.vercel.app",nt=null,jo=new Set,Ji=e=>{nt
85
85
  // iOS c\xF3 th\u1EC3 \u0111\u1EC3 context \u1EDF suspended / interrupted (vd. khi camera m\u1EDF phi\xEAn quay): ch\u1EA1y l\u1EA1i xong m\u1EDBi ph\xE1t.
86
86
  if (ctx.state === 'running') { play(); } else { ctx.resume().then(play).catch(function () {}); }
87
87
  } catch (e) {}
88
- })(); true;`,oa=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),bn=(e,t)=>{if(typeof e!="string"||!e)throw new f("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},ui=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:l,app_id:s,instance_id:c,options:a,emit:p,isActive:d,playBeep:m})=>{var v,M,U,w,V,z,le,H;let u=a==null?void 0:a.handlers,A={app_id:s,instance_id:c,close:l},S=()=>{var h;(h=a==null?void 0:a.haptic)==null||h.call(a,"impactLight"),m==null||m()},P=()=>new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Jo(t);return Ht(e,()=>Ko(h,d))}case"speech.start":{if(!p)throw P();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new f("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let _ of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[_])!==void 0){if(typeof t[_]!="boolean")throw new f("INVALID_PARAMS",`${_} ph\u1EA3i l\xE0 boolean`);h[_]=t[_]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new f("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let T=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",E=T==="voice"?(v=a==null?void 0:a.voice)!=null?v:a==null?void 0:a.speech:void 0;if(Fr(c,E),E){Or(c,E);try{return await E.start({owner:c,app_id:s,mode:T,options:h,emit:p,isActive:d!=null?d:(()=>!0)})}catch(_){throw Ir(c,E),_}}return Nr(c,h,p,d)}case"speech.stop":{let h=Lr(c);return h?h.stop(c):Ur(c)}case Vt.scan:return Wr(c,uo(t),d,S);case Vt.start:{if(!p)throw P();return jr(c,uo(t),p,d,S)}case Vt.stop:return Gr(c);case"uploadFiles":{let{task_id:h,...T}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new f("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return hr(rr(T),{instance_id:c,app_id:s,getContext:r,task_id:h,config:a==null?void 0:a.upload,emit:p,exclusivePick:E=>Ht("uploadFiles.pick",E)})}case"uploadFiles.cancel":gr(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return ur(a==null?void 0:a.upload);case"getBiometricAvailability":return((M=a==null?void 0:a.biometrics)!=null?M:await Nn()).getAvailability();case"authenticateBiometric":{let h=bn(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new f("INVALID_PARAMS","reason must contain 1\u2013200 characters");let T=t==null?void 0:t.cancelButtonText;if(T!==void 0&&(typeof T!="string"||!T.trim()||T.length>80))throw new f("INVALID_PARAMS","Invalid cancelButtonText");return Ht(e,async()=>{var _;return((_=a==null?void 0:a.biometrics)!=null?_:await Nn()).authenticate({reason:h,cancelButtonText:T})})}case"requestPayment":{let h=u==null?void 0:u.requestPayment;if(!h)throw P();let T=t==null?void 0:t.amount;if(typeof T!="number"||!Number.isFinite(T)||T<=0)throw new f("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let E={...t,amount:T,currency:bn(t==null?void 0:t.currency,"currency")};return Ht(e,()=>h(E,A))}case"printImage":{let h=u==null?void 0:u.printImage;if(!h)throw P();let T=bn(t==null?void 0:t.image,"image");await Ht(e,()=>h({image:T},A));return}case"openScreen":if(!(u!=null&&u.openScreen))throw P();await u.openScreen({screen:bn(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},A);return;case"closeApp":l();return;case"openWebview":{let h=String((U=t==null?void 0:t.url)!=null?U:"");if(!/^https?:\/\//i.test(h))throw new f("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(a!=null&&a.openUrl?a.openUrl(h):Yr.openURL(h));return}case"openLink":{let h=String((w=t==null?void 0:t.url)!=null?w:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new f("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(a!=null&&a.openUrl?a.openUrl(h):Yr.openURL(h))}catch(T){throw new f("NOT_SUPPORTED",String((z=(V=T==null?void 0:T.message)!=null?V:T)!=null?z:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=mr(t);if(!h||(d==null?void 0:d())===!1)return;a!=null&&a.showToast?a.showToast(h.message,{type:h.type}):yr(h.message,h.type);return}case"changelog.openPopup":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;return(d==null?void 0:d())===!1?{shown:!1}:{shown:await Dt(h,{force:(t==null?void 0:t.force)===!0})}}case"changelog.openHistory":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;(d==null?void 0:d())!==!1&&oo(h);return}case"haptic":{let h=oa.has(t==null?void 0:t.type)?t.type:"selection";(le=a==null?void 0:a.haptic)==null||le.call(a,h);return}case"getSystemInfo":return{platform:na.OS==="ios"?"ios":"android",appVersion:(H=a==null?void 0:a.app_version)!=null?H:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let _=n().access_token;if(!_)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return _}if(h!=="partner"&&h!=="chatbox")throw new f("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let T=li[h];if(!o().includes(T))throw new f("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${T} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let E=h==="partner"?n().partner_token:n().chatbox_token;if(!E)throw new f("HOST_ERROR",`Kh\xF4ng c\xF3 ${T}`);return E}case"getUserInfo":{let h=n().user;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new f("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var $t=new Map,di=(e,t)=>($t.set(e,t),()=>{$t.get(e)===t&&$t.delete(e)}),_o=(e,t)=>{let n=$t.get(e);return n?n(t):!1},gi=e=>{let t=0;return $t.forEach(n=>{n(e)&&(t+=1)}),t};var Ao=1,ra="retion.ai.agent",mi="retion.ai.message",yi="retion.ai.stopped",bi="retion.ai.payload_meta",_i="retion.ai.payload_meta_result",wn=new Map,wi=null,_n="[miniapp:agent]",hi=e=>{try{let t=JSON.stringify(e);return t&&t.length>300?`${t.slice(0,300)}\u2026`:t}catch{return String(e)}},wo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ia=e=>{try{let t=JSON.parse(e);return wo(t)?t:null}catch{return null}},sa=(e,t)=>_o(e,JSON.stringify({v:Ao,...t})),fi=(e,t)=>{var r;let n=(r=wn.get(e))!=null?r:"",o=gi(JSON.stringify({v:Ao,app_id:n,agent_id:e,...t}));return console.log(_n,`${String(t.type)} \u2192 ${o} WebView`,`app_id=${n||"(ch\u01B0a bi\u1EBFt)"}`,`agent_id=${e||"(tr\u1ED1ng)"}`),o},Ai=(e,t,n)=>{let o=ia(e);if(!o)return!1;if(o.type===ra){let a=typeof o.agent_id=="string"?o.agent_id:"",p=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id;return a&&(wn.get(a)!==p&&console.log(_n,"ghi nh\u1EADn agent",a,"\u2192 app",p),wn.set(a,p),wi=a),!1}if(o.type!==bi)return!1;let r=typeof o.request_id=="string"?o.request_id:"",i=a=>{console.log(_n,"payload_meta_result \u2192",t.instance_id,r,hi(a)),r&&sa(t.instance_id,{type:_i,request_id:r,...a})};if(!n)return i({ok:!1,error:"unsupported"}),!0;if(!wo(o.payload_meta))return i({ok:!1,error:"invalid"}),!0;console.log(_n,"payload_meta \u2190",t.instance_id,r,hi(o.payload_meta));let l=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id,s=typeof o.agent_id=="string"&&o.agent_id?o.agent_id:void 0,c=typeof o.text=="string"?o.text:"";return Promise.resolve().then(()=>n.sendPayloadMeta({app_id:l,agent_id:s,text:c,payload_meta:o.payload_meta})).then(a=>i({...wo(a)?a:null,ok:!!(a!=null&&a.ok)})).catch(a=>{console.warn("[miniapp] agent sendPayloadMeta l\u1ED7i",a),i({ok:!1,error:"send_failed"})}),!0},Si=e=>e.subscribe({message:({agent_id:t,fb_client_id:n,raw:o})=>{fi(t!=null?t:"",{type:mi,fb_client_id:n,raw:o})},stopped:({agent_id:t,source:n})=>{fi(t||wi||"",{type:yi,source:n})}}),aa=e=>{var t;return(t=wn.get(e))!=null?t:null};import{useCallback as Mi,useEffect as ht,useRef as Ie,useState as An}from"react";import{Animated as $,BackHandler as la,Dimensions as ca,Easing as Sn,Pressable as pa,StyleSheet as Mo,Text as Wt,View as K}from"react-native";import{Fragment as Aa,jsx as k,jsxs as Oe}from"react/jsx-runtime";var jt="#22C55E",ua="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",da=2,vn=18,ga=1600,Gt=14,ha=2e3,Ci=.38,fa=40,vi=2,ma=8,ya=2e3,ba=250,ft=2e3,_a=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:Gt},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:Gt},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:Gt},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:Gt}],xi=({color:e})=>k(Aa,{children:_a.map((t,n)=>k(K,{style:[x.corner,t,{borderColor:e}]},n))}),Mn=({style:e,children:t,...n})=>{let o=Ie(new $.Value(1)).current,r=i=>$.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return k(pa,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:k($.View,{style:[e,{transform:[{scale:o}]}],children:t})})},vo=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var en,tn;let{vision:r,types:i,mode:l,layout:s,hint:c,glass_view:a,absolute:p}=e,d=s===_e.top,m=Ie(new $.Value(0)).current,u=r.useCameraDevice("back"),A=Ie(new $.Value(1)).current,[S,P]=An(!1),[v,M]=An(1),U=Ie(null),[w,V]=An(()=>{let{width:C,height:X}=ca.get("window");return{width:C,height:d?X*Ci:X,window_y:0}}),z=B(Z,C=>C.last_value),le=B(Z,C=>C.hit_tick),H=B(Z,C=>C.scan_count),h=B(Z,C=>C.notice),T=B(Z,C=>C.is_picking),E=Ie(null),_=gt(),ue=_.top,j=Ie(new $.Value(0)).current,F=Ie(new $.Value(0)).current,se=Ie(new $.Value(0)).current,Pe=Ie(n);Pe.current=n,ht(()=>{if(!t)return;m.setValue(w.height);let C=$.timing(m,{toValue:0,duration:ba,easing:Sn.out(Sn.cubic),useNativeDriver:!1});return C.start(({finished:X})=>{var g;X&&((g=Pe.current)==null||g.call(Pe))}),()=>C.stop()},[t,m]);let ze=Math.round(w.width*(d?.8:.78)),Y=Math.round(d?w.height*.46:ze*.78),ke=Math.round((w.height-Y)/2),G=Math.round((w.width-ze)/2),de=r.useCodeScanner({codeTypes:i,onCodeScanned:Mi(C=>fo(C),[])});ht(()=>{let C=la.addEventListener("hardwareBackPress",()=>(ho(),!0));return()=>C.remove()},[]);let Ze=Ie(le);ht(()=>{if(le===Ze.current)return;j.setValue(1),se.setValue(1);let C=$.parallel([$.timing(j,{toValue:0,duration:450,useNativeDriver:!0}),$.sequence([$.delay(ha),$.timing(se,{toValue:0,duration:250,useNativeDriver:!0})])]);return C.start(),()=>C.stop()},[le,j,se]),ht(()=>{let C=g=>$.timing(F,{toValue:g,duration:ga,easing:Sn.inOut(Sn.quad),useNativeDriver:!0}),X=$.loop($.sequence([C(1),C(0)]));return X.start(),()=>X.stop()},[F]);let St=Mi(()=>{$.timing(A,{toValue:0,duration:220,useNativeDriver:!0}).start()},[A]);ht(()=>{let C=setTimeout(St,ya);return()=>clearTimeout(C)},[St]);let[Xt,Qt]=An(!1);ht(()=>{let C=requestAnimationFrame(()=>{C=requestAnimationFrame(()=>Qt(!0))});return()=>cancelAnimationFrame(C)},[]);let $e=!!(u!=null&&u.hasTorch),We=(en=u==null?void 0:u.neutralZoom)!=null?en:1,et=u?Math.min(u.maxZoom/We,ma):1,Ln=We*Math.min(v,et),ct=C=>{var b;let{touches:X}=C.nativeEvent;if(X.length!==2){U.current=null;return}let g=Math.hypot(X[0].pageX-X[1].pageX,X[0].pageY-X[1].pageY);(b=U.current)!=null||(U.current={distance:g,level:v}),M(Math.max(1,Math.min(et,U.current.level*(g/U.current.distance))))},Zt=k(Wt,{style:[x.hint,!!h&&x.hint_notice],numberOfLines:1,children:(tn=h!=null?h:c)!=null?tn:ua});return k($.View,{ref:E,onTouchMove:ct,onTouchEnd:()=>{U.current=null},pointerEvents:t?"none":"auto",style:d?[x.top,p&&x.top_absolute,t&&{height:m}]:x.full,onLayout:({nativeEvent:{layout:C}})=>{var X;t||(o==null||o(C.height),(X=E.current)==null||X.measureInWindow((g,b)=>{V({width:C.width,height:C.height,window_y:b||0})}))},children:Oe(K,{style:t?[x.content_closing,{height:w.height}]:x.content,children:[u&&Xt&&k(r.Camera,{style:Mo.absoluteFill,device:u,isActive:!T,codeScanner:de,torch:S&&$e?"on":"off",zoom:Ln,onPreviewStarted:St,onError:C=>Jr(C.message)}),k($.View,{style:[x.preview_cover,{opacity:A}],pointerEvents:"none"}),w.height>0&&Oe(K,{style:x.overlay,pointerEvents:"none",children:[k(K,{style:[x.dim_ring,{top:ke-ft,left:G-ft,width:ze+ft*2,height:Y+ft*2}]}),Oe(K,{style:{position:"absolute",top:ke,left:G,width:ze,height:Y},children:[k(xi,{color:"#FFFFFF"}),k($.View,{style:[Mo.absoluteFill,{opacity:j}],children:k(xi,{color:jt})}),Oe($.View,{style:[x.scan_line_wrap,{transform:[{translateY:F.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,Y-vn)]})}]}],children:[k(K,{style:x.scan_glow_outer}),k(K,{style:x.scan_glow_inner}),k(K,{style:x.scan_line})]})]}),k(K,{style:[x.hint_slot,d?{top:0,height:ke-6,justifyContent:"flex-end"}:{top:ke+Y+20}],children:Zt}),l===Ye.continuous&&!!z&&k($.View,{style:[x.result_slot,{top:d?ke+Y-fa:ke+Y+52},{opacity:se}],children:Oe(K,{style:x.result,children:[k(K,{style:x.check_badge,children:k(K,{style:x.check_mark})}),k(Wt,{style:x.result_text,numberOfLines:1,children:z}),Oe(Wt,{style:x.result_count,children:["\xB7 ",H," m\xE3"]})]})})]}),w.height>0&&k(K,{style:[x.close_slot,d?x.close_slot_top:{top:Math.max(12,ue-w.window_y+12)}],children:Oe(Mn,{style:[x.close_button,!!a&&x.glass_surface],onPress:ho,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&k(a,{style:x.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),k(K,{style:[x.close_bar,x.close_bar_a]}),k(K,{style:[x.close_bar,x.close_bar_b]})]})}),k(K,{style:[x.toolbar_wrap,!d&&{bottom:_.bottom+20}],pointerEvents:"box-none",children:Oe(K,{style:[x.toolbar,!!a&&x.glass_surface],children:[a&&k(a,{style:x.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),k(Mn,{style:x.tool,onPress:Kr,disabled:T,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:Oe(K,{style:x.image_icon,children:[k(K,{style:x.image_icon_dot}),k(K,{style:x.image_icon_hill})]})}),!!u&&et>=vi&&k(Mn,{style:[x.tool,v>1&&x.tool_on],onPress:()=>M(C=>C>1?1:vi),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:Oe(Wt,{style:[x.zoom_text,v>1&&x.zoom_text_on],children:[Math.round(v*10)/10,"x"]})}),$e&&k(Mn,{style:[x.tool,S&&x.tool_on],onPress:()=>P(C=>!C),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:S},children:k(Wt,{style:[x.torch_icon,S&&x.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},wa="rgba(0,0,0,0.5)",So=50,x=Mo.create({top:{height:`${Ci*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:ft,borderColor:wa,borderRadius:ft+Gt},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:vn,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:vn,borderRadius:vn/2,backgroundColor:jt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:jt,opacity:.2},scan_line:{height:da,borderRadius:1,backgroundColor:jt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:So,height:So,borderRadius:So/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:jt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});import{useEffect as Ei,useRef as Jt,useState as Ti}from"react";import{AccessibilityInfo as Sa,Animated as ee,Platform as Ma,StyleSheet as Pi,Text as va,View as st}from"react-native";import{Fragment as Oi,jsx as fe,jsxs as Co}from"react/jsx-runtime";var xo={[Me.info]:"#3B82F6",[Me.success]:"#22C55E",[Me.error]:"#EF4444"},ki=-120,xn=Ma.OS==="android",Ri=({type:e})=>e===Me.success?fe(st,{style:ie.check_mark}):e===Me.error?Co(Oi,{children:[fe(st,{style:[ie.cross_bar,ie.cross_a]}),fe(st,{style:[ie.cross_bar,ie.cross_b]})]}):Co(Oi,{children:[fe(st,{style:ie.info_dot}),fe(st,{style:ie.info_bar})]}),Ii=()=>{let e=B(Tt,m=>m.message),t=B(Tt,m=>m.type),n=B(Tt,m=>m.tick),o=Jt(new ee.Value(ki)).current,r=Jt(new ee.Value(0)).current,i=Jt(new ee.Value(.92)).current,l=Jt(new ee.Value(0)).current,[s,c]=Ti(),[a,p]=Ti(!1);Ei(()=>{let m=!0;return Bt().then(u=>{m&&u&&c(()=>u)}),()=>{m=!1}},[]);let d=Jt(n);return Ei(()=>{if(n===d.current)return;Sa.announceForAccessibility(e),p(!0),l.setValue(0),i.setValue(.92);let m=ee.sequence([ee.parallel([ee.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),ee.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),ee.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),ee.sequence([ee.delay(90),ee.spring(l,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),ee.delay(fr[t]),ee.parallel([ee.timing(o,{toValue:ki,duration:240,useNativeDriver:!0}),ee.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return m.start(({finished:u})=>{u&&p(!1)}),()=>m.stop()},[n]),a?fe(st,{style:[ie.layer,{top:gt().top+(xn?12:8)}],pointerEvents:"none",children:Co(ee.View,{style:[ie.toast,xn&&ie.toast_android,!!s&&ie.toast_glass,{opacity:s?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[s&&fe(s,{style:ie.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),xn?fe(ee.View,{style:[ie.badge_halo,{backgroundColor:`${xo[t]}33`,transform:[{scale:l}]}],children:fe(st,{style:[ie.badge,{backgroundColor:xo[t]}],children:fe(Ri,{type:t})})}):fe(ee.View,{style:[ie.badge,{backgroundColor:xo[t],transform:[{scale:l}]}],children:fe(Ri,{type:t})}),fe(va,{style:[ie.message,xn&&ie.message_android],numberOfLines:2,children:e})]})}):null},ie=Pi.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:Pi.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});import{Fragment as Ro,jsx as ne,jsxs as mt}from"react/jsx-runtime";var To=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Di=0,Ra=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Oa=e=>{let[t,n]=Fe(0);return pe(()=>{if(!e||Ui.OS!=="ios"){n(0);return}let o=Li.addListener("keyboardWillChangeFrame",i=>n(Math.max(0,i.endCoordinates.height))),r=Li.addListener("keyboardWillHide",()=>n(0));return()=>{o.remove(),r.remove()}},[e]),t},Ia=Oo.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:l,bridge:s,opaque_background:c,allow_embedded_miniapps:a,keyboard_mode:p,onWebLoadEnd:d})=>{var C,X;let m=Ui.OS==="ios",u=m&&p!=="scroll",A=Oa(m&&p==="resize"&&t),S=Ce(null),P=Ce(!1),v=B(re,g=>g.instances[e]),M=v==null?void 0:v.app.app_id,U=v==null?void 0:v.app.manifest_url,w=v==null?void 0:v.context,V=v==null?void 0:v.url_params,z=B(Z,g=>{var b;return((b=g.active)==null?void 0:b.owner)===e?g.active:null}),[le,H]=Fe(null),[h,T]=Fe(z);z!==h&&(T(z),z?H(null):(h==null?void 0:h.layout)===_e.top&&H(h));let E=(z==null?void 0:z.layout)===_e.top?z:le,[_,ue]=Fe(()=>M?D(M):null),[j,F]=Fe(!1),[se,Pe]=Fe(0),[ze,Y]=Fe(0),[ke,G]=Fe(!1),de=Ce(null),Ze=g=>{de.current&&clearTimeout(de.current),de.current=setTimeout(()=>{de.current=null,G(!0)},g)};pe(()=>()=>{de.current&&clearTimeout(de.current)},[]),pe(()=>{if(!M||!t&&_)return;let g=!0;return F(!1),(async()=>{let b=D(M),ge=b?await Ue(b):!1;if(!g||(ue(ge?Se=>!Se||Se.version!==b.version||Se.permissions.join(",")!==b.permissions.join(",")?b:Se:null),__DEV__&&Date.now()-Di>1e4&&(Di=Date.now(),await Kn()),!g))return;let je=await dn(M),tt=je!==void 0?je:U?await Sr(M,U):D(M);if(g){if(!tt){F(!0);return}ue(Se=>Se!=null?Se:tt)}})(),()=>{g=!1}},[t,M,U,se]),pe(()=>di(e,g=>S.current?(S.current.postMessage(g),!0):!1),[e]);let St=B(I,g=>{let b=M?g.downloads[M]:void 0;return(b==null?void 0:b.status)==="installed"?b.version:void 0});pe(()=>{if(t||!M||!_)return;let g=D(M);if(!g||g.version===_.version)return;let b=!0;return Ue(g).then(ge=>{!b||!ge||(ce(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",_.version,"\u2192",g.version),ue(g))}),()=>{b=!1}},[t,M,St,_==null?void 0:_.version]);let Xt=B(I,g=>{var b;return M&&(b=g.apply_ticks[M])!=null?b:0});pe(()=>{if(!Xt||!M)return;let g=D(M);if(!g||g.version===(_==null?void 0:_.version))return;let b=!0;return Ue(g).then(ge=>{!b||!ge||(ce(`webview:${e}`,"c\u1EADp nh\u1EADt",_==null?void 0:_.version,"\u2192",g.version),G(!1),ue(g))}),()=>{b=!1}},[Xt]),pe(()=>{var ge;let g=(ge=R().keep_alive)==null?void 0:ge.idle_close_ms;if(t||!g||g<=0)return;let b=setTimeout(()=>{an(e)},g);return()=>clearTimeout(b)},[t,e]),pe(()=>{r>0&&(F(!1),G(!1),Y(g=>g+1),Pe(g=>g+1))},[r]);let Qt=Ce(t);pe(()=>{var g;Qt.current!==t&&(Qt.current=t,P.current&&((g=S.current)==null||g.injectJavaScript(ri(t?"resumed":"paused"))))},[t]);let $e=`${(C=_==null?void 0:_.version)!=null?C:"none"}:${(X=_==null?void 0:_.permissions.join(","))!=null?X:""}:${ze}`,We=Cn(()=>JSON.stringify([w!=null?w:{},V!=null?V:{}]),[w,V]),et=Cn(()=>{var g;return ci(V!=null?V:{},(g=_==null?void 0:_.permissions)!=null?g:[])},[We,_==null?void 0:_.permissions]),Ln=Cn(()=>ai(w!=null?w:{},et,{keyboard_mode:u?p:void 0})+ni()+oi()+(R().debug?ti():""),[et]),ct=Ce(null),Zt=Ce(null);pe(()=>{var b,ge,je;if(!_)return;if(Zt.current!==$e){Zt.current=$e,ct.current=We;return}if(ct.current===We)return;let g=((ge=JSON.parse((b=ct.current)!=null?b:"[]")[0])!=null?ge:{}).org_id;if(ct.current=We,g===(w==null?void 0:w.org_id)&&P.current){G(!1),Ze(1500),(je=S.current)==null||je.injectJavaScript(ii(w!=null?w:{},et));return}G(!1),Y(tt=>tt+1)},[We,_,$e]),pe(()=>(t||(qe(e),Xe(e),rt(e)),()=>{qe(e),Xe(e),rt(e)}),[t,e,$e,r]),pe(()=>{let g=Fi.addEventListener("change",b=>{b==="background"&&!Dr()&&qe(e),b==="background"&&!qr()&&Xe(e)});return()=>g.remove()},[e]);let en=Po(async g=>{var ge,je,tt,Se,Dn,$o;let b=Xr(g.nativeEvent.data);if(!b){if(M&&Ai(g.nativeEvent.data,{app_id:M,instance_id:e},s==null?void 0:s.agent))return;if(M&&(s!=null&&s.onWebEvent))try{Promise.resolve(s.onWebEvent(g.nativeEvent.data,{app_id:M,instance_id:e})).catch(W=>{console.warn("[miniapp] onWebEvent l\u1ED7i",M,W)})}catch(W){console.warn("[miniapp] onWebEvent l\u1ED7i",M,W)}return}if(b.method==="log"){let{level:W,text:J}=b;ce(`web:${e}`,W!=null?W:"log",J!=null?J:"");return}if(b.method==="pong"){de.current||G(!0);return}if(b.method==="touchAtTop"){i.emit(!!b.at_top);return}if(b.method==="contextApplied"){de.current&&clearTimeout(de.current),de.current=null,G(!0);return}if(b.method==="ready"){P.current=!0,G(!0);let W=(ge=re.getState().instances[e])==null?void 0:ge.context;W&&((je=S.current)==null||je.injectJavaScript(yo(W)));return}try{let W=await ui(b,{getHostData:()=>{var J,ye;return(ye=(J=re.getState().instances[e])==null?void 0:J.host_data)!=null?ye:{}},getPermissions:()=>{var J,ye;return M?(ye=(J=D(M))==null?void 0:J.permissions)!=null?ye:[]:[]},getContext:()=>{var J,ye;return(ye=(J=re.getState().instances[e])==null?void 0:J.context)!=null?ye:{}},is_dark:o,close:Rt,app_id:M!=null?M:"",instance_id:e,options:s,emit:(J,ye)=>{var Wo;(Wo=S.current)==null||Wo.injectJavaScript(ei(J,ye))},playBeep:(tt=s==null?void 0:s.playScannerBeep)!=null?tt:(()=>{var J;(J=S.current)==null||J.injectJavaScript(pi())}),isActive:()=>re.getState().active_key===e&&Fi.currentState!=="background"});b.id&&((Se=S.current)==null||Se.injectJavaScript(Qr(b.id,W)))}catch(W){if(!b.id)return;let J=W==null?void 0:W.code,ye=W instanceof f?W:new f(typeof J=="string"?J:"HOST_ERROR",String((Dn=W==null?void 0:W.message)!=null?Dn:W));($o=S.current)==null||$o.injectJavaScript(Zr(b.id,ye))}},[e,o,M,i,s]),tn=Po(()=>{F(!1),Y(g=>g+1),Pe(g=>g+1)},[]);return mt(ko,{style:[Io.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&we.behind],pointerEvents:t?"auto":"none",children:[E&&ne(vo,{scanner:E,closing:E===le,onClosed:()=>{var g;H(null),E.absolute&&((g=S.current)==null||g.injectJavaScript(bo(0)))},onHeight:E.absolute?g=>{var b;return(b=S.current)==null?void 0:b.injectJavaScript(bo(g))}:void 0}),_?ne(ka,{ref:S,source:{uri:_.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${a?Hn():_.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ln,onMessage:en,onShouldStartLoadWithRequest:g=>{let b=g.url;return g.isTopFrame===!1||!/^https?:\/\//i.test(b)?!0:(Promise.resolve(s!=null&&s.openUrl?s.openUrl(b):Ta.openURL(b)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",scrollEnabled:!u,onLoadStart:g=>{qe(e),Xe(e),rt(e),ce(`webview:${e}`,"load start",To(g.nativeEvent.url)),P.current=!1,G(!1)},onError:g=>{qe(e),Xe(e),rt(e),ce(`webview:${e}`,"load error",To(g.nativeEvent.url),g.nativeEvent.description),F(!0),G(!1)},onLoadEnd:g=>{let b=g.nativeEvent.url;ce(`webview:${e}`,"load end",To(b)),M&&(d==null||d({app_id:M,instance_id:e,url:b})),Ze(1500)},onContentProcessDidTerminate:()=>{qe(e),Xe(e),rt(e),P.current=!1,G(!1),Y(g=>g+1)},onRenderProcessGone:()=>(qe(e),Xe(e),rt(e),P.current=!1,G(!1),Y(g=>g+1),!0),style:[we.webview,A>0&&{marginBottom:A}]},$e):null,(z==null?void 0:z.layout)===_e.full&&ne(vo,{scanner:z}),v&&ne(La,{visible:!_||!ke,interactive:j,children:ne(Fa,{splash:l,app:v.app,is_dark:o,error:j,has_bundle:!!_,retry:tn})})]})}),Fa=Oo.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let l=e,s=It(t.app_id),c=o?"error":!r&&(s==null?void 0:s.status)==="downloading"?"downloading":"loading";return ne(l,{app:t,is_dark:n,status:c,progress:c==="downloading"?s==null?void 0:s.progress:void 0,retry:i})}),La=({visible:e,interactive:t,children:n})=>{let o=Ce(new Eo.Value(e?1:0)).current,[r,i]=Fe(e);return pe(()=>{if(e){i(!0),o.setValue(1);return}let l=Eo.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return l.start(({finished:s})=>{s&&i(!1)}),()=>l.stop()},[e,o]),r?ne(Eo.View,{style:[Io.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},Vi=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return mt(ko,{style:[we.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[ne(ko,{style:[we.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?ne(Ea,{source:{uri:e.icon},style:we.splash_icon_image}):ne(Kt,{style:we.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),ne(Kt,{style:[we.splash_name,{color:i}],children:e.name}),n==="error"?mt(Ro,{children:[ne(Kt,{style:we.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),ne(Pa,{activeOpacity:.7,style:[we.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:ne(Kt,{style:[we.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):mt(Ro,{children:[ne(xa,{style:we.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&mt(Kt,{style:we.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},Ni=(e,t)=>{let n=Ce(t),o=Ce(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},Da=({container:e,splash:t=Vi,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:l=!1,keyboard_mode:s="scroll",onWebLoadEnd:c})=>{Ni("container",e),Ni("splash",t);let a=e,p=B(re,w=>w.active_key),d=Ce(p);p&&(d.current=p);let m=B(re,w=>Object.keys(w.instances).join("|")),u=B(re,w=>{var V;return w.active_key?(V=w.instances[w.active_key])==null?void 0:V.app.name:void 0}),A=Cn(()=>m?m.split("|"):[],[m]),[S,P]=Fe({}),v=Ce(Ra()).current,M=o==null?void 0:o.agent;pe(()=>M?Si(M):void 0,[M]),pe(()=>{if(!p||!r)return;let w=Ca.addEventListener("hardwareBackPress",()=>(Rt(),!0));return()=>w.remove()},[p,r]);let U=Po(()=>{let w=re.getState().active_key;w&&P(V=>({...V,[w]:(V[w]||0)+1}))},[]);return A.length?mt(Ro,{children:[ne(a,{visible:!!p,title:u!=null?u:"",is_dark:n,close:Rt,reload:U,subscribeWebAtTop:v.subscribe,children:A.map(w=>ne(Ia,{instance_key:w,is_active:p===w,is_front:(p!=null?p:d.current)===w,is_dark:n,reload_tick:S[w]||0,web_at_top:v,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:l,keyboard_mode:s,onWebLoadEnd:c},w))}),ne(Ii,{})]}):null},we=Io.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"}}),Na=Oo.memo(Da);import hl,{useRef as fl,useState as Gi}from"react";import{useEffect as al,useRef as Wi,useState as Ho}from"react";import{Animated as wt,Image as ll,Modal as zo,Pressable as cl,ScrollView as pl,StyleSheet as ul,Text as me,TouchableOpacity as qo,View as Ne}from"react-native";import{Linking as Ga,Text as at,View as bt}from"react-native";var Ua=/\*\*(.+?)\*\*|`([^`]+)`|\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,En=e=>{var o;let t=[],n=0;for(let r of e.matchAll(Ua)){let i=(o=r.index)!=null?o:0;i>n&&t.push({type:"text",text:e.slice(n,i)}),r[1]!==void 0?t.push({type:"bold",text:r[1]}):r[2]!==void 0?t.push({type:"code",text:r[2]}):t.push({type:"link",text:r[3],url:r[4]}),n=i+r[0].length}return n<e.length&&t.push({type:"text",text:e.slice(n)}),t},Va=e=>En(e).map(t=>t.text).join("");import{Platform as Uo,StyleSheet as No}from"react-native";import{createContext as Ba,useContext as Ha,useMemo as qa}from"react";import{jsx as ja}from"react/jsx-runtime";var Lo={changelog_title:"C\xF3 g\xEC m\u1EDBi",changelog_ok:"\u0110\xE3 hi\u1EC3u",changelog_view_all:"Xem t\u1EA5t c\u1EA3 c\u1EADp nh\u1EADt",changelog_more:"+{count} thay \u0111\u1ED5i kh\xE1c",history_title:"L\u1ECBch s\u1EED c\u1EADp nh\u1EADt",history_empty:"Ch\u01B0a c\xF3 ghi ch\xFA c\u1EADp nh\u1EADt.",history_error:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c l\u1ECBch s\u1EED c\u1EADp nh\u1EADt.",retry:"Th\u1EED l\u1EA1i",update_title:"\u0110\xE3 c\xF3 b\u1EA3n c\u1EADp nh\u1EADt",updating_title:"\u0110ang c\u1EADp nh\u1EADt\u2026",update_message:`Phi\xEAn b\u1EA3n {next} \u0111\xE3 s\u1EB5n s\xE0ng (hi\u1EC7n t\u1EA1i {current}).
89
- Vui l\xF2ng c\u1EADp nh\u1EADt \u0111\u1EC3 ti\u1EBFp t\u1EE5c s\u1EED d\u1EE5ng.`,update_failed:"C\u1EADp nh\u1EADt kh\xF4ng th\xE0nh c\xF4ng. Ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng r\u1ED3i th\u1EED l\u1EA1i.",update_now:"C\u1EADp nh\u1EADt ngay",updating_hint:"Vui l\xF2ng kh\xF4ng t\u1EAFt \u1EE9ng d\u1EE5ng",date_locale:"vi-VN"},Tn=(e,t)=>e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n),Do=[{key:"new",label:"M\u1EDBi",color:"#007AFF",bg:"#E5F1FF"},{key:"fix",label:"S\u1EEDa l\u1ED7i",color:"#C4320A",bg:"#FFF1EB"},{key:"improve",label:"C\u1EA3i thi\u1EC7n",color:"#067647",bg:"#E7F7EE"}],Le={primary:"#007AFF",on_primary:"#FFFFFF",background:"#F2F2F7",surface:"#FFFFFF",text:"#1C1C1E",text_secondary:"#666666",hint:"#AEAEB2",overlay:"rgba(0, 0, 0, 0.6)",divider:"rgba(60, 60, 67, 0.18)",radius:28,button_radius:12,button_height:50},za={primary:"#0A84FF",on_primary:"#FFFFFF",background:"#000000",surface:"#1C1C1E",text:"#FFFFFF",text_secondary:"#A1A1AA",hint:"#636366",overlay:"rgba(0, 0, 0, 0.7)",divider:"rgba(84, 84, 88, 0.6)",radius:28,button_radius:12,button_height:50},$a={new:{color:"#64B5FF",bg:"rgba(10, 132, 255, 0.18)"},fix:{color:"#FF9F7A",bg:"rgba(255, 112, 67, 0.18)"},improve:{color:"#5FD39A",bg:"rgba(48, 209, 88, 0.18)"}},Fo=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Pn=(e={},t)=>{let{kinds:n,dark:o=!1,...r}=e;return{...o?za:Le,...Fo(r),dark:o,labels:{...Lo,...Fo(t!=null?t:{})},kinds:Do.map(i=>{var l;return{...i,...o?$a[i.key]:null,...i.key==="new"&&e.primary?{color:e.primary}:null,...Fo((l=n==null?void 0:n[i.key])!=null?l:{})}})}},Bi=Ba(void 0),Wa=Pn(),yt=({theme:e,labels:t,children:n})=>{let o=qa(()=>Pn(e,t),[e,t]);return ja(Bi.Provider,{value:o,children:n})},Ee=()=>{var e;return(e=Ha(Bi))!=null?e:Wa},kn=e=>({new:e.flatMap(t=>t.changelog.new),fix:e.flatMap(t=>t.changelog.fix),improve:e.flatMap(t=>t.changelog.improve)}),Hi=(e,t)=>{let n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString(t)};var N={blue:Le.primary,track:"#E5E5EA",overlay:Le.overlay,shadow:"#000000",title:Le.text,sub_title:Le.text_secondary,error:"#D92D20",hint:Le.hint,surface:Le.surface,background:Le.background},qi=Uo.select({ios:{shadowColor:N.shadow,shadowOffset:{width:0,height:10},shadowOpacity:.1,shadowRadius:20},android:{elevation:10}}),y=No.create({overlay:{flex:1,backgroundColor:N.overlay,justifyContent:"center",alignItems:"center"},container:{width:"85%",maxWidth:340,backgroundColor:N.surface,padding:24,borderRadius:28,alignItems:"center",...qi},sheet:{width:"88%",maxWidth:380,maxHeight:"78%",backgroundColor:N.surface,borderRadius:28,overflow:"hidden",...qi},sheet_head:{alignItems:"center",paddingTop:24,paddingHorizontal:22,paddingBottom:4},sheet_name:{fontSize:13,color:N.sub_title,marginTop:4,maxWidth:"100%"},version_pill:{flexDirection:"row",alignItems:"center",gap:6,marginTop:10,paddingHorizontal:12,paddingVertical:5,borderRadius:999,backgroundColor:N.background},version_old:{fontSize:13,color:N.sub_title,fontVariant:["tabular-nums"]},version_arrow:{fontSize:13,color:N.hint},version_new:{fontSize:13,fontWeight:"700",color:N.blue,fontVariant:["tabular-nums"]},sheet_foot:{paddingHorizontal:22,paddingTop:4,paddingBottom:18},sheet_foot_divider:{borderTopWidth:No.hairlineWidth,borderTopColor:"rgba(60, 60, 67, 0.18)"},logo:{width:64,height:64,borderRadius:16,marginBottom:20},title:{fontSize:20,fontWeight:"700",color:N.title,textAlign:"center"},sub_title:{fontSize:13,color:N.sub_title,textAlign:"center",lineHeight:18,marginTop:6},gap:{marginBottom:15},error_text:{fontSize:12,textAlign:"center",color:N.error,lineHeight:17,marginBottom:15},progress_section:{width:"100%",alignItems:"center",paddingVertical:8,marginTop:8,gap:12},progress_text:{fontSize:18,fontWeight:"700",color:N.blue},progress_track:{width:"100%",height:6,borderRadius:3,backgroundColor:N.track,overflow:"hidden"},progress_fill:{height:"100%",borderRadius:3,backgroundColor:N.blue},loading_hint:{fontSize:12,color:N.hint,textAlign:"center"},scroll:{flexGrow:0,flexShrink:1},scroll_content:{paddingHorizontal:22,paddingTop:16,paddingBottom:16},groups:{gap:18},group:{gap:8},group_head:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:2},group_count:{fontSize:12,fontWeight:"600",color:N.hint},dot:{width:5,height:5,borderRadius:3,marginTop:8},more:{fontSize:14,fontWeight:"500",color:N.blue,paddingLeft:17,paddingTop:2},badge:{alignSelf:"flex-start",paddingHorizontal:10,paddingVertical:3,borderRadius:999},badge_text:{fontSize:12,fontWeight:"700"},item:{flexDirection:"row",gap:10,paddingLeft:2},item_text:{flex:1,fontSize:15,lineHeight:21,color:N.title},md_bold:{fontWeight:"700"},md_code:{fontFamily:Uo.select({ios:"Menlo",default:"monospace"}),fontSize:13,backgroundColor:"#F2F2F7",color:"#3A3A3C"},md_link:{color:N.blue,textDecorationLine:"underline"},full:{width:"100%"},btn_primary:{marginTop:14,backgroundColor:N.blue,paddingVertical:14,borderRadius:12,alignItems:"center"},btn_primary_text:{color:"white",fontWeight:"600",fontSize:16},btn_secondary:{paddingTop:12,alignItems:"center"},link:{color:N.blue,fontSize:15,fontWeight:"600"},history:{flex:1,backgroundColor:N.background},float_header:{position:"absolute",top:0,left:0,right:0},header_row:{flexDirection:"row",alignItems:"center",paddingHorizontal:16,paddingTop:2,paddingBottom:8},header_title:{position:"absolute",top:2,bottom:8,alignItems:"center",justifyContent:"center"},history_title:{fontSize:15,fontWeight:"500",color:"#1C1C1E"},history_sub:{fontSize:11,color:"#71717A",marginTop:1},back_btn:{alignItems:"center",justifyContent:"center"},back_btn_fallback:{backgroundColor:N.surface,...Uo.select({ios:{shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8},default:{borderWidth:No.hairlineWidth*2,borderColor:"rgba(0, 0, 0, 0.08)"}})},icon_layer:{position:"absolute",top:0,left:0,right:0,bottom:0,alignItems:"center",justifyContent:"center"},fade:{position:"absolute",top:0,left:0,right:0},chevron:{width:11,height:11,borderLeftWidth:2.2,borderBottomWidth:2.2,borderColor:Le.text,transform:[{rotate:"45deg"}],marginLeft:4},pressed:{opacity:.6,transform:[{scale:.94}]},history_list:{padding:16,gap:12},card:{backgroundColor:N.surface,borderRadius:16,padding:16,gap:12},card_head:{flexDirection:"row",justifyContent:"space-between",alignItems:"baseline"},version:{fontSize:16,fontWeight:"700",color:N.title},date:{fontSize:13,color:N.sub_title},loading:{marginTop:40},center:{alignItems:"center",marginTop:40,gap:12},empty:{marginTop:40}});import{jsx as Te,jsxs as Vo}from"react/jsx-runtime";var Bo=({text:e,style:t})=>{let n=Ee();return Te(at,{style:t,children:En(e.replace(/^(?:[-*•]\s+)+/,"")).map((o,r)=>{switch(o.type){case"bold":return Te(at,{style:y.md_bold,children:o.text},r);case"code":return Te(at,{style:[y.md_code,{backgroundColor:n.background,color:n.text}],children:o.text},r);case"link":return Te(at,{style:[y.md_link,{color:n.primary}],accessibilityRole:"link",onPress:()=>{Ga.openURL(o.url).catch(()=>{})},children:o.text},r);default:return o.text}})})},_t=({changelog:e,max_items:t,onMore:n})=>{let o=Ee();return Te(bt,{style:y.groups,children:o.kinds.filter(r=>e[r.key].length).map(r=>{let i=e[r.key],l=t?i.slice(0,t):i,s=i.length-l.length;return Vo(bt,{style:y.group,children:[Vo(bt,{style:y.group_head,children:[Te(bt,{style:[y.badge,{backgroundColor:r.bg}],children:Te(at,{style:[y.badge_text,{color:r.color}],children:r.label})}),Te(at,{style:[y.group_count,{color:o.hint}],children:i.length})]}),l.map((c,a)=>Vo(bt,{style:y.item,children:[Te(bt,{style:[y.dot,{backgroundColor:r.color}]}),Te(Bo,{text:c,style:[y.item_text,{color:o.text}]})]},a)),s>0&&Te(at,{style:[y.more,{color:o.primary}],onPress:n,suppressHighlighting:!0,children:Tn(o.labels.changelog_more,{count:s})})]},r.key)})})};import{useEffect as zi,useState as $i}from"react";import{ActivityIndicator as Ja,Platform as Ka,Pressable as Ya,ScrollView as Xa,StyleSheet as Qa,Text as lt,TouchableOpacity as Za,View as Ae}from"react-native";import{jsx as oe,jsxs as De}from"react/jsx-runtime";var Rn,el=()=>(Rn!=null||(Rn=Promise.all([Ka.OS==="ios"?import("expo-image").then(e=>e.Image).catch(()=>{}):Promise.resolve(void 0),import("expo-linear-gradient").then(e=>e.LinearGradient).catch(()=>{})]).then(([e,t])=>({ExpoImage:e,LinearGradient:t}))),Rn),tl=()=>{let[e,t]=$i({});return zi(()=>{let n=!0;return el().then(o=>{n&&t(o)}),()=>{n=!1}},[]),e},nl="#1C1C1E",ol=e=>/^#[0-9a-f]{6}$/i.test(e),rl=()=>{let[e,t]=$i();return zi(()=>{let n=!0;return Bt().then(o=>{n&&o&&t(()=>o)}),()=>{n=!1}},[]),e},il=({onPress:e,size:t,GlassView:n,ExpoImage:o})=>{let r=Ee(),i=r.dark?"#FFFFFF":nl;return De(Ya,{onPress:e,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"Quay l\u1EA1i",style:({pressed:l})=>[y.back_btn,{width:t,height:t,borderRadius:t/2},!n&&y.back_btn_fallback,!n&&r.dark&&{backgroundColor:"#3F3F46",shadowOpacity:0},!n&&l&&y.pressed],children:[n&&oe(n,{style:[Qa.absoluteFill,{borderRadius:t/2}],glassEffectStyle:"regular",colorScheme:r.dark?"dark":"light",isInteractive:!0}),oe(Ae,{pointerEvents:"none",style:y.icon_layer,children:o?oe(o,{source:"sf:chevron.left",transition:0,contentFit:"contain",style:{width:20,height:20,fontSize:20,color:i}}):oe(Ae,{style:[y.chevron,{borderColor:i}]})})]})},Yt=({app_id:e,name:t,onBack:n,renderHeader:o})=>{let r=Ee(),i=gt(),l=rl(),{ExpoImage:s,LinearGradient:c}=tl(),a=l?46:42,p=o?0:i.top+a+10,{versions:d,loading:m,error:u,reload:A}=Zn(e);return De(Ae,{style:[y.history,{backgroundColor:r.background}],children:[o&&oe(Ae,{style:{paddingTop:i.top},children:o({title:r.labels.history_title,subtitle:t,onBack:n})}),m&&!d.length?oe(Ja,{style:[y.loading,{marginTop:p+40}],color:r.primary}):u&&!d.length?De(Ae,{style:[y.center,{marginTop:p+40}],children:[oe(lt,{style:[y.sub_title,{color:r.text_secondary}],children:r.labels.history_error}),oe(Za,{onPress:A,children:oe(lt,{style:[y.link,{color:r.primary}],children:r.labels.retry})})]}):De(Xa,{contentContainerStyle:[y.history_list,{paddingTop:p+8,paddingBottom:i.bottom+24}],scrollIndicatorInsets:{top:p},children:[d.map(S=>De(Ae,{style:[y.card,{backgroundColor:r.surface,borderRadius:Math.max(r.radius-12,0)}],children:[De(Ae,{style:y.card_head,children:[De(lt,{style:[y.version,{color:r.text}],children:["v",S.version]}),oe(lt,{style:[y.date,{color:r.text_secondary}],children:Hi(S.created_at,r.labels.date_locale)})]}),oe(_t,{changelog:S.changelog})]},S.version)),!d.length&&oe(lt,{style:[y.sub_title,y.empty,{color:r.text_secondary}],children:r.labels.history_empty})]}),!o&&De(Ae,{pointerEvents:"box-none",style:[y.float_header,{paddingTop:i.top}],children:[c&&ol(r.background)?oe(c,{pointerEvents:"none",colors:[`${r.background}F5`,`${r.background}E6`,`${r.background}B3`,`${r.background}00`],locations:[0,.45,.75,1],style:[y.fade,{height:p+28}]}):oe(Ae,{pointerEvents:"none",style:y.fade,children:sl.map((S,P)=>oe(Ae,{style:{height:P===0?p:4,backgroundColor:r.background,opacity:S}},P))}),De(Ae,{style:y.header_row,children:[oe(il,{onPress:n,size:a,GlassView:l,ExpoImage:s}),De(Ae,{pointerEvents:"none",style:[y.header_title,{left:a+24,right:a+24}],children:[oe(lt,{style:[y.history_title,{color:r.text}],numberOfLines:1,children:r.labels.history_title}),oe(lt,{style:[y.history_sub,{color:r.text_secondary}],numberOfLines:1,children:t})]})]})]})]})},sl=[.96,.9,.8,.68,.55,.42,.3,.18,.08];import{Fragment as gl,jsx as L,jsxs as Qe}from"react/jsx-runtime";var ji=e=>({backgroundColor:e.primary,borderRadius:e.button_radius,height:e.button_height,paddingVertical:0,justifyContent:"center"}),dl=4,On=({request:e,changelog:t,onClose:n,renderHistoryHeader:o,renderActions:r})=>{var m;let i=Ee(),[l,s]=Ho(!1),[c,a]=Ho(0),[p,d]=Ho(0);return L(zo,{visible:!0,transparent:!l,animationType:l?"slide":"fade",statusBarTranslucent:!0,onRequestClose:l?()=>s(!1):n,children:l?L(Yt,{app_id:e.app_id,name:e.name,onBack:()=>s(!1),renderHeader:o}):Qe(Ne,{style:[y.overlay,{backgroundColor:i.overlay}],children:[L(cl,{style:ul.absoluteFill,onPress:n,accessibilityLabel:"\u0110\xF3ng"}),Qe(Ne,{style:[y.sheet,{backgroundColor:i.surface,borderRadius:i.radius}],children:[Qe(Ne,{style:y.sheet_head,children:[L(me,{style:[y.title,{color:i.text}],children:i.labels.changelog_title}),L(me,{style:[y.sheet_name,{color:i.text_secondary}],numberOfLines:1,children:e.name}),Qe(Ne,{style:[y.version_pill,{backgroundColor:i.background}],children:[L(me,{style:[y.version_old,{color:i.text_secondary}],children:`v${e.from}`}),L(me,{style:[y.version_arrow,{color:i.hint}],children:"\u2192"}),L(me,{style:[y.version_new,{color:i.primary}],children:`v${e.to}`})]})]}),L(pl,{style:y.scroll,contentContainerStyle:y.scroll_content,onContentSizeChange:(u,A)=>a(A),onLayout:u=>d(u.nativeEvent.layout.height),children:L(_t,{changelog:t,max_items:dl,onMore:()=>s(!0)})}),L(Ne,{style:[y.sheet_foot,c>p+1&&[y.sheet_foot_divider,{borderTopColor:i.divider}]],children:r?r({onClose:n,onViewAll:()=>s(!0),labels:i.labels}):Qe(gl,{children:[L(qo,{style:[y.btn_primary,ji(i)],activeOpacity:.8,onPress:n,children:L(me,{style:[y.btn_primary_text,{color:i.on_primary}],children:i.labels.changelog_ok})}),L(qo,{style:y.btn_secondary,onPress:()=>s(!0),children:L(me,{style:[y.link,{color:(m=i.secondary)!=null?m:i.primary}],children:i.labels.changelog_view_all})})]})})]})]})})},In=({update:e,is_updating:t,progress:n,has_failed:o,onUpdate:r,logo:i,renderAction:l})=>{let s=Ee(),c=Wi(new wt.Value(0)).current,a=Wi(new wt.Value(30)).current;return al(()=>{wt.parallel([wt.timing(c,{toValue:1,duration:400,useNativeDriver:!0}),wt.spring(a,{toValue:0,friction:8,tension:40,useNativeDriver:!0})]).start()},[c,a]),L(zo,{visible:!0,transparent:!0,animationType:"none",statusBarTranslucent:!0,onRequestClose:()=>{},children:L(Ne,{style:[y.overlay,{backgroundColor:s.overlay}],children:Qe(wt.View,{style:[y.container,{backgroundColor:s.surface,borderRadius:s.radius},{opacity:c,transform:[{translateY:a}]}],children:[i&&L(ll,{source:i,style:y.logo}),L(me,{style:[y.title,{color:s.text}],children:t?s.labels.updating_title:s.labels.update_title}),!t&&L(me,{style:[y.sub_title,y.gap,{color:s.text_secondary}],children:Tn(s.labels.update_message,{next:e.next_version,current:e.current_version})}),!t&&o&&L(me,{style:y.error_text,children:s.labels.update_failed}),t?Qe(Ne,{style:y.progress_section,children:[Qe(me,{style:[y.progress_text,{color:s.primary}],children:[n,"%"]}),L(Ne,{style:[y.progress_track,{backgroundColor:s.background}],children:L(Ne,{style:[y.progress_fill,{backgroundColor:s.primary,width:`${n}%`}]})}),L(me,{style:[y.loading_hint,{color:s.hint}],children:s.labels.updating_hint})]}):l?L(Ne,{style:y.full,children:l({onUpdate:r,has_failed:o,label:o?s.labels.retry:s.labels.update_now})}):L(qo,{style:[y.btn_primary,y.full,ji(s)],activeOpacity:.8,onPress:r,children:L(me,{style:[y.btn_primary_text,{color:s.on_primary}],children:o?s.labels.retry:s.labels.update_now})})]})})})},Fn=({app_id:e,name:t,onClose:n,renderHistoryHeader:o})=>L(zo,{visible:!0,animationType:"slide",statusBarTranslucent:!0,onRequestClose:n,children:L(Yt,{app_id:e,name:t,onBack:n,renderHeader:o})});import{jsx as At}from"react/jsx-runtime";var ml=({app_ids:e,shouldShowUpdate:t,logo:n,renderUpdate:o,renderChangelog:r,theme:i,renderHistoryHeader:l,labels:s,renderChangelogActions:c,renderUpdateAction:a})=>{var z,le;let p=B(I,H=>H.updates),m=((z=e!=null?e:R().manual_update)!=null?z:[]).map(H=>p[H]).find(H=>!!H&&(!t||t(H))),u=It(m==null?void 0:m.app_id),[A,S]=Gi(!1),[P,v]=Gi(!1),M=fl(!1),U=no(),w=io(),V=async()=>{if(!m||M.current)return;M.current=!0,S(!0),v(!1);let H=await Yn(m.app_id);M.current=!1,S(!1),v(!H)};if(m){let H=(u==null?void 0:u.status)==="updating"?Math.round(((le=u.progress)!=null?le:0)*100):0,h={update:m,is_updating:A,progress:H,has_failed:P,onUpdate:V};return At(yt,{theme:i,labels:s,children:o?o(h):At(In,{...h,logo:n,renderAction:a})})}if(U){let H={request:U,changelog:kn(U.versions),onClose:to};return At(yt,{theme:i,labels:s,children:r?r(H):At(On,{...H,renderHistoryHeader:l,renderActions:c})})}return w?At(yt,{theme:i,labels:s,children:At(Fn,{...w,onClose:ro,renderHistoryHeader:l})}):null},yl=hl.memo(ml);export{Ao as AGENT_BRIDGE_VERSION,mi as AGENT_MESSAGE_EVENT,bi as AGENT_PAYLOAD_META_EVENT,_i as AGENT_PAYLOAD_META_RESULT_EVENT,yi as AGENT_STOPPED_EVENT,ae as CodeType,Lo as DEFAULT_MINIAPP_UPDATES_LABELS,Fn as DefaultMiniAppChangelogHistoryModal,On as DefaultMiniAppChangelogPrompt,Vi as DefaultMiniAppSplash,In as DefaultMiniAppUpdatePrompt,Do as MINIAPP_CHANGELOG_KINDS,Mt as MINIAPP_PLATFORM_URL,_t as MiniAppChangelogGroups,Yt as MiniAppChangelogHistory,Bo as MiniAppChangelogText,Na as MiniAppHost,f as MiniAppHostError,yl as MiniAppUpdates,yt as MiniAppUpdatesThemeProvider,dt as ScannerEndReason,po as ScannerEvent,_e as ScannerLayout,Vt as ScannerMethod,Me as ToastType,Rt as closeMiniApp,ro as closeMiniAppChangelogHistory,Ji as configureMiniApp,Yi as createMmkvStorage,Go as createReactNativeBiometrics,Ki as createRnfsFileSystem,to as dismissMiniAppChangelog,dn as ensureMiniApp,hn as fetchMiniAppChangelog,D as getLocalMiniApp,qs as getMiniAppCatalog,Ft as getMiniAppCatalogEntry,Xn as getMiniAppChangelogSeen,aa as getMiniAppIdByAgentId,Is as getMiniAppStatuses,Tr as getMiniAppUpdate,Qn as getPendingChangelog,Ss as installBundledMiniApp,Nt as markMiniAppChangelogSeen,kn as mergeMiniAppChangelog,Jn as onMiniAppEvent,vs as openMiniApp,En as parseInlineMarkdown,Us as pauseMiniApp,Bs as pauseMiniAppDownloads,xs as preloadMiniApp,qe as releaseSpeechFor,Pn as resolveMiniAppUpdatesTheme,Ns as restoreMiniApp,Vs as resumeMiniApp,Hs as resumeMiniAppDownloads,_o as sendEventToWeb,Dt as showMiniAppChangelog,oo as showMiniAppChangelogHistory,Va as stripInlineMarkdown,Kn as syncMiniAppCatalog,Ds as uninstallMiniApp,Yn as updateMiniApp,cr as uploadToUrl,Zn as useMiniAppChangelog,io as useMiniAppChangelogHistoryRequest,no as useMiniAppChangelogRequest,It as useMiniAppDownload,Os as useMiniAppDownloadsPaused,Ee as useMiniAppUpdatesTheme};
88
+ })(); true;`,oa=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),_n=(e,t)=>{if(typeof e!="string"||!e)throw new f("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},pi=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:l,app_id:s,instance_id:c,options:a,emit:p,isActive:d,playBeep:m})=>{var v,M,U,w,V,z,le,H;let u=a==null?void 0:a.handlers,A={app_id:s,instance_id:c,close:l},S=()=>{var h;(h=a==null?void 0:a.haptic)==null||h.call(a,"impactLight"),m==null||m()},P=()=>new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=Go(t);return Ht(e,()=>Jo(h,d))}case"speech.start":{if(!p)throw P();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new f("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let b of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[b])!==void 0){if(typeof t[b]!="boolean")throw new f("INVALID_PARAMS",`${b} ph\u1EA3i l\xE0 boolean`);h[b]=t[b]}if((t==null?void 0:t.mode)!==void 0&&t.mode!=="s2t"&&t.mode!=="voice")throw new f("INVALID_PARAMS","mode ph\u1EA3i l\xE0 's2t' ho\u1EB7c 'voice'");let T=(t==null?void 0:t.mode)==="s2t"?"s2t":"voice",E=T==="voice"?(v=a==null?void 0:a.voice)!=null?v:a==null?void 0:a.speech:void 0;if(Ir(c,E),E){Rr(c,E);try{return await E.start({owner:c,app_id:s,mode:T,options:h,emit:p,isActive:d!=null?d:(()=>!0)})}catch(b){throw Or(c,E),b}}return Dr(c,h,p,d)}case"speech.stop":{let h=Fr(c);return h?h.stop(c):Nr(c)}case Vt.scan:return $r(c,uo(t),d,S);case Vt.start:{if(!p)throw P();return Wr(c,uo(t),p,d,S)}case Vt.stop:return jr(c);case"uploadFiles":{let{task_id:h,...T}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new f("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return gr(or(T),{instance_id:c,app_id:s,getContext:r,task_id:h,config:a==null?void 0:a.upload,emit:p,exclusivePick:E=>Ht("uploadFiles.pick",E)})}case"uploadFiles.cancel":dr(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return pr(a==null?void 0:a.upload);case"getBiometricAvailability":return((M=a==null?void 0:a.biometrics)!=null?M:await Nn()).getAvailability();case"authenticateBiometric":{let h=_n(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new f("INVALID_PARAMS","reason must contain 1\u2013200 characters");let T=t==null?void 0:t.cancelButtonText;if(T!==void 0&&(typeof T!="string"||!T.trim()||T.length>80))throw new f("INVALID_PARAMS","Invalid cancelButtonText");return Ht(e,async()=>{var b;return((b=a==null?void 0:a.biometrics)!=null?b:await Nn()).authenticate({reason:h,cancelButtonText:T})})}case"requestPayment":{let h=u==null?void 0:u.requestPayment;if(!h)throw P();let T=t==null?void 0:t.amount;if(typeof T!="number"||!Number.isFinite(T)||T<=0)throw new f("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let E={...t,amount:T,currency:_n(t==null?void 0:t.currency,"currency")};return Ht(e,()=>h(E,A))}case"printImage":{let h=u==null?void 0:u.printImage;if(!h)throw P();let T=_n(t==null?void 0:t.image,"image");await Ht(e,()=>h({image:T},A));return}case"openScreen":if(!(u!=null&&u.openScreen))throw P();await u.openScreen({screen:_n(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},A);return;case"closeApp":l();return;case"openWebview":{let h=String((U=t==null?void 0:t.url)!=null?U:"");if(!/^https?:\/\//i.test(h))throw new f("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(a!=null&&a.openUrl?a.openUrl(h):Kr.openURL(h));return}case"openLink":{let h=String((w=t==null?void 0:t.url)!=null?w:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new f("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(a!=null&&a.openUrl?a.openUrl(h):Kr.openURL(h))}catch(T){throw new f("NOT_SUPPORTED",String((z=(V=T==null?void 0:T.message)!=null?V:T)!=null?z:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=fr(t);if(!h||(d==null?void 0:d())===!1)return;a!=null&&a.showToast?a.showToast(h.message,{type:h.type}):mr(h.message,h.type);return}case"changelog.openPopup":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;return(d==null?void 0:d())===!1?{shown:!1}:{shown:await Dt(h,{force:(t==null?void 0:t.force)===!0})}}case"changelog.openHistory":{let h=typeof(t==null?void 0:t.app_id)=="string"&&t.app_id?t.app_id:s;(d==null?void 0:d())!==!1&&oo(h);return}case"haptic":{let h=oa.has(t==null?void 0:t.type)?t.type:"selection";(le=a==null?void 0:a.haptic)==null||le.call(a,h);return}case"getSystemInfo":return{platform:na.OS==="ios"?"ios":"android",appVersion:(H=a==null?void 0:a.app_version)!=null?H:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let b=n().access_token;if(!b)throw new f("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return b}if(h!=="partner"&&h!=="chatbox")throw new f("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let T=ai[h];if(!o().includes(T))throw new f("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${T} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let E=h==="partner"?n().partner_token:n().chatbox_token;if(!E)throw new f("HOST_ERROR",`Kh\xF4ng c\xF3 ${T}`);return E}case"getUserInfo":{let h=n().user;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new f("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new f("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new f("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var bn=new Map,ui=(e,t)=>(bn.set(e,t),()=>{bn.get(e)===t&&bn.delete(e)}),bo=(e,t)=>{let n=bn.get(e);return n?n(t):!1};var hi=1,ra="retion.ai.agent",fi="retion.ai.message",mi="retion.ai.stopped",yi="retion.ai.payload_meta",_i="retion.ai.payload_meta_result",wn=new Map,bi=null,ia="[miniapp:agent]",$t=(...e)=>{globalThis.__DEV__&&console.log(ia,...e)},di=e=>{try{let t=JSON.stringify(e);return t&&t.length>300?`${t.slice(0,300)}\u2026`:t}catch{return String(e)}},wo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),sa=e=>{try{let t=JSON.parse(e);return wo(t)?t:null}catch{return null}},wi=(e,t)=>bo(e,JSON.stringify({v:hi,...t})),gi=(e,t)=>{let n=e?wn.get(e):void 0;if(!n)return $t(`${String(t.type)}: ch\u01B0a mini app n\xE0o b\xE1o agent ${e||"(tr\u1ED1ng)"} \u2192 kh\xF4ng g\u1EEDi`),0;let o=0;return n.instances.forEach(r=>{wi(r,{app_id:n.app_id,agent_id:e,...t})&&(o+=1)}),$t(`${String(t.type)} \u2192 ${o} WebView`,`app_id=${n.app_id}`,`agent_id=${e}`),o},Ai=(e,t,n)=>{let o=sa(e);if(!o)return!1;if(o.type===ra){let a=typeof o.agent_id=="string"?o.agent_id:"",p=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id;if(a){let d=wn.get(a);d&&d.app_id===p?d.instances.add(t.instance_id):($t("ghi nh\u1EADn agent",a,"\u2192 app",p,"WebView",t.instance_id),wn.set(a,{app_id:p,instances:new Set([t.instance_id])})),bi=a}return!1}if(o.type!==yi)return!1;let r=typeof o.request_id=="string"?o.request_id:"",i=a=>{$t("payload_meta_result \u2192",t.instance_id,r,di(a)),r&&wi(t.instance_id,{type:_i,request_id:r,...a})};if(!n)return i({ok:!1,error:"unsupported"}),!0;if(!wo(o.payload_meta))return i({ok:!1,error:"invalid"}),!0;$t("payload_meta \u2190",t.instance_id,r,di(o.payload_meta));let l=typeof o.app_id=="string"&&o.app_id?o.app_id:t.app_id,s=typeof o.agent_id=="string"&&o.agent_id?o.agent_id:void 0,c=typeof o.text=="string"?o.text:"";return Promise.resolve().then(()=>n.sendPayloadMeta({app_id:l,agent_id:s,text:c,payload_meta:o.payload_meta})).then(a=>i({...wo(a)?a:null,ok:!!(a!=null&&a.ok)})).catch(a=>{console.warn("[miniapp] agent sendPayloadMeta l\u1ED7i",a),i({ok:!1,error:"send_failed"})}),!0},Si=e=>e.subscribe({message:({agent_id:t,fb_client_id:n,raw:o})=>{gi(t!=null?t:"",{type:fi,fb_client_id:n,raw:o})},stopped:({agent_id:t,source:n})=>{gi(t||bi||"",{type:mi,source:n})}}),aa=e=>{var t,n;return(n=(t=wn.get(e))==null?void 0:t.app_id)!=null?n:null};import{useCallback as Mi,useEffect as ht,useRef as Ie,useState as An}from"react";import{Animated as $,BackHandler as la,Dimensions as ca,Easing as Sn,Pressable as pa,StyleSheet as So,Text as Wt,View as K}from"react-native";import{Fragment as Aa,jsx as k,jsxs as Oe}from"react/jsx-runtime";var jt="#22C55E",ua="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",da=2,vn=18,ga=1600,Gt=14,ha=2e3,Ci=.38,fa=40,vi=2,ma=8,ya=2e3,_a=250,ft=2e3,ba=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:Gt},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:Gt},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:Gt},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:Gt}],xi=({color:e})=>k(Aa,{children:ba.map((t,n)=>k(K,{style:[x.corner,t,{borderColor:e}]},n))}),Mn=({style:e,children:t,...n})=>{let o=Ie(new $.Value(1)).current,r=i=>$.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return k(pa,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:k($.View,{style:[e,{transform:[{scale:o}]}],children:t})})},Mo=({scanner:e,closing:t=!1,onClosed:n,onHeight:o})=>{var en,tn;let{vision:r,types:i,mode:l,layout:s,hint:c,glass_view:a,absolute:p}=e,d=s===be.top,m=Ie(new $.Value(0)).current,u=r.useCameraDevice("back"),A=Ie(new $.Value(1)).current,[S,P]=An(!1),[v,M]=An(1),U=Ie(null),[w,V]=An(()=>{let{width:C,height:X}=ca.get("window");return{width:C,height:d?X*Ci:X,window_y:0}}),z=B(Z,C=>C.last_value),le=B(Z,C=>C.hit_tick),H=B(Z,C=>C.scan_count),h=B(Z,C=>C.notice),T=B(Z,C=>C.is_picking),E=Ie(null),b=gt(),ue=b.top,j=Ie(new $.Value(0)).current,F=Ie(new $.Value(0)).current,se=Ie(new $.Value(0)).current,Pe=Ie(n);Pe.current=n,ht(()=>{if(!t)return;m.setValue(w.height);let C=$.timing(m,{toValue:0,duration:_a,easing:Sn.out(Sn.cubic),useNativeDriver:!1});return C.start(({finished:X})=>{var g;X&&((g=Pe.current)==null||g.call(Pe))}),()=>C.stop()},[t,m]);let ze=Math.round(w.width*(d?.8:.78)),Y=Math.round(d?w.height*.46:ze*.78),ke=Math.round((w.height-Y)/2),G=Math.round((w.width-ze)/2),de=r.useCodeScanner({codeTypes:i,onCodeScanned:Mi(C=>fo(C),[])});ht(()=>{let C=la.addEventListener("hardwareBackPress",()=>(ho(),!0));return()=>C.remove()},[]);let Ze=Ie(le);ht(()=>{if(le===Ze.current)return;j.setValue(1),se.setValue(1);let C=$.parallel([$.timing(j,{toValue:0,duration:450,useNativeDriver:!0}),$.sequence([$.delay(ha),$.timing(se,{toValue:0,duration:250,useNativeDriver:!0})])]);return C.start(),()=>C.stop()},[le,j,se]),ht(()=>{let C=g=>$.timing(F,{toValue:g,duration:ga,easing:Sn.inOut(Sn.quad),useNativeDriver:!0}),X=$.loop($.sequence([C(1),C(0)]));return X.start(),()=>X.stop()},[F]);let St=Mi(()=>{$.timing(A,{toValue:0,duration:220,useNativeDriver:!0}).start()},[A]);ht(()=>{let C=setTimeout(St,ya);return()=>clearTimeout(C)},[St]);let[Xt,Qt]=An(!1);ht(()=>{let C=requestAnimationFrame(()=>{C=requestAnimationFrame(()=>Qt(!0))});return()=>cancelAnimationFrame(C)},[]);let $e=!!(u!=null&&u.hasTorch),We=(en=u==null?void 0:u.neutralZoom)!=null?en:1,et=u?Math.min(u.maxZoom/We,ma):1,Ln=We*Math.min(v,et),ct=C=>{var _;let{touches:X}=C.nativeEvent;if(X.length!==2){U.current=null;return}let g=Math.hypot(X[0].pageX-X[1].pageX,X[0].pageY-X[1].pageY);(_=U.current)!=null||(U.current={distance:g,level:v}),M(Math.max(1,Math.min(et,U.current.level*(g/U.current.distance))))},Zt=k(Wt,{style:[x.hint,!!h&&x.hint_notice],numberOfLines:1,children:(tn=h!=null?h:c)!=null?tn:ua});return k($.View,{ref:E,onTouchMove:ct,onTouchEnd:()=>{U.current=null},pointerEvents:t?"none":"auto",style:d?[x.top,p&&x.top_absolute,t&&{height:m}]:x.full,onLayout:({nativeEvent:{layout:C}})=>{var X;t||(o==null||o(C.height),(X=E.current)==null||X.measureInWindow((g,_)=>{V({width:C.width,height:C.height,window_y:_||0})}))},children:Oe(K,{style:t?[x.content_closing,{height:w.height}]:x.content,children:[u&&Xt&&k(r.Camera,{style:So.absoluteFill,device:u,isActive:!T,codeScanner:de,torch:S&&$e?"on":"off",zoom:Ln,onPreviewStarted:St,onError:C=>Gr(C.message)}),k($.View,{style:[x.preview_cover,{opacity:A}],pointerEvents:"none"}),w.height>0&&Oe(K,{style:x.overlay,pointerEvents:"none",children:[k(K,{style:[x.dim_ring,{top:ke-ft,left:G-ft,width:ze+ft*2,height:Y+ft*2}]}),Oe(K,{style:{position:"absolute",top:ke,left:G,width:ze,height:Y},children:[k(xi,{color:"#FFFFFF"}),k($.View,{style:[So.absoluteFill,{opacity:j}],children:k(xi,{color:jt})}),Oe($.View,{style:[x.scan_line_wrap,{transform:[{translateY:F.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,Y-vn)]})}]}],children:[k(K,{style:x.scan_glow_outer}),k(K,{style:x.scan_glow_inner}),k(K,{style:x.scan_line})]})]}),k(K,{style:[x.hint_slot,d?{top:0,height:ke-6,justifyContent:"flex-end"}:{top:ke+Y+20}],children:Zt}),l===Ye.continuous&&!!z&&k($.View,{style:[x.result_slot,{top:d?ke+Y-fa:ke+Y+52},{opacity:se}],children:Oe(K,{style:x.result,children:[k(K,{style:x.check_badge,children:k(K,{style:x.check_mark})}),k(Wt,{style:x.result_text,numberOfLines:1,children:z}),Oe(Wt,{style:x.result_count,children:["\xB7 ",H," m\xE3"]})]})})]}),w.height>0&&k(K,{style:[x.close_slot,d?x.close_slot_top:{top:Math.max(12,ue-w.window_y+12)}],children:Oe(Mn,{style:[x.close_button,!!a&&x.glass_surface],onPress:ho,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&k(a,{style:x.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),k(K,{style:[x.close_bar,x.close_bar_a]}),k(K,{style:[x.close_bar,x.close_bar_b]})]})}),k(K,{style:[x.toolbar_wrap,!d&&{bottom:b.bottom+20}],pointerEvents:"box-none",children:Oe(K,{style:[x.toolbar,!!a&&x.glass_surface],children:[a&&k(a,{style:x.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),k(Mn,{style:x.tool,onPress:Jr,disabled:T,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:Oe(K,{style:x.image_icon,children:[k(K,{style:x.image_icon_dot}),k(K,{style:x.image_icon_hill})]})}),!!u&&et>=vi&&k(Mn,{style:[x.tool,v>1&&x.tool_on],onPress:()=>M(C=>C>1?1:vi),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:Oe(Wt,{style:[x.zoom_text,v>1&&x.zoom_text_on],children:[Math.round(v*10)/10,"x"]})}),$e&&k(Mn,{style:[x.tool,S&&x.tool_on],onPress:()=>P(C=>!C),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:S},children:k(Wt,{style:[x.torch_icon,S&&x.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},wa="rgba(0,0,0,0.5)",Ao=50,x=So.create({top:{height:`${Ci*100}%`,overflow:"hidden",backgroundColor:"#000000"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,backgroundColor:"#000000"},top_absolute:{position:"absolute",top:0,left:0,right:0,zIndex:1},content_closing:{position:"absolute",left:0,right:0,bottom:0,backgroundColor:"#000000"},preview_cover:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"#000000"},overlay:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"hidden"},dim_ring:{position:"absolute",borderWidth:ft,borderColor:wa,borderRadius:ft+Gt},hint_slot:{position:"absolute",left:16,right:16,alignItems:"center"},hint:{color:"#FFFFFF",fontSize:14,fontWeight:"500"},hint_notice:{color:"#FCA5A5"},corner:{position:"absolute",width:28,height:28},scan_line_wrap:{position:"absolute",top:0,left:10,right:10,height:vn,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:vn,borderRadius:vn/2,backgroundColor:jt,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:jt,opacity:.2},scan_line:{height:da,borderRadius:1,backgroundColor:jt},glass_surface:{backgroundColor:"transparent",overflow:"visible"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:999},close_slot:{position:"absolute",right:12},close_slot_top:{bottom:15},close_button:{width:48,height:48,borderRadius:24,overflow:"hidden",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0,0,0,0.5)"},close_bar:{position:"absolute",width:20,height:2,borderRadius:1,backgroundColor:"#FFFFFF"},close_bar_a:{transform:[{rotate:"45deg"}]},close_bar_b:{transform:[{rotate:"-45deg"}]},toolbar_wrap:{position:"absolute",left:0,right:0,bottom:10,alignItems:"center"},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:Ao,height:Ao,borderRadius:Ao/2,alignItems:"center",justifyContent:"center"},tool_on:{backgroundColor:"#FFFFFF"},zoom_text:{color:"#FFFFFF",fontSize:16,fontWeight:"600"},zoom_text_on:{color:"#18181B"},torch_icon:{color:"#FFFFFF",fontSize:22,fontWeight:"600"},image_icon:{width:24,height:19,borderRadius:3,borderWidth:1.5,borderColor:"#FFFFFF",overflow:"hidden"},image_icon_dot:{position:"absolute",top:3,right:3,width:4,height:4,borderRadius:2,backgroundColor:"#FFFFFF"},image_icon_hill:{position:"absolute",left:2,bottom:-6,width:12,height:12,backgroundColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_slot:{position:"absolute",left:16,right:16,alignItems:"center"},result:{maxWidth:"100%",flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingVertical:6,borderRadius:999,backgroundColor:"rgba(39,39,42,0.9)"},check_badge:{width:18,height:18,borderRadius:9,alignItems:"center",justifyContent:"center",backgroundColor:jt},check_mark:{width:5,height:9,marginTop:-2,borderRightWidth:2,borderBottomWidth:2,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},result_text:{flexShrink:1,color:"#FFFFFF",fontWeight:"600",fontSize:13},result_count:{color:"#A1A1AA",fontSize:13}});import{useEffect as Ei,useRef as Jt,useState as Ti}from"react";import{AccessibilityInfo as Sa,Animated as ee,Platform as Ma,StyleSheet as Pi,Text as va,View as st}from"react-native";import{Fragment as Oi,jsx as fe,jsxs as xo}from"react/jsx-runtime";var vo={[Me.info]:"#3B82F6",[Me.success]:"#22C55E",[Me.error]:"#EF4444"},ki=-120,xn=Ma.OS==="android",Ri=({type:e})=>e===Me.success?fe(st,{style:ie.check_mark}):e===Me.error?xo(Oi,{children:[fe(st,{style:[ie.cross_bar,ie.cross_a]}),fe(st,{style:[ie.cross_bar,ie.cross_b]})]}):xo(Oi,{children:[fe(st,{style:ie.info_dot}),fe(st,{style:ie.info_bar})]}),Ii=()=>{let e=B(Tt,m=>m.message),t=B(Tt,m=>m.type),n=B(Tt,m=>m.tick),o=Jt(new ee.Value(ki)).current,r=Jt(new ee.Value(0)).current,i=Jt(new ee.Value(.92)).current,l=Jt(new ee.Value(0)).current,[s,c]=Ti(),[a,p]=Ti(!1);Ei(()=>{let m=!0;return Bt().then(u=>{m&&u&&c(()=>u)}),()=>{m=!1}},[]);let d=Jt(n);return Ei(()=>{if(n===d.current)return;Sa.announceForAccessibility(e),p(!0),l.setValue(0),i.setValue(.92);let m=ee.sequence([ee.parallel([ee.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),ee.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),ee.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),ee.sequence([ee.delay(90),ee.spring(l,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),ee.delay(hr[t]),ee.parallel([ee.timing(o,{toValue:ki,duration:240,useNativeDriver:!0}),ee.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return m.start(({finished:u})=>{u&&p(!1)}),()=>m.stop()},[n]),a?fe(st,{style:[ie.layer,{top:gt().top+(xn?12:8)}],pointerEvents:"none",children:xo(ee.View,{style:[ie.toast,xn&&ie.toast_android,!!s&&ie.toast_glass,{opacity:s?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[s&&fe(s,{style:ie.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),xn?fe(ee.View,{style:[ie.badge_halo,{backgroundColor:`${vo[t]}33`,transform:[{scale:l}]}],children:fe(st,{style:[ie.badge,{backgroundColor:vo[t]}],children:fe(Ri,{type:t})})}):fe(ee.View,{style:[ie.badge,{backgroundColor:vo[t],transform:[{scale:l}]}],children:fe(Ri,{type:t})}),fe(va,{style:[ie.message,xn&&ie.message_android],numberOfLines:2,children:e})]})}):null},ie=Pi.create({layer:{position:"absolute",left:16,right:16,alignItems:"center",zIndex:9999,elevation:9999},toast:{maxWidth:"100%",minHeight:50,flexDirection:"row",alignItems:"center",gap:10,paddingLeft:11,paddingRight:18,paddingVertical:11,borderRadius:25,backgroundColor:"#18181B",shadowColor:"#000000",shadowOpacity:.32,shadowRadius:18,shadowOffset:{width:0,height:8},elevation:12},toast_android:{width:"100%",minHeight:60,gap:12,paddingLeft:10,paddingRight:16,paddingVertical:10,borderRadius:20,borderWidth:Pi.hairlineWidth,borderColor:"rgba(255,255,255,0.16)",backgroundColor:"#232327",elevation:16},toast_glass:{backgroundColor:"transparent"},badge_halo:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},glass_fill:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:25},badge:{width:28,height:28,borderRadius:14,alignItems:"center",justifyContent:"center"},message:{flexShrink:1,color:"#FFFFFF",fontSize:15,lineHeight:20,fontWeight:"600"},message_android:{fontSize:14,fontWeight:"500",letterSpacing:.1,color:"#F4F4F5"},check_mark:{width:7,height:13,marginTop:-3,borderRightWidth:2.5,borderBottomWidth:2.5,borderColor:"#FFFFFF",transform:[{rotate:"45deg"}]},cross_bar:{position:"absolute",width:14,height:2.5,borderRadius:2,backgroundColor:"#FFFFFF"},cross_a:{transform:[{rotate:"45deg"}]},cross_b:{transform:[{rotate:"-45deg"}]},info_dot:{width:3,height:3,borderRadius:2,marginBottom:2,backgroundColor:"#FFFFFF"},info_bar:{width:2.5,height:10,borderRadius:2,backgroundColor:"#FFFFFF"}});import{Fragment as ko,jsx as ne,jsxs as mt}from"react/jsx-runtime";var Eo=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Di=0,Ra=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Oa=e=>{let[t,n]=Fe(0);return pe(()=>{if(!e||Ui.OS!=="ios"){n(0);return}let o=Li.addListener("keyboardWillChangeFrame",i=>n(Math.max(0,i.endCoordinates.height))),r=Li.addListener("keyboardWillHide",()=>n(0));return()=>{o.remove(),r.remove()}},[e]),t},Ia=Ro.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:l,bridge:s,opaque_background:c,allow_embedded_miniapps:a,keyboard_mode:p,onWebLoadEnd:d})=>{var C,X;let m=Ui.OS==="ios",u=m&&p!=="scroll",A=Oa(m&&p==="resize"&&t),S=Ce(null),P=Ce(!1),v=B(re,g=>g.instances[e]),M=v==null?void 0:v.app.app_id,U=v==null?void 0:v.app.manifest_url,w=v==null?void 0:v.context,V=v==null?void 0:v.url_params,z=B(Z,g=>{var _;return((_=g.active)==null?void 0:_.owner)===e?g.active:null}),[le,H]=Fe(null),[h,T]=Fe(z);z!==h&&(T(z),z?H(null):(h==null?void 0:h.layout)===be.top&&H(h));let E=(z==null?void 0:z.layout)===be.top?z:le,[b,ue]=Fe(()=>M?D(M):null),[j,F]=Fe(!1),[se,Pe]=Fe(0),[ze,Y]=Fe(0),[ke,G]=Fe(!1),de=Ce(null),Ze=g=>{de.current&&clearTimeout(de.current),de.current=setTimeout(()=>{de.current=null,G(!0)},g)};pe(()=>()=>{de.current&&clearTimeout(de.current)},[]),pe(()=>{if(!M||!t&&b)return;let g=!0;return F(!1),(async()=>{let _=D(M),ge=_?await Ue(_):!1;if(!g||(ue(ge?Se=>!Se||Se.version!==_.version||Se.permissions.join(",")!==_.permissions.join(",")?_:Se:null),__DEV__&&Date.now()-Di>1e4&&(Di=Date.now(),await Kn()),!g))return;let je=await dn(M),tt=je!==void 0?je:U?await Ar(M,U):D(M);if(g){if(!tt){F(!0);return}ue(Se=>Se!=null?Se:tt)}})(),()=>{g=!1}},[t,M,U,se]),pe(()=>ui(e,g=>S.current?(S.current.postMessage(g),!0):!1),[e]);let St=B(I,g=>{let _=M?g.downloads[M]:void 0;return(_==null?void 0:_.status)==="installed"?_.version:void 0});pe(()=>{if(t||!M||!b)return;let g=D(M);if(!g||g.version===b.version)return;let _=!0;return Ue(g).then(ge=>{!_||!ge||(ce(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",b.version,"\u2192",g.version),ue(g))}),()=>{_=!1}},[t,M,St,b==null?void 0:b.version]);let Xt=B(I,g=>{var _;return M&&(_=g.apply_ticks[M])!=null?_:0});pe(()=>{if(!Xt||!M)return;let g=D(M);if(!g||g.version===(b==null?void 0:b.version))return;let _=!0;return Ue(g).then(ge=>{!_||!ge||(ce(`webview:${e}`,"c\u1EADp nh\u1EADt",b==null?void 0:b.version,"\u2192",g.version),G(!1),ue(g))}),()=>{_=!1}},[Xt]),pe(()=>{var ge;let g=(ge=R().keep_alive)==null?void 0:ge.idle_close_ms;if(t||!g||g<=0)return;let _=setTimeout(()=>{an(e)},g);return()=>clearTimeout(_)},[t,e]),pe(()=>{r>0&&(F(!1),G(!1),Y(g=>g+1),Pe(g=>g+1))},[r]);let Qt=Ce(t);pe(()=>{var g;Qt.current!==t&&(Qt.current=t,P.current&&((g=S.current)==null||g.injectJavaScript(oi(t?"resumed":"paused"))))},[t]);let $e=`${(C=b==null?void 0:b.version)!=null?C:"none"}:${(X=b==null?void 0:b.permissions.join(","))!=null?X:""}:${ze}`,We=Cn(()=>JSON.stringify([w!=null?w:{},V!=null?V:{}]),[w,V]),et=Cn(()=>{var g;return li(V!=null?V:{},(g=b==null?void 0:b.permissions)!=null?g:[])},[We,b==null?void 0:b.permissions]),Ln=Cn(()=>si(w!=null?w:{},et,{keyboard_mode:u?p:void 0})+ti()+ni()+(R().debug?ei():""),[et]),ct=Ce(null),Zt=Ce(null);pe(()=>{var _,ge,je;if(!b)return;if(Zt.current!==$e){Zt.current=$e,ct.current=We;return}if(ct.current===We)return;let g=((ge=JSON.parse((_=ct.current)!=null?_:"[]")[0])!=null?ge:{}).org_id;if(ct.current=We,g===(w==null?void 0:w.org_id)&&P.current){G(!1),Ze(1500),(je=S.current)==null||je.injectJavaScript(ri(w!=null?w:{},et));return}G(!1),Y(tt=>tt+1)},[We,b,$e]),pe(()=>(t||(qe(e),Xe(e),rt(e)),()=>{qe(e),Xe(e),rt(e)}),[t,e,$e,r]),pe(()=>{let g=Fi.addEventListener("change",_=>{_==="background"&&!Lr()&&qe(e),_==="background"&&!Hr()&&Xe(e)});return()=>g.remove()},[e]);let en=To(async g=>{var ge,je,tt,Se,Dn,zo;let _=Yr(g.nativeEvent.data);if(!_){if(M&&Ai(g.nativeEvent.data,{app_id:M,instance_id:e},s==null?void 0:s.agent))return;if(M&&(s!=null&&s.onWebEvent))try{Promise.resolve(s.onWebEvent(g.nativeEvent.data,{app_id:M,instance_id:e})).catch(W=>{console.warn("[miniapp] onWebEvent l\u1ED7i",M,W)})}catch(W){console.warn("[miniapp] onWebEvent l\u1ED7i",M,W)}return}if(_.method==="log"){let{level:W,text:J}=_;ce(`web:${e}`,W!=null?W:"log",J!=null?J:"");return}if(_.method==="pong"){de.current||G(!0);return}if(_.method==="touchAtTop"){i.emit(!!_.at_top);return}if(_.method==="contextApplied"){de.current&&clearTimeout(de.current),de.current=null,G(!0);return}if(_.method==="ready"){P.current=!0,G(!0);let W=(ge=re.getState().instances[e])==null?void 0:ge.context;W&&((je=S.current)==null||je.injectJavaScript(yo(W)));return}try{let W=await pi(_,{getHostData:()=>{var J,ye;return(ye=(J=re.getState().instances[e])==null?void 0:J.host_data)!=null?ye:{}},getPermissions:()=>{var J,ye;return M?(ye=(J=D(M))==null?void 0:J.permissions)!=null?ye:[]:[]},getContext:()=>{var J,ye;return(ye=(J=re.getState().instances[e])==null?void 0:J.context)!=null?ye:{}},is_dark:o,close:Rt,app_id:M!=null?M:"",instance_id:e,options:s,emit:(J,ye)=>{var $o;($o=S.current)==null||$o.injectJavaScript(Zr(J,ye))},playBeep:(tt=s==null?void 0:s.playScannerBeep)!=null?tt:(()=>{var J;(J=S.current)==null||J.injectJavaScript(ci())}),isActive:()=>re.getState().active_key===e&&Fi.currentState!=="background"});_.id&&((Se=S.current)==null||Se.injectJavaScript(Xr(_.id,W)))}catch(W){if(!_.id)return;let J=W==null?void 0:W.code,ye=W instanceof f?W:new f(typeof J=="string"?J:"HOST_ERROR",String((Dn=W==null?void 0:W.message)!=null?Dn:W));(zo=S.current)==null||zo.injectJavaScript(Qr(_.id,ye))}},[e,o,M,i,s]),tn=To(()=>{F(!1),Y(g=>g+1),Pe(g=>g+1)},[]);return mt(Po,{style:[Oo.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&we.behind],pointerEvents:t?"auto":"none",children:[E&&ne(Mo,{scanner:E,closing:E===le,onClosed:()=>{var g;H(null),E.absolute&&((g=S.current)==null||g.injectJavaScript(_o(0)))},onHeight:E.absolute?g=>{var _;return(_=S.current)==null?void 0:_.injectJavaScript(_o(g))}:void 0}),b?ne(ka,{ref:S,source:{uri:b.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${a?Hn():b.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ln,onMessage:en,onShouldStartLoadWithRequest:g=>{let _=g.url;return g.isTopFrame===!1||!/^https?:\/\//i.test(_)?!0:(Promise.resolve(s!=null&&s.openUrl?s.openUrl(_):Ta.openURL(_)).catch(()=>{}),!1)},setSupportMultipleWindows:!1,bounces:!1,overScrollMode:"never",scrollEnabled:!u,onLoadStart:g=>{qe(e),Xe(e),rt(e),ce(`webview:${e}`,"load start",Eo(g.nativeEvent.url)),P.current=!1,G(!1)},onError:g=>{qe(e),Xe(e),rt(e),ce(`webview:${e}`,"load error",Eo(g.nativeEvent.url),g.nativeEvent.description),F(!0),G(!1)},onLoadEnd:g=>{let _=g.nativeEvent.url;ce(`webview:${e}`,"load end",Eo(_)),M&&(d==null||d({app_id:M,instance_id:e,url:_})),Ze(1500)},onContentProcessDidTerminate:()=>{qe(e),Xe(e),rt(e),P.current=!1,G(!1),Y(g=>g+1)},onRenderProcessGone:()=>(qe(e),Xe(e),rt(e),P.current=!1,G(!1),Y(g=>g+1),!0),style:[we.webview,A>0&&{marginBottom:A}]},$e):null,(z==null?void 0:z.layout)===be.full&&ne(Mo,{scanner:z}),v&&ne(La,{visible:!b||!ke,interactive:j,children:ne(Fa,{splash:l,app:v.app,is_dark:o,error:j,has_bundle:!!b,retry:tn})})]})}),Fa=Ro.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let l=e,s=It(t.app_id),c=o?"error":!r&&(s==null?void 0:s.status)==="downloading"?"downloading":"loading";return ne(l,{app:t,is_dark:n,status:c,progress:c==="downloading"?s==null?void 0:s.progress:void 0,retry:i})}),La=({visible:e,interactive:t,children:n})=>{let o=Ce(new Co.Value(e?1:0)).current,[r,i]=Fe(e);return pe(()=>{if(e){i(!0),o.setValue(1);return}let l=Co.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return l.start(({finished:s})=>{s&&i(!1)}),()=>l.stop()},[e,o]),r?ne(Co.View,{style:[Oo.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},Vi=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return mt(Po,{style:[we.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[ne(Po,{style:[we.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?ne(Ea,{source:{uri:e.icon},style:we.splash_icon_image}):ne(Kt,{style:we.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),ne(Kt,{style:[we.splash_name,{color:i}],children:e.name}),n==="error"?mt(ko,{children:[ne(Kt,{style:we.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),ne(Pa,{activeOpacity:.7,style:[we.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:ne(Kt,{style:[we.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):mt(ko,{children:[ne(xa,{style:we.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&mt(Kt,{style:we.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},Ni=(e,t)=>{let n=Ce(t),o=Ce(!1);__DEV__&&!o.current&&n.current!==t&&(o.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.`))},Da=({container:e,splash:t=Vi,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:l=!1,keyboard_mode:s="scroll",onWebLoadEnd:c})=>{Ni("container",e),Ni("splash",t);let a=e,p=B(re,w=>w.active_key),d=Ce(p);p&&(d.current=p);let m=B(re,w=>Object.keys(w.instances).join("|")),u=B(re,w=>{var V;return w.active_key?(V=w.instances[w.active_key])==null?void 0:V.app.name:void 0}),A=Cn(()=>m?m.split("|"):[],[m]),[S,P]=Fe({}),v=Ce(Ra()).current,M=o==null?void 0:o.agent;pe(()=>M?Si(M):void 0,[M]),pe(()=>{if(!p||!r)return;let w=Ca.addEventListener("hardwareBackPress",()=>(Rt(),!0));return()=>w.remove()},[p,r]);let U=To(()=>{let w=re.getState().active_key;w&&P(V=>({...V,[w]:(V[w]||0)+1}))},[]);return A.length?mt(ko,{children:[ne(a,{visible:!!p,title:u!=null?u:"",is_dark:n,close:Rt,reload:U,subscribeWebAtTop:v.subscribe,children:A.map(w=>ne(Ia,{instance_key:w,is_active:p===w,is_front:(p!=null?p:d.current)===w,is_dark:n,reload_tick:S[w]||0,web_at_top:v,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:l,keyboard_mode:s,onWebLoadEnd:c},w))}),ne(Ii,{})]}):null},we=Oo.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"}}),Na=Ro.memo(Da);import hl,{useRef as fl,useState as Gi}from"react";import{useEffect as al,useRef as Wi,useState as Bo}from"react";import{Animated as wt,Image as ll,Modal as qo,Pressable as cl,ScrollView as pl,StyleSheet as ul,Text as me,TouchableOpacity as Ho,View as Ne}from"react-native";import{Linking as Ga,Text as at,View as _t}from"react-native";var Ua=/\*\*(.+?)\*\*|`([^`]+)`|\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,En=e=>{var o;let t=[],n=0;for(let r of e.matchAll(Ua)){let i=(o=r.index)!=null?o:0;i>n&&t.push({type:"text",text:e.slice(n,i)}),r[1]!==void 0?t.push({type:"bold",text:r[1]}):r[2]!==void 0?t.push({type:"code",text:r[2]}):t.push({type:"link",text:r[3],url:r[4]}),n=i+r[0].length}return n<e.length&&t.push({type:"text",text:e.slice(n)}),t},Va=e=>En(e).map(t=>t.text).join("");import{Platform as No,StyleSheet as Do}from"react-native";import{createContext as Ba,useContext as Ha,useMemo as qa}from"react";import{jsx as ja}from"react/jsx-runtime";var Fo={changelog_title:"C\xF3 g\xEC m\u1EDBi",changelog_ok:"\u0110\xE3 hi\u1EC3u",changelog_view_all:"Xem t\u1EA5t c\u1EA3 c\u1EADp nh\u1EADt",changelog_more:"+{count} thay \u0111\u1ED5i kh\xE1c",history_title:"L\u1ECBch s\u1EED c\u1EADp nh\u1EADt",history_empty:"Ch\u01B0a c\xF3 ghi ch\xFA c\u1EADp nh\u1EADt.",history_error:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c l\u1ECBch s\u1EED c\u1EADp nh\u1EADt.",retry:"Th\u1EED l\u1EA1i",update_title:"\u0110\xE3 c\xF3 b\u1EA3n c\u1EADp nh\u1EADt",updating_title:"\u0110ang c\u1EADp nh\u1EADt\u2026",update_message:`Phi\xEAn b\u1EA3n {next} \u0111\xE3 s\u1EB5n s\xE0ng (hi\u1EC7n t\u1EA1i {current}).
89
+ Vui l\xF2ng c\u1EADp nh\u1EADt \u0111\u1EC3 ti\u1EBFp t\u1EE5c s\u1EED d\u1EE5ng.`,update_failed:"C\u1EADp nh\u1EADt kh\xF4ng th\xE0nh c\xF4ng. Ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng r\u1ED3i th\u1EED l\u1EA1i.",update_now:"C\u1EADp nh\u1EADt ngay",updating_hint:"Vui l\xF2ng kh\xF4ng t\u1EAFt \u1EE9ng d\u1EE5ng",date_locale:"vi-VN"},Tn=(e,t)=>e.replace(/\{(\w+)\}/g,(n,o)=>o in t?String(t[o]):n),Lo=[{key:"new",label:"M\u1EDBi",color:"#007AFF",bg:"#E5F1FF"},{key:"fix",label:"S\u1EEDa l\u1ED7i",color:"#C4320A",bg:"#FFF1EB"},{key:"improve",label:"C\u1EA3i thi\u1EC7n",color:"#067647",bg:"#E7F7EE"}],Le={primary:"#007AFF",on_primary:"#FFFFFF",background:"#F2F2F7",surface:"#FFFFFF",text:"#1C1C1E",text_secondary:"#666666",hint:"#AEAEB2",overlay:"rgba(0, 0, 0, 0.6)",divider:"rgba(60, 60, 67, 0.18)",radius:28,button_radius:12,button_height:50},za={primary:"#0A84FF",on_primary:"#FFFFFF",background:"#000000",surface:"#1C1C1E",text:"#FFFFFF",text_secondary:"#A1A1AA",hint:"#636366",overlay:"rgba(0, 0, 0, 0.7)",divider:"rgba(84, 84, 88, 0.6)",radius:28,button_radius:12,button_height:50},$a={new:{color:"#64B5FF",bg:"rgba(10, 132, 255, 0.18)"},fix:{color:"#FF9F7A",bg:"rgba(255, 112, 67, 0.18)"},improve:{color:"#5FD39A",bg:"rgba(48, 209, 88, 0.18)"}},Io=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Pn=(e={},t)=>{let{kinds:n,dark:o=!1,...r}=e;return{...o?za:Le,...Io(r),dark:o,labels:{...Fo,...Io(t!=null?t:{})},kinds:Lo.map(i=>{var l;return{...i,...o?$a[i.key]:null,...i.key==="new"&&e.primary?{color:e.primary}:null,...Io((l=n==null?void 0:n[i.key])!=null?l:{})}})}},Bi=Ba(void 0),Wa=Pn(),yt=({theme:e,labels:t,children:n})=>{let o=qa(()=>Pn(e,t),[e,t]);return ja(Bi.Provider,{value:o,children:n})},Ee=()=>{var e;return(e=Ha(Bi))!=null?e:Wa},kn=e=>({new:e.flatMap(t=>t.changelog.new),fix:e.flatMap(t=>t.changelog.fix),improve:e.flatMap(t=>t.changelog.improve)}),Hi=(e,t)=>{let n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString(t)};var N={blue:Le.primary,track:"#E5E5EA",overlay:Le.overlay,shadow:"#000000",title:Le.text,sub_title:Le.text_secondary,error:"#D92D20",hint:Le.hint,surface:Le.surface,background:Le.background},qi=No.select({ios:{shadowColor:N.shadow,shadowOffset:{width:0,height:10},shadowOpacity:.1,shadowRadius:20},android:{elevation:10}}),y=Do.create({overlay:{flex:1,backgroundColor:N.overlay,justifyContent:"center",alignItems:"center"},container:{width:"85%",maxWidth:340,backgroundColor:N.surface,padding:24,borderRadius:28,alignItems:"center",...qi},sheet:{width:"88%",maxWidth:380,maxHeight:"78%",backgroundColor:N.surface,borderRadius:28,overflow:"hidden",...qi},sheet_head:{alignItems:"center",paddingTop:24,paddingHorizontal:22,paddingBottom:4},sheet_name:{fontSize:13,color:N.sub_title,marginTop:4,maxWidth:"100%"},version_pill:{flexDirection:"row",alignItems:"center",gap:6,marginTop:10,paddingHorizontal:12,paddingVertical:5,borderRadius:999,backgroundColor:N.background},version_old:{fontSize:13,color:N.sub_title,fontVariant:["tabular-nums"]},version_arrow:{fontSize:13,color:N.hint},version_new:{fontSize:13,fontWeight:"700",color:N.blue,fontVariant:["tabular-nums"]},sheet_foot:{paddingHorizontal:22,paddingTop:4,paddingBottom:18},sheet_foot_divider:{borderTopWidth:Do.hairlineWidth,borderTopColor:"rgba(60, 60, 67, 0.18)"},logo:{width:64,height:64,borderRadius:16,marginBottom:20},title:{fontSize:20,fontWeight:"700",color:N.title,textAlign:"center"},sub_title:{fontSize:13,color:N.sub_title,textAlign:"center",lineHeight:18,marginTop:6},gap:{marginBottom:15},error_text:{fontSize:12,textAlign:"center",color:N.error,lineHeight:17,marginBottom:15},progress_section:{width:"100%",alignItems:"center",paddingVertical:8,marginTop:8,gap:12},progress_text:{fontSize:18,fontWeight:"700",color:N.blue},progress_track:{width:"100%",height:6,borderRadius:3,backgroundColor:N.track,overflow:"hidden"},progress_fill:{height:"100%",borderRadius:3,backgroundColor:N.blue},loading_hint:{fontSize:12,color:N.hint,textAlign:"center"},scroll:{flexGrow:0,flexShrink:1},scroll_content:{paddingHorizontal:22,paddingTop:16,paddingBottom:16},groups:{gap:18},group:{gap:8},group_head:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:2},group_count:{fontSize:12,fontWeight:"600",color:N.hint},dot:{width:5,height:5,borderRadius:3,marginTop:8},more:{fontSize:14,fontWeight:"500",color:N.blue,paddingLeft:17,paddingTop:2},badge:{alignSelf:"flex-start",paddingHorizontal:10,paddingVertical:3,borderRadius:999},badge_text:{fontSize:12,fontWeight:"700"},item:{flexDirection:"row",gap:10,paddingLeft:2},item_text:{flex:1,fontSize:15,lineHeight:21,color:N.title},md_bold:{fontWeight:"700"},md_code:{fontFamily:No.select({ios:"Menlo",default:"monospace"}),fontSize:13,backgroundColor:"#F2F2F7",color:"#3A3A3C"},md_link:{color:N.blue,textDecorationLine:"underline"},full:{width:"100%"},btn_primary:{marginTop:14,backgroundColor:N.blue,paddingVertical:14,borderRadius:12,alignItems:"center"},btn_primary_text:{color:"white",fontWeight:"600",fontSize:16},btn_secondary:{paddingTop:12,alignItems:"center"},link:{color:N.blue,fontSize:15,fontWeight:"600"},history:{flex:1,backgroundColor:N.background},float_header:{position:"absolute",top:0,left:0,right:0},header_row:{flexDirection:"row",alignItems:"center",paddingHorizontal:16,paddingTop:2,paddingBottom:8},header_title:{position:"absolute",top:2,bottom:8,alignItems:"center",justifyContent:"center"},history_title:{fontSize:15,fontWeight:"500",color:"#1C1C1E"},history_sub:{fontSize:11,color:"#71717A",marginTop:1},back_btn:{alignItems:"center",justifyContent:"center"},back_btn_fallback:{backgroundColor:N.surface,...No.select({ios:{shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.1,shadowRadius:8},default:{borderWidth:Do.hairlineWidth*2,borderColor:"rgba(0, 0, 0, 0.08)"}})},icon_layer:{position:"absolute",top:0,left:0,right:0,bottom:0,alignItems:"center",justifyContent:"center"},fade:{position:"absolute",top:0,left:0,right:0},chevron:{width:11,height:11,borderLeftWidth:2.2,borderBottomWidth:2.2,borderColor:Le.text,transform:[{rotate:"45deg"}],marginLeft:4},pressed:{opacity:.6,transform:[{scale:.94}]},history_list:{padding:16,gap:12},card:{backgroundColor:N.surface,borderRadius:16,padding:16,gap:12},card_head:{flexDirection:"row",justifyContent:"space-between",alignItems:"baseline"},version:{fontSize:16,fontWeight:"700",color:N.title},date:{fontSize:13,color:N.sub_title},loading:{marginTop:40},center:{alignItems:"center",marginTop:40,gap:12},empty:{marginTop:40}});import{jsx as Te,jsxs as Uo}from"react/jsx-runtime";var Vo=({text:e,style:t})=>{let n=Ee();return Te(at,{style:t,children:En(e.replace(/^(?:[-*•]\s+)+/,"")).map((o,r)=>{switch(o.type){case"bold":return Te(at,{style:y.md_bold,children:o.text},r);case"code":return Te(at,{style:[y.md_code,{backgroundColor:n.background,color:n.text}],children:o.text},r);case"link":return Te(at,{style:[y.md_link,{color:n.primary}],accessibilityRole:"link",onPress:()=>{Ga.openURL(o.url).catch(()=>{})},children:o.text},r);default:return o.text}})})},bt=({changelog:e,max_items:t,onMore:n})=>{let o=Ee();return Te(_t,{style:y.groups,children:o.kinds.filter(r=>e[r.key].length).map(r=>{let i=e[r.key],l=t?i.slice(0,t):i,s=i.length-l.length;return Uo(_t,{style:y.group,children:[Uo(_t,{style:y.group_head,children:[Te(_t,{style:[y.badge,{backgroundColor:r.bg}],children:Te(at,{style:[y.badge_text,{color:r.color}],children:r.label})}),Te(at,{style:[y.group_count,{color:o.hint}],children:i.length})]}),l.map((c,a)=>Uo(_t,{style:y.item,children:[Te(_t,{style:[y.dot,{backgroundColor:r.color}]}),Te(Vo,{text:c,style:[y.item_text,{color:o.text}]})]},a)),s>0&&Te(at,{style:[y.more,{color:o.primary}],onPress:n,suppressHighlighting:!0,children:Tn(o.labels.changelog_more,{count:s})})]},r.key)})})};import{useEffect as zi,useState as $i}from"react";import{ActivityIndicator as Ja,Platform as Ka,Pressable as Ya,ScrollView as Xa,StyleSheet as Qa,Text as lt,TouchableOpacity as Za,View as Ae}from"react-native";import{jsx as oe,jsxs as De}from"react/jsx-runtime";var Rn,el=()=>(Rn!=null||(Rn=Promise.all([Ka.OS==="ios"?import("expo-image").then(e=>e.Image).catch(()=>{}):Promise.resolve(void 0),import("expo-linear-gradient").then(e=>e.LinearGradient).catch(()=>{})]).then(([e,t])=>({ExpoImage:e,LinearGradient:t}))),Rn),tl=()=>{let[e,t]=$i({});return zi(()=>{let n=!0;return el().then(o=>{n&&t(o)}),()=>{n=!1}},[]),e},nl="#1C1C1E",ol=e=>/^#[0-9a-f]{6}$/i.test(e),rl=()=>{let[e,t]=$i();return zi(()=>{let n=!0;return Bt().then(o=>{n&&o&&t(()=>o)}),()=>{n=!1}},[]),e},il=({onPress:e,size:t,GlassView:n,ExpoImage:o})=>{let r=Ee(),i=r.dark?"#FFFFFF":nl;return De(Ya,{onPress:e,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"Quay l\u1EA1i",style:({pressed:l})=>[y.back_btn,{width:t,height:t,borderRadius:t/2},!n&&y.back_btn_fallback,!n&&r.dark&&{backgroundColor:"#3F3F46",shadowOpacity:0},!n&&l&&y.pressed],children:[n&&oe(n,{style:[Qa.absoluteFill,{borderRadius:t/2}],glassEffectStyle:"regular",colorScheme:r.dark?"dark":"light",isInteractive:!0}),oe(Ae,{pointerEvents:"none",style:y.icon_layer,children:o?oe(o,{source:"sf:chevron.left",transition:0,contentFit:"contain",style:{width:20,height:20,fontSize:20,color:i}}):oe(Ae,{style:[y.chevron,{borderColor:i}]})})]})},Yt=({app_id:e,name:t,onBack:n,renderHeader:o})=>{let r=Ee(),i=gt(),l=rl(),{ExpoImage:s,LinearGradient:c}=tl(),a=l?46:42,p=o?0:i.top+a+10,{versions:d,loading:m,error:u,reload:A}=Zn(e);return De(Ae,{style:[y.history,{backgroundColor:r.background}],children:[o&&oe(Ae,{style:{paddingTop:i.top},children:o({title:r.labels.history_title,subtitle:t,onBack:n})}),m&&!d.length?oe(Ja,{style:[y.loading,{marginTop:p+40}],color:r.primary}):u&&!d.length?De(Ae,{style:[y.center,{marginTop:p+40}],children:[oe(lt,{style:[y.sub_title,{color:r.text_secondary}],children:r.labels.history_error}),oe(Za,{onPress:A,children:oe(lt,{style:[y.link,{color:r.primary}],children:r.labels.retry})})]}):De(Xa,{contentContainerStyle:[y.history_list,{paddingTop:p+8,paddingBottom:i.bottom+24}],scrollIndicatorInsets:{top:p},children:[d.map(S=>De(Ae,{style:[y.card,{backgroundColor:r.surface,borderRadius:Math.max(r.radius-12,0)}],children:[De(Ae,{style:y.card_head,children:[De(lt,{style:[y.version,{color:r.text}],children:["v",S.version]}),oe(lt,{style:[y.date,{color:r.text_secondary}],children:Hi(S.created_at,r.labels.date_locale)})]}),oe(bt,{changelog:S.changelog})]},S.version)),!d.length&&oe(lt,{style:[y.sub_title,y.empty,{color:r.text_secondary}],children:r.labels.history_empty})]}),!o&&De(Ae,{pointerEvents:"box-none",style:[y.float_header,{paddingTop:i.top}],children:[c&&ol(r.background)?oe(c,{pointerEvents:"none",colors:[`${r.background}F5`,`${r.background}E6`,`${r.background}B3`,`${r.background}00`],locations:[0,.45,.75,1],style:[y.fade,{height:p+28}]}):oe(Ae,{pointerEvents:"none",style:y.fade,children:sl.map((S,P)=>oe(Ae,{style:{height:P===0?p:4,backgroundColor:r.background,opacity:S}},P))}),De(Ae,{style:y.header_row,children:[oe(il,{onPress:n,size:a,GlassView:l,ExpoImage:s}),De(Ae,{pointerEvents:"none",style:[y.header_title,{left:a+24,right:a+24}],children:[oe(lt,{style:[y.history_title,{color:r.text}],numberOfLines:1,children:r.labels.history_title}),oe(lt,{style:[y.history_sub,{color:r.text_secondary}],numberOfLines:1,children:t})]})]})]})]})},sl=[.96,.9,.8,.68,.55,.42,.3,.18,.08];import{Fragment as gl,jsx as L,jsxs as Qe}from"react/jsx-runtime";var ji=e=>({backgroundColor:e.primary,borderRadius:e.button_radius,height:e.button_height,paddingVertical:0,justifyContent:"center"}),dl=4,On=({request:e,changelog:t,onClose:n,renderHistoryHeader:o,renderActions:r})=>{var m;let i=Ee(),[l,s]=Bo(!1),[c,a]=Bo(0),[p,d]=Bo(0);return L(qo,{visible:!0,transparent:!l,animationType:l?"slide":"fade",statusBarTranslucent:!0,onRequestClose:l?()=>s(!1):n,children:l?L(Yt,{app_id:e.app_id,name:e.name,onBack:()=>s(!1),renderHeader:o}):Qe(Ne,{style:[y.overlay,{backgroundColor:i.overlay}],children:[L(cl,{style:ul.absoluteFill,onPress:n,accessibilityLabel:"\u0110\xF3ng"}),Qe(Ne,{style:[y.sheet,{backgroundColor:i.surface,borderRadius:i.radius}],children:[Qe(Ne,{style:y.sheet_head,children:[L(me,{style:[y.title,{color:i.text}],children:i.labels.changelog_title}),L(me,{style:[y.sheet_name,{color:i.text_secondary}],numberOfLines:1,children:e.name}),Qe(Ne,{style:[y.version_pill,{backgroundColor:i.background}],children:[L(me,{style:[y.version_old,{color:i.text_secondary}],children:`v${e.from}`}),L(me,{style:[y.version_arrow,{color:i.hint}],children:"\u2192"}),L(me,{style:[y.version_new,{color:i.primary}],children:`v${e.to}`})]})]}),L(pl,{style:y.scroll,contentContainerStyle:y.scroll_content,onContentSizeChange:(u,A)=>a(A),onLayout:u=>d(u.nativeEvent.layout.height),children:L(bt,{changelog:t,max_items:dl,onMore:()=>s(!0)})}),L(Ne,{style:[y.sheet_foot,c>p+1&&[y.sheet_foot_divider,{borderTopColor:i.divider}]],children:r?r({onClose:n,onViewAll:()=>s(!0),labels:i.labels}):Qe(gl,{children:[L(Ho,{style:[y.btn_primary,ji(i)],activeOpacity:.8,onPress:n,children:L(me,{style:[y.btn_primary_text,{color:i.on_primary}],children:i.labels.changelog_ok})}),L(Ho,{style:y.btn_secondary,onPress:()=>s(!0),children:L(me,{style:[y.link,{color:(m=i.secondary)!=null?m:i.primary}],children:i.labels.changelog_view_all})})]})})]})]})})},In=({update:e,is_updating:t,progress:n,has_failed:o,onUpdate:r,logo:i,renderAction:l})=>{let s=Ee(),c=Wi(new wt.Value(0)).current,a=Wi(new wt.Value(30)).current;return al(()=>{wt.parallel([wt.timing(c,{toValue:1,duration:400,useNativeDriver:!0}),wt.spring(a,{toValue:0,friction:8,tension:40,useNativeDriver:!0})]).start()},[c,a]),L(qo,{visible:!0,transparent:!0,animationType:"none",statusBarTranslucent:!0,onRequestClose:()=>{},children:L(Ne,{style:[y.overlay,{backgroundColor:s.overlay}],children:Qe(wt.View,{style:[y.container,{backgroundColor:s.surface,borderRadius:s.radius},{opacity:c,transform:[{translateY:a}]}],children:[i&&L(ll,{source:i,style:y.logo}),L(me,{style:[y.title,{color:s.text}],children:t?s.labels.updating_title:s.labels.update_title}),!t&&L(me,{style:[y.sub_title,y.gap,{color:s.text_secondary}],children:Tn(s.labels.update_message,{next:e.next_version,current:e.current_version})}),!t&&o&&L(me,{style:y.error_text,children:s.labels.update_failed}),t?Qe(Ne,{style:y.progress_section,children:[Qe(me,{style:[y.progress_text,{color:s.primary}],children:[n,"%"]}),L(Ne,{style:[y.progress_track,{backgroundColor:s.background}],children:L(Ne,{style:[y.progress_fill,{backgroundColor:s.primary,width:`${n}%`}]})}),L(me,{style:[y.loading_hint,{color:s.hint}],children:s.labels.updating_hint})]}):l?L(Ne,{style:y.full,children:l({onUpdate:r,has_failed:o,label:o?s.labels.retry:s.labels.update_now})}):L(Ho,{style:[y.btn_primary,y.full,ji(s)],activeOpacity:.8,onPress:r,children:L(me,{style:[y.btn_primary_text,{color:s.on_primary}],children:o?s.labels.retry:s.labels.update_now})})]})})})},Fn=({app_id:e,name:t,onClose:n,renderHistoryHeader:o})=>L(qo,{visible:!0,animationType:"slide",statusBarTranslucent:!0,onRequestClose:n,children:L(Yt,{app_id:e,name:t,onBack:n,renderHeader:o})});import{jsx as At}from"react/jsx-runtime";var ml=({app_ids:e,shouldShowUpdate:t,logo:n,renderUpdate:o,renderChangelog:r,theme:i,renderHistoryHeader:l,labels:s,renderChangelogActions:c,renderUpdateAction:a})=>{var z,le;let p=B(I,H=>H.updates),m=((z=e!=null?e:R().manual_update)!=null?z:[]).map(H=>p[H]).find(H=>!!H&&(!t||t(H))),u=It(m==null?void 0:m.app_id),[A,S]=Gi(!1),[P,v]=Gi(!1),M=fl(!1),U=no(),w=io(),V=async()=>{if(!m||M.current)return;M.current=!0,S(!0),v(!1);let H=await Yn(m.app_id);M.current=!1,S(!1),v(!H)};if(m){let H=(u==null?void 0:u.status)==="updating"?Math.round(((le=u.progress)!=null?le:0)*100):0,h={update:m,is_updating:A,progress:H,has_failed:P,onUpdate:V};return At(yt,{theme:i,labels:s,children:o?o(h):At(In,{...h,logo:n,renderAction:a})})}if(U){let H={request:U,changelog:kn(U.versions),onClose:to};return At(yt,{theme:i,labels:s,children:r?r(H):At(On,{...H,renderHistoryHeader:l,renderActions:c})})}return w?At(yt,{theme:i,labels:s,children:At(Fn,{...w,onClose:ro,renderHistoryHeader:l})}):null},yl=hl.memo(ml);export{hi as AGENT_BRIDGE_VERSION,fi as AGENT_MESSAGE_EVENT,yi as AGENT_PAYLOAD_META_EVENT,_i as AGENT_PAYLOAD_META_RESULT_EVENT,mi as AGENT_STOPPED_EVENT,ae as CodeType,Fo as DEFAULT_MINIAPP_UPDATES_LABELS,Fn as DefaultMiniAppChangelogHistoryModal,On as DefaultMiniAppChangelogPrompt,Vi as DefaultMiniAppSplash,In as DefaultMiniAppUpdatePrompt,Lo as MINIAPP_CHANGELOG_KINDS,Mt as MINIAPP_PLATFORM_URL,bt as MiniAppChangelogGroups,Yt as MiniAppChangelogHistory,Vo as MiniAppChangelogText,Na as MiniAppHost,f as MiniAppHostError,yl as MiniAppUpdates,yt as MiniAppUpdatesThemeProvider,dt as ScannerEndReason,po as ScannerEvent,be as ScannerLayout,Vt as ScannerMethod,Me as ToastType,Rt as closeMiniApp,ro as closeMiniAppChangelogHistory,Ji as configureMiniApp,Yi as createMmkvStorage,jo as createReactNativeBiometrics,Ki as createRnfsFileSystem,to as dismissMiniAppChangelog,dn as ensureMiniApp,hn as fetchMiniAppChangelog,D as getLocalMiniApp,qs as getMiniAppCatalog,Ft as getMiniAppCatalogEntry,Xn as getMiniAppChangelogSeen,aa as getMiniAppIdByAgentId,Is as getMiniAppStatuses,Er as getMiniAppUpdate,Qn as getPendingChangelog,Ss as installBundledMiniApp,Nt as markMiniAppChangelogSeen,kn as mergeMiniAppChangelog,Jn as onMiniAppEvent,vs as openMiniApp,En as parseInlineMarkdown,Us as pauseMiniApp,Bs as pauseMiniAppDownloads,xs as preloadMiniApp,qe as releaseSpeechFor,Pn as resolveMiniAppUpdatesTheme,Ns as restoreMiniApp,Vs as resumeMiniApp,Hs as resumeMiniAppDownloads,bo as sendEventToWeb,Dt as showMiniAppChangelog,oo as showMiniAppChangelogHistory,Va as stripInlineMarkdown,Kn as syncMiniAppCatalog,Ds as uninstallMiniApp,Yn as updateMiniApp,lr as uploadToUrl,Zn as useMiniAppChangelog,io as useMiniAppChangelogHistoryRequest,no as useMiniAppChangelogRequest,It as useMiniAppDownload,Os as useMiniAppDownloadsPaused,Ee as useMiniAppUpdatesTheme};
@@ -555,6 +555,49 @@ configureMiniApp({
555
555
 
556
556
  Mini app bị huỷ WebView vẫn còn bundle trong máy — mở lại chỉ mất thời gian khởi động trang, không tải lại.
557
557
 
558
+ ### Cầu nối Agent ↔ mini app (`bridge.agent`)
559
+
560
+ Host chỉ là **ống dẫn**: không đọc, không sửa nội dung — agent và mini app tự thống nhất format. App truyền
561
+ `bridge.agent` (nối chat của app, vd `@retion/chat-sdk`), package lo định tuyến + giao thức; mini app dùng
562
+ `onAgentMessage` / `sendPayloadMeta` / `onAgentStop` của `@retion-miniapp/sdk` (>= 0.19.0).
563
+
564
+ ```
565
+ Agent ──socket (từng gói, nguyên vẹn)──▶ provider.subscribe → emit.message ──retion.ai.message──▶ MỌI WebView
566
+ (mini app tự lọc theo app_id)
567
+ Mini app: sendPayloadMeta ──retion.ai.payload_meta──▶ provider.sendPayloadMeta ──▶ Agent
568
+ ◀──retion.ai.payload_meta_result { request_id, ok, message_mid? }──┘
569
+ User dừng ──▶ provider.subscribe → emit.stopped ──retion.ai.stopped { source }──▶ MỌI WebView
570
+ ```
571
+
572
+ ```tsx
573
+ import type { MiniAppAgentProvider } from '@retion-miniapp/react-native';
574
+ import { onAgentSocketMessage, onAgentStop, sendAgentPayloadMetaMessage } from '@retion/chat-sdk';
575
+
576
+ // Khai báo ngoài component → reference ổn định
577
+ const AGENT_PROVIDER: MiniAppAgentProvider = {
578
+ sendPayloadMeta: ({ agent_id, text, payload_meta }) =>
579
+ sendAgentPayloadMetaMessage(payload_meta, { text, agent_id }),
580
+ subscribe: (emit) => {
581
+ const off_message = onAgentSocketMessage(({ agent_id, fb_client_id, raw }) => emit.message({ agent_id, fb_client_id, raw }));
582
+ const off_stop = onAgentStop((source) => { if (source !== 'internal') {emit.stopped({ source });} });
583
+ return () => { off_message(); off_stop(); };
584
+ },
585
+ };
586
+
587
+ <MiniAppHost container={…} bridge={{ …, agent: AGENT_PROVIDER }} />
588
+ ```
589
+
590
+ - **Định tuyến:** host ghi nhận agent → app + WebView từ `retion.ai.agent` (mini app gọi `setAgent`), gửi event
591
+ thẳng tới các WebView đã báo agent đó — không gửi cho mini app khác (gói socket chứa nội dung hội thoại). Agent
592
+ chưa mini app nào báo → không gửi. Dừng không rõ agent → gắn agent báo `setAgent` gần nhất.
593
+ - **`payload_meta`:** host kiểm tra là object rồi gọi `provider.sendPayloadMeta`, trả kết quả cho đúng WebView theo
594
+ `request_id`. Không có provider → `{ ok: false, error: 'unsupported' }`; sai kiểu → `'invalid'`; provider throw →
595
+ `'send_failed'`. `retion.ai.payload_meta` không chuyển cho `onWebEvent`; `retion.ai.agent` vẫn chuyển như cũ.
596
+ - **Phiên bản:** mọi event có `v` (`AGENT_BRIDGE_VERSION`). Bên nhận gặp `type` lạ thì bỏ qua.
597
+ - **Log:** `[miniapp:agent]` (chỉ bản dev `__DEV__`) — ghi nhận agent, số WebView nhận event, payload_meta vào / kết quả.
598
+ - Export: `AGENT_BRIDGE_VERSION`, `AGENT_MESSAGE_EVENT`, `AGENT_STOPPED_EVENT`, `AGENT_PAYLOAD_META_EVENT`,
599
+ `AGENT_PAYLOAD_META_RESULT_EVENT`, `getMiniAppIdByAgentId`, type `MiniAppAgentProvider` / `MiniAppAgentSendResult`.
600
+
558
601
  ### Token và quyền
559
602
 
560
603
  - `access_token` luôn trả cho web.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.23.1",
3
+ "version": "0.23.2",
4
4
  "description": "React Native host for Retion Mini Apps with built-in biometric authentication",
5
5
  "license": "MIT",
6
6
  "repository": {