@retion-miniapp/react-native 0.13.1 → 0.13.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 Ko=Object.create;var ut=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Xo=Object.getOwnPropertyNames;var Zo=Object.getPrototypeOf,Qo=Object.prototype.hasOwnProperty;var er=(e,t)=>{for(var n in t)ut(e,n,{get:t[n],enumerable:!0})},pn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Xo(t))!Qo.call(e,r)&&r!==n&&ut(e,r,{get:()=>t[r],enumerable:!(o=Yo(t,r))||o.enumerable});return e};var le=(e,t,n)=>(n=e!=null?Ko(Zo(e)):{},pn(t||!e||!e.__esModule?ut(n,"default",{value:e,enumerable:!0}):n,e)),tr=e=>pn(ut({},"__esModule",{value:!0}),e);var ei={};er(ei,{CodeType:()=>Z,DefaultMiniAppSplash:()=>cn,MINIAPP_PLATFORM_URL:()=>dt,MiniAppHost:()=>Go,MiniAppHostError:()=>g,ScannerEndReason:()=>Be,ScannerEvent:()=>wt,ScannerLayout:()=>ve,ScannerMethod:()=>ze,ToastType:()=>ue,closeMiniApp:()=>He,configureMiniApp:()=>dn,createMmkvStorage:()=>fn,createReactNativeBiometrics:()=>Lt,createRnfsFileSystem:()=>mn,ensureMiniApp:()=>lt,getLocalMiniApp:()=>U,getMiniAppCatalog:()=>Wo,getMiniAppCatalogEntry:()=>Je,getMiniAppStatuses:()=>Fo,getMiniAppUpdate:()=>sn,installBundledMiniApp:()=>wo,onMiniAppEvent:()=>Lo,openMiniApp:()=>To,pauseMiniApp:()=>Vo,pauseMiniAppDownloads:()=>qo,preloadMiniApp:()=>Po,releaseSpeechFor:()=>Se,restoreMiniApp:()=>Uo,resumeMiniApp:()=>Bo,resumeMiniAppDownloads:()=>$o,sendEventToWeb:()=>Ao,syncMiniAppCatalog:()=>Ot,uninstallMiniApp:()=>No,updateMiniApp:()=>zo,uploadToUrl:()=>Ut,useMiniAppDownload:()=>Pt,useMiniAppDownloadsPaused:()=>Io});module.exports=tr(ei);var dt="https://retion-miniapp-platform.vercel.app",Ne=null,un=new Set,dn=e=>{Ne=e,un.forEach(t=>t())},B=()=>{if(!Ne)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Ne},gn=e=>{un.add(e),Ne&&e()},pe=(...e)=>{Ne!=null&&Ne.debug&&console.log("[miniapp]",...e)};var mn=(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:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:c})=>r==null?void 0:r(l,c)});return{promise:a.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(i)}}}),fn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var A=le(require("react")),k=require("react-native"),Jo=le(require("react-native-webview"));var nt=require("react-native");var Lt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),gt,Ft=()=>(gt||(gt=import("react-native-biometrics").then(({default:e})=>Lt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw gt=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),gt);var Ae=require("react-native");var hn=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("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 g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,l]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<a||c>l))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${l} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},yn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,s)=>{r||(r=!0,clearTimeout(a),c?o(c):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),l=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!l())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(l()){if(Ae.Platform.OS==="android"){let s=Ae.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ae.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,m=await Ae.PermissionsAndroid.check(s);if(!l())return;let y=m||await Ae.PermissionsAndroid.check(d);if(!l())return;if(!m&&!y){let u=await Ae.PermissionsAndroid.requestMultiple([s,d]);if(!l())return;if(u[s]!==Ae.PermissionsAndroid.RESULTS.GRANTED&&u[d]!==Ae.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}l()&&c.getCurrentPosition(s=>{l()&&i(void 0,s)},s=>{var m;if(!l())return;let d=(m={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?m:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(c=>i(c))});var Nt=require("react-native");var Dt=20,wn=20,Mn=/^[a-z][a-z0-9_-]{0,31}$/,nr=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,or=["low","medium","high"],Te=e=>!!e&&typeof e=="object"&&!Array.isArray(e),G=e=>new g("INVALID_PARAMS",e),Qe=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,_n=(e,t)=>{if(e===void 0)return{};if(!Te(e)||Object.keys(e).length>wn||Object.values(e).some(n=>typeof n!="string"))throw G(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${wn} key)`);return e},xn=e=>{var n,o,r,i;if(e!==void 0&&!Te(e))throw G("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Mn.test(t.source)))throw G("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!nr.test(a))))throw G("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Qe(t.max_count,1,Dt))throw G(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Dt}`);if(t.max_size!==void 0&&!Qe(t.max_size,1,Number.MAX_SAFE_INTEGER))throw G("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Qe(t.concurrency,1,5))throw G("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(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:rr(t.process),target:ir(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},rr=e=>{if(e===void 0)return{};if(!Te(e))throw G("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Te(n))throw G("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Qe(n[o],1,1e4))throw G(`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 G("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(!Te(n))throw G("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Qe(n.max_duration,1,3600))throw G("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!or.includes(n.quality))throw G("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},ir=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Te(e))throw G("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Mn.test(t))throw G("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Te(e.params))throw G("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 G("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw G(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:_n(e.headers,"upload.headers"),form_data:_n(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},En=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},sr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=En(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},ar=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"},Ye,cr=()=>(Ye!=null||(Ye=import("react-native-image-picker").catch(e=>{throw Ye=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ye),bn=e=>async({accept:t,max_count:n,process:o})=>{var c,s,d,m,y,u,w,C,M;let r=await cr(),i=ar(t),a={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(m=(d=o.image)==null?void 0:d.quality)!=null?m:.8,videoQuality:(u=(y=o.video)==null?void 0:y.quality)!=null?u:"medium",durationLimit:(w=o.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},l=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(l.didCancel)return[];if(l.errorCode){let T=l.errorCode==="permission"?"PERMISSION_DENIED":l.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(T,(C=l.errorMessage)!=null?C:l.errorCode)}return((M=l.assets)!=null?M:[]).filter(T=>T.uri).map((T,x)=>{var b,Q,ee;return{uri:T.uri,name:(b=T.fileName)!=null?b:`file_${x+1}`,mime_type:(Q=T.type)!=null?Q:"application/octet-stream",size:T.fileSize,width:T.width,height:T.height,duration:T.duration,processed:!((ee=T.type)!=null&&ee.startsWith("video/"))||Nt.Platform.OS==="ios"}})},lr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},pr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},ur=e=>async({accept:t,max_count:n})=>{var i,a,l,c;let o=t.map(s=>{var d;return(d=lr[s])!=null?d:pr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,w)=>{var C,M,T;return{uri:u.uri,name:(C=u.name)!=null?C:`file_${w+1}`,mime_type:(M=u.type)!=null?M:"application/octet-stream",size:(T=u.size)!=null?T:void 0}});if(Nt.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(u=>u.uri.startsWith("content://")))return d;let m=await e.keepLocalCopy({files:d.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),y=new Map(m.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return d.map(u=>{var w;return{...u,uri:(w=y.get(u.uri))!=null?w:u.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((c=(l=e.errorCodes)==null?void 0:l.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Xe,dr=async e=>(Xe!=null||(Xe=import("@react-native-documents/picker").then(t=>ur(t)).catch(t=>{throw Xe=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Xe)(e)),Rn={library:bn("library"),camera:bn("camera"),document:dr},An={type:"image",label:"\u1EA2nh",accept:["image/*"]},Sn={type:"video",label:"Video",accept:["video/*"]},vn={library:[An,Sn],camera:[An,Sn],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"]}]},Ze,Tn=()=>(Ze!=null||(Ze=import("react-native-compressor").catch(()=>(Ze=void 0,null))),Ze),Pn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},gr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),mr={low:640,medium:1280,high:1920},fr=async(e,{image:t})=>{var o;if(!t||!gr.has(e.mime_type.toLowerCase()))return e;let n=await Tn();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 Pn(n,r,e.size),processed:!0}}catch{return e}},hr=async(e,{video:t})=>{var o;let n=await Tn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:mr[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Pn(n,r,e.size),processed:!0}}catch{return e}},yr={image:fr,video:hr},wr=(e,t)=>t.split(".").reduce((n,o)=>Te(n)?n[o]:void 0,e),Ut=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let l=new XMLHttpRequest,c=new FormData;Object.entries(a.form_data).forEach(([m,y])=>c.append(m,y)),c.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>l.abort();o.addEventListener("abort",s);let d=m=>{o.removeEventListener("abort",s),m()};l.open("POST",a.url),Object.entries(a.headers).forEach(([m,y])=>l.setRequestHeader(m,y)),l.upload.onprogress=m=>n(m.loaded,m.total||e.size||0),l.onload=()=>d(()=>{let m=l.responseText;try{m=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${l.status}`));return}let y=wr(m,a.url_field);if(typeof y!="string"||!y){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:y,response:m})}),l.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),l.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),l.send(c)}),Cn=e=>{var o,r;let t={...Rn};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Ut};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},On=e=>{let{sources:t,targets:n}=Cn(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Rn[i]&&vn[i]).map(i=>[i,vn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Dt}},ft=new Map,kn=(e,t)=>`${e}:${t}`,_r=0,In=(e,t)=>{var n;typeof t=="string"&&((n=ft.get(kn(e,t)))==null||n.abort())},Ue=e=>{for(let[t,n]of ft)t.startsWith(`${e}:`)&&n.abort()},mt=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),br=(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)}},Ln=async(e,t)=>{var c;let{sources:n,targets:o}=Cn(t.config),r=n[e.source];if(!r)throw new g("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 g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,l=kn(t.instance_id,(c=t.task_id)!=null?c:`auto-${++_r}`);ft.set(l,a);try{return await Ar(e,t,r,i,a.signal)}finally{ft.delete(l)}},Ar=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:l=m=>m()},c,s,d)=>{var h,E,j;let m={app_id:n!=null?n:"",instance_id:t,context:{...(h=o==null?void 0:o())!=null?h:{}}},y=(await l(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:m}))).slice(0,e.max_count);if(d.aborted)throw mt();if(!y.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],w=y.filter(P=>sr(P,e.accept)?!0:(u.push({name:P.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${P.mime_type||En(P.name)}`}),!1)),C=w.map(()=>0),M=w.map(P=>{var L;return(L=P.size)!=null?L:0}),T=0,x=0,b=(P=!1)=>{if(!a||!r)return;let L=Date.now();if(!P&&L-x<200)return;x=L;let V=M.reduce((D,te)=>D+te,0),z=C.reduce((D,te)=>D+te,0);a("upload.progress",{task_id:r,loaded:z,total:V,percent:V?Math.min(100,Math.round(z/V*100)):0,done_count:T,count:w.length})},Q=[],ee=0,oe=async()=>{var P,L,V;for(;ee<w.length;){let z=ee++,D=w[z];try{if(d.aborted)throw mt();let te=D.mime_type.startsWith("image/")?"image":D.mime_type.startsWith("video/")?"video":void 0,Le=te&&!D.processed?(L=(P=i==null?void 0:i.processors)==null?void 0:P[te])!=null?L:yr[te]:void 0;if(Le&&(D=await Le(D,e.process),M[z]=(V=D.size)!=null?V:M[z],d.aborted))throw mt();if(e.max_size&&D.size&&D.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${D.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let fe=(Re,Fe)=>{C[z]=Re,Fe&&(M[z]=Fe),b()},ne=await s({file:D,target:e.target,onProgress:fe,signal:d,caller:m});if(typeof(ne==null?void 0:ne.url)!="string"||!ne.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Ee,...be}=ne;Q[z]={url:Ee,name:D.name,mime_type:D.mime_type,size:D.size,width:D.width,height:D.height,duration:D.duration,...Object.keys(be).length?{response:"response"in be?be.response:be}:{}},C[z]=M[z]}catch(te){u.push(br(w[z].name,te))}finally{T++,b(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,w.length)},oe)),d.aborted)throw mt();let _e=Q.filter(P=>!!P);if(!_e.length){let P=u[0];throw new g((E=P==null?void 0:P.code)!=null?E:"UPLOAD_FAILED",(j=P==null?void 0:P.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:_e,failed:u}};var ht=require("react"),Pe=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)})}},W=(e,t,n=Object.is)=>{let o=(0,ht.useRef)(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let l=t(i),c=a&&n(a.value,l)?a.value:l;return o.current={state:i,selector:t,value:c},c};return(0,ht.useSyncExternalStore)(e.subscribe,r)};var ue={info:"info",success:"success",error:"error"},Sr=200,Fn={info:2e3,success:2e3,error:3e3},et=Pe({message:"",type:ue.info,tick:0}),Dn=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,Sr);return o?{message:o,type:Object.values(ue).includes(n)?n:ue.info}:null},Nn=(e,t=ue.info)=>{et.setState(n=>({message:e,type:t,tick:n.tick+1}))};var qt=require("react-native");var Ve=require("react-native");var de,Un=()=>Ve.Platform.OS==="android"&&!!(de!=null&&de.requesting_permission),vr=1500,yt=()=>new Promise(e=>{if(Ve.Platform.OS!=="android"||Ve.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,vr),o=Ve.AppState.addEventListener("change",r=>{r==="active"&&t()})}),Vt=e=>{var t;if(de===e&&(de=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Ve.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Vn=async(e,t,n,o=()=>!0)=>{var i,a,l,c,s;if(de)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};de=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let m=d.ExpoSpeechRecognitionModule;if(r.native=m,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await m.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await yt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await m.getStateAsync()!=="inactive")throw new g("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 g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(m.addListener("result",u=>{var w,C;de!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(C=(w=u.results[0])==null?void 0:w.transcript)!=null?C:""})}),m.addListener("error",u=>{de===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),m.addListener("end",()=>{de===r&&(Vt(r),n("speech.end"))})),r.started=!0,m.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(l=t.interimResults)!=null?l:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Vt(r),d}},Bn=e=>{let t=de;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Se=e=>{let t=de;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Vt(t)}};var qn={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"},Z={...qn,all:Object.values(qn)},ze={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},wt={result:"scanner.result",end:"scanner.end"},Be={user:"user",web:"web",closed:"closed",error:"error"},ve={top:"top",full:"full"},qe={once:"once",continuous:"continuous"},Mr=1500,$n=6e4,N,K=Pe({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Wn=()=>qt.Platform.OS==="android"&&!!(N!=null&&N.requesting_permission),$t=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r}=e!=null?e:{},i={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(a=>Z.all.includes(a)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");i.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>$n)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${$n}`);i.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");i.hint=o}if(r!==void 0){if(!Object.values(ve).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");i.layout=r}return i},zt=e=>N!==e?!1:(N=void 0,K.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),jn=async(e,t)=>{if(N)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");N=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n(),e.requesting_permission=!0;let r;try{r=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await yt(),n(),r!=="granted")throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera");if(!o.Camera.getAvailableCameraDevices().some(a=>a.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await Wt();n(),K.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw zt(e),o}},Wt=async()=>{if(qt.Platform.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},Hn=(e,t,n)=>{var o,r,i;return{owner:e,mode:t,types:(o=n.types)!=null?o:Z.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Mr,hint:n.hint,layout:t===qe.once?ve.full:(i=n.layout)!=null?i:ve.top,cancelled:!1,requesting_permission:!1,last_seen:new Map}},Jn=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=Hn(e,qe.once,t);a.onHit=o,a.resolve=r,a.reject=i,jn(a,n).catch(i)}),Gn=(e,t,n,o=()=>!0,r)=>{let i=Hn(e,qe.continuous,t);return i.emit=n,i.onHit=r,jn(i,o)},_t=(e,t,n)=>{var o,r;if(!K.getState().active){e.cancelled=!0;return}if(zt(e)){if(e.mode===qe.once){(o=e.reject)==null||o.call(e,t===Be.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,wt.end,n?{reason:t,message:n}:{reason:t})}},Kn=e=>{(N==null?void 0:N.owner)===e&&_t(N,Be.web)},Ce=e=>{(N==null?void 0:N.owner)===e&&_t(N,Be.closed)},jt=()=>{N&&_t(N,Be.user)},Yn=e=>{N&&_t(N,Be.error,e)},Ht=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=N;if(!(!o||!K.getState().active))for(let{value:l,type:c}of e){if(!l)continue;let s=o.last_seen.get(l);if(o.last_seen.set(l,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===qe.once){zt(o),(i=o.resolve)==null||i.call(o,{value:l,type:c});return}K.setState(d=>({last_value:l,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,wt.result,{value:l,type:c})}}},xr={1:Z.code128,2:Z.code39,4:Z.code93,8:Z.codabar,16:Z.dataMatrix,32:Z.ean13,64:Z.ean8,128:Z.itf,256:Z.qr,512:Z.upcA,1024:Z.upcE,2048:Z.pdf417,4096:Z.aztec},Er=2500,zn=2e3,Bt=e=>{K.setState({notice:e}),setTimeout(()=>{K.getState().notice===e&&K.setState({notice:null})},Er)},Xn=async()=>{var t,n;let e=N;if(!(!e||K.getState().is_picking)){e.requesting_permission=!0,K.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:zn,maxHeight:zn}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||N!==e)return;if(r.errorCode||!i){Bt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),l=await a.scan(i);if(N!==e)return;let c=l.map(({value:s,format:d})=>({value:s,code_type:xr[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!c.length){Bt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}Ht(c,Date.now(),!0)}catch{N===e&&Bt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await yt(),e.requesting_permission=!1,N===e&&K.setState({is_picking:!1})}}};var At=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},Zn=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===At&&typeof t.method=="string"?t:null}catch{return null}},ot=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Qn=(e,t)=>ot({id:e,result:t}),eo=(e,t)=>ot({id:e,error:{code:t.code,message:t.message}}),to=(e,t)=>ot({event:e,data:t}),Gt=e=>ot({event:"context",data:e});var no=()=>`(function () {
1
+ "use strict";var Ko=Object.create;var dt=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Xo=Object.getOwnPropertyNames;var Zo=Object.getPrototypeOf,Qo=Object.prototype.hasOwnProperty;var er=(e,t)=>{for(var n in t)dt(e,n,{get:t[n],enumerable:!0})},pn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Xo(t))!Qo.call(e,r)&&r!==n&&dt(e,r,{get:()=>t[r],enumerable:!(o=Yo(t,r))||o.enumerable});return e};var le=(e,t,n)=>(n=e!=null?Ko(Zo(e)):{},pn(t||!e||!e.__esModule?dt(n,"default",{value:e,enumerable:!0}):n,e)),tr=e=>pn(dt({},"__esModule",{value:!0}),e);var ti={};er(ti,{CodeType:()=>Z,DefaultMiniAppSplash:()=>cn,MINIAPP_PLATFORM_URL:()=>gt,MiniAppHost:()=>Go,MiniAppHostError:()=>g,ScannerEndReason:()=>qe,ScannerEvent:()=>_t,ScannerLayout:()=>ve,ScannerMethod:()=>We,ToastType:()=>ue,closeMiniApp:()=>Je,configureMiniApp:()=>dn,createMmkvStorage:()=>fn,createReactNativeBiometrics:()=>Ft,createRnfsFileSystem:()=>mn,ensureMiniApp:()=>pt,getLocalMiniApp:()=>U,getMiniAppCatalog:()=>Wo,getMiniAppCatalogEntry:()=>Ge,getMiniAppStatuses:()=>Fo,getMiniAppUpdate:()=>sn,installBundledMiniApp:()=>wo,onMiniAppEvent:()=>Lo,openMiniApp:()=>Po,pauseMiniApp:()=>Vo,pauseMiniAppDownloads:()=>qo,preloadMiniApp:()=>To,releaseSpeechFor:()=>Se,restoreMiniApp:()=>Uo,resumeMiniApp:()=>Bo,resumeMiniAppDownloads:()=>$o,sendEventToWeb:()=>Ao,syncMiniAppCatalog:()=>kt,uninstallMiniApp:()=>No,updateMiniApp:()=>zo,uploadToUrl:()=>Vt,useMiniAppDownload:()=>Ct,useMiniAppDownloadsPaused:()=>Io});module.exports=tr(ti);var gt="https://retion-miniapp-platform.vercel.app",Ue=null,un=new Set,dn=e=>{Ue=e,un.forEach(t=>t())},B=()=>{if(!Ue)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return Ue},gn=e=>{un.add(e),Ue&&e()},pe=(...e)=>{Ue!=null&&Ue.debug&&console.log("[miniapp]",...e)};var mn=(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:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:c})=>r==null?void 0:r(l,c)});return{promise:a.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(i)}}}),fn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var A=le(require("react")),k=require("react-native"),Jo=le(require("react-native-webview"));var ot=require("react-native");var Ft=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),mt,Dt=()=>(mt||(mt=import("react-native-biometrics").then(({default:e})=>Ft(new e({allowDeviceCredentials:!1}))).catch(e=>{throw mt=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),mt);var Ae=require("react-native");var hn=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("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 g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,l]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<a||c>l))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${l} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},yn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,s)=>{r||(r=!0,clearTimeout(a),c?o(c):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),l=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!l())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(l()){if(Ae.Platform.OS==="android"){let s=Ae.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ae.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,m=await Ae.PermissionsAndroid.check(s);if(!l())return;let y=m||await Ae.PermissionsAndroid.check(d);if(!l())return;if(!m&&!y){let u=await Ae.PermissionsAndroid.requestMultiple([s,d]);if(!l())return;if(u[s]!==Ae.PermissionsAndroid.RESULTS.GRANTED&&u[d]!==Ae.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}l()&&c.getCurrentPosition(s=>{l()&&i(void 0,s)},s=>{var m;if(!l())return;let d=(m={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?m:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(c=>i(c))});var Ut=require("react-native");var Nt=20,wn=20,Mn=/^[a-z][a-z0-9_-]{0,31}$/,nr=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,or=["low","medium","high"],Pe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),G=e=>new g("INVALID_PARAMS",e),et=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,_n=(e,t)=>{if(e===void 0)return{};if(!Pe(e)||Object.keys(e).length>wn||Object.values(e).some(n=>typeof n!="string"))throw G(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${wn} key)`);return e},xn=e=>{var n,o,r,i;if(e!==void 0&&!Pe(e))throw G("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Mn.test(t.source)))throw G("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!nr.test(a))))throw G("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,Nt))throw G(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Nt}`);if(t.max_size!==void 0&&!et(t.max_size,1,Number.MAX_SAFE_INTEGER))throw G("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!et(t.concurrency,1,5))throw G("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(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:rr(t.process),target:ir(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},rr=e=>{if(e===void 0)return{};if(!Pe(e))throw G("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Pe(n))throw G("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 G(`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 G("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(!Pe(n))throw G("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!et(n.max_duration,1,3600))throw G("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!or.includes(n.quality))throw G("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},ir=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Pe(e))throw G("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Mn.test(t))throw G("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Pe(e.params))throw G("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 G("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw G(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:_n(e.headers,"upload.headers"),form_data:_n(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},En=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},sr=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=En(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},ar=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"},Xe,cr=()=>(Xe!=null||(Xe=import("react-native-image-picker").catch(e=>{throw Xe=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Xe),bn=e=>async({accept:t,max_count:n,process:o})=>{var c,s,d,m,y,u,w,C,M;let r=await cr(),i=ar(t),a={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(m=(d=o.image)==null?void 0:d.quality)!=null?m:.8,videoQuality:(u=(y=o.video)==null?void 0:y.quality)!=null?u:"medium",durationLimit:(w=o.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},l=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(l.didCancel)return[];if(l.errorCode){let P=l.errorCode==="permission"?"PERMISSION_DENIED":l.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(P,(C=l.errorMessage)!=null?C:l.errorCode)}return((M=l.assets)!=null?M:[]).filter(P=>P.uri).map((P,x)=>{var b,Q,ee;return{uri:P.uri,name:(b=P.fileName)!=null?b:`file_${x+1}`,mime_type:(Q=P.type)!=null?Q:"application/octet-stream",size:P.fileSize,width:P.width,height:P.height,duration:P.duration,processed:!((ee=P.type)!=null&&ee.startsWith("video/"))||Ut.Platform.OS==="ios"}})},lr={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},pr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},ur=e=>async({accept:t,max_count:n})=>{var i,a,l,c;let o=t.map(s=>{var d;return(d=lr[s])!=null?d:pr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,w)=>{var C,M,P;return{uri:u.uri,name:(C=u.name)!=null?C:`file_${w+1}`,mime_type:(M=u.type)!=null?M:"application/octet-stream",size:(P=u.size)!=null?P:void 0}});if(Ut.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(u=>u.uri.startsWith("content://")))return d;let m=await e.keepLocalCopy({files:d.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),y=new Map(m.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return d.map(u=>{var w;return{...u,uri:(w=y.get(u.uri))!=null?w:u.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((c=(l=e.errorCodes)==null?void 0:l.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Ze,dr=async e=>(Ze!=null||(Ze=import("@react-native-documents/picker").then(t=>ur(t)).catch(t=>{throw Ze=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Ze)(e)),Rn={library:bn("library"),camera:bn("camera"),document:dr},An={type:"image",label:"\u1EA2nh",accept:["image/*"]},Sn={type:"video",label:"Video",accept:["video/*"]},vn={library:[An,Sn],camera:[An,Sn],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"]}]},Qe,Pn=()=>(Qe!=null||(Qe=import("react-native-compressor").catch(()=>(Qe=void 0,null))),Qe),Tn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},gr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),mr={low:640,medium:1280,high:1920},fr=async(e,{image:t})=>{var o;if(!t||!gr.has(e.mime_type.toLowerCase()))return e;let n=await Pn();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 Tn(n,r,e.size),processed:!0}}catch{return e}},hr=async(e,{video:t})=>{var o;let n=await Pn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:mr[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Tn(n,r,e.size),processed:!0}}catch{return e}},yr={image:fr,video:hr},wr=(e,t)=>t.split(".").reduce((n,o)=>Pe(n)?n[o]:void 0,e),Vt=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let l=new XMLHttpRequest,c=new FormData;Object.entries(a.form_data).forEach(([m,y])=>c.append(m,y)),c.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>l.abort();o.addEventListener("abort",s);let d=m=>{o.removeEventListener("abort",s),m()};l.open("POST",a.url),Object.entries(a.headers).forEach(([m,y])=>l.setRequestHeader(m,y)),l.upload.onprogress=m=>n(m.loaded,m.total||e.size||0),l.onload=()=>d(()=>{let m=l.responseText;try{m=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${l.status}`));return}let y=wr(m,a.url_field);if(typeof y!="string"||!y){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:y,response:m})}),l.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),l.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),l.send(c)}),Cn=e=>{var o,r;let t={...Rn};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Vt};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},On=e=>{let{sources:t,targets:n}=Cn(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Rn[i]&&vn[i]).map(i=>[i,vn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Nt}},ht=new Map,kn=(e,t)=>`${e}:${t}`,_r=0,In=(e,t)=>{var n;typeof t=="string"&&((n=ht.get(kn(e,t)))==null||n.abort())},Ve=e=>{for(let[t,n]of ht)t.startsWith(`${e}:`)&&n.abort()},ft=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),br=(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)}},Ln=async(e,t)=>{var c;let{sources:n,targets:o}=Cn(t.config),r=n[e.source];if(!r)throw new g("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 g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,l=kn(t.instance_id,(c=t.task_id)!=null?c:`auto-${++_r}`);ht.set(l,a);try{return await Ar(e,t,r,i,a.signal)}finally{ht.delete(l)}},Ar=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:l=m=>m()},c,s,d)=>{var h,E,j;let m={app_id:n!=null?n:"",instance_id:t,context:{...(h=o==null?void 0:o())!=null?h:{}}},y=(await l(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:m}))).slice(0,e.max_count);if(d.aborted)throw ft();if(!y.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],w=y.filter(T=>sr(T,e.accept)?!0:(u.push({name:T.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${T.mime_type||En(T.name)}`}),!1)),C=w.map(()=>0),M=w.map(T=>{var L;return(L=T.size)!=null?L:0}),P=0,x=0,b=(T=!1)=>{if(!a||!r)return;let L=Date.now();if(!T&&L-x<200)return;x=L;let V=M.reduce((D,te)=>D+te,0),z=C.reduce((D,te)=>D+te,0);a("upload.progress",{task_id:r,loaded:z,total:V,percent:V?Math.min(100,Math.round(z/V*100)):0,done_count:P,count:w.length})},Q=[],ee=0,oe=async()=>{var T,L,V;for(;ee<w.length;){let z=ee++,D=w[z];try{if(d.aborted)throw ft();let te=D.mime_type.startsWith("image/")?"image":D.mime_type.startsWith("video/")?"video":void 0,Fe=te&&!D.processed?(L=(T=i==null?void 0:i.processors)==null?void 0:T[te])!=null?L:yr[te]:void 0;if(Fe&&(D=await Fe(D,e.process),M[z]=(V=D.size)!=null?V:M[z],d.aborted))throw ft();if(e.max_size&&D.size&&D.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${D.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let fe=(Re,De)=>{C[z]=Re,De&&(M[z]=De),b()},ne=await s({file:D,target:e.target,onProgress:fe,signal:d,caller:m});if(typeof(ne==null?void 0:ne.url)!="string"||!ne.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Ee,...be}=ne;Q[z]={url:Ee,name:D.name,mime_type:D.mime_type,size:D.size,width:D.width,height:D.height,duration:D.duration,...Object.keys(be).length?{response:"response"in be?be.response:be}:{}},C[z]=M[z]}catch(te){u.push(br(w[z].name,te))}finally{P++,b(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,w.length)},oe)),d.aborted)throw ft();let _e=Q.filter(T=>!!T);if(!_e.length){let T=u[0];throw new g((E=T==null?void 0:T.code)!=null?E:"UPLOAD_FAILED",(j=T==null?void 0:T.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:_e,failed:u}};var yt=require("react"),Te=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)})}},W=(e,t,n=Object.is)=>{let o=(0,yt.useRef)(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let l=t(i),c=a&&n(a.value,l)?a.value:l;return o.current={state:i,selector:t,value:c},c};return(0,yt.useSyncExternalStore)(e.subscribe,r)};var ue={info:"info",success:"success",error:"error"},Sr=200,Fn={info:2e3,success:2e3,error:3e3},tt=Te({message:"",type:ue.info,tick:0}),Dn=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,Sr);return o?{message:o,type:Object.values(ue).includes(n)?n:ue.info}:null},Nn=(e,t=ue.info)=>{tt.setState(n=>({message:e,type:t,tick:n.tick+1}))};var Ce=require("react-native");var Be=require("react-native");var de,Un=()=>Be.Platform.OS==="android"&&!!(de!=null&&de.requesting_permission),vr=1500,wt=()=>new Promise(e=>{if(Be.Platform.OS!=="android"||Be.AppState.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,vr),o=Be.AppState.addEventListener("change",r=>{r==="active"&&t()})}),Bt=e=>{var t;if(de===e&&(de=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Be.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Vn=async(e,t,n,o=()=>!0)=>{var i,a,l,c,s;if(de)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};de=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let m=d.ExpoSpeechRecognitionModule;if(r.native=m,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let y;try{y=await m.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await wt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!y.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await m.getStateAsync()!=="inactive")throw new g("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 g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(m.addListener("result",u=>{var w,C;de!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(C=(w=u.results[0])==null?void 0:w.transcript)!=null?C:""})}),m.addListener("error",u=>{de===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),m.addListener("end",()=>{de===r&&(Bt(r),n("speech.end"))})),r.started=!0,m.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(l=t.interimResults)!=null?l:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Bt(r),d}},Bn=e=>{let t=de;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},Se=e=>{let t=de;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Bt(t)}};var qn={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"},Z={...qn,all:Object.values(qn)},We={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},_t={result:"scanner.result",end:"scanner.end"},qe={user:"user",web:"web",closed:"closed",error:"error"},ve={top:"top",full:"full"},$e={once:"once",continuous:"continuous"},Mr=1500,$n=6e4,N,K=Te({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Wn=()=>Ce.Platform.OS==="android"&&!!(N!=null&&N.requesting_permission),$t=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r}=e!=null?e:{},i={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(a=>Z.all.includes(a)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");i.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>$n)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${$n}`);i.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");i.hint=o}if(r!==void 0){if(!Object.values(ve).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");i.layout=r}return i},zt=e=>N!==e?!1:(N=void 0,K.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),xr=()=>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(()=>{})}}]),jn=async(e,t)=>{if(N)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");N=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=Ce.Platform.OS==="ios"&&o.Camera.getCameraPermissionStatus()==="denied";e.requesting_permission=!0;let i;try{i=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await wt(),n(),i!=="granted")throw r&&xr(),new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera");if(!o.Camera.getAvailableCameraDevices().some(l=>l.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let a=await Wt();n(),K.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,hint:e.hint,vision:o,glass_view:a},last_value:null,scan_count:0,notice:null})}catch(o){throw zt(e),o}},Wt=async()=>{if(Ce.Platform.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},Hn=(e,t,n)=>{var o,r,i;return{owner:e,mode:t,types:(o=n.types)!=null?o:Z.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Mr,hint:n.hint,layout:t===$e.once?ve.full:(i=n.layout)!=null?i:ve.top,cancelled:!1,requesting_permission:!1,last_seen:new Map}},Jn=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=Hn(e,$e.once,t);a.onHit=o,a.resolve=r,a.reject=i,jn(a,n).catch(i)}),Gn=(e,t,n,o=()=>!0,r)=>{let i=Hn(e,$e.continuous,t);return i.emit=n,i.onHit=r,jn(i,o)},bt=(e,t,n)=>{var o,r;if(!K.getState().active){e.cancelled=!0;return}if(zt(e)){if(e.mode===$e.once){(o=e.reject)==null||o.call(e,t===qe.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,_t.end,n?{reason:t,message:n}:{reason:t})}},Kn=e=>{(N==null?void 0:N.owner)===e&&bt(N,qe.web)},Oe=e=>{(N==null?void 0:N.owner)===e&&bt(N,qe.closed)},jt=()=>{N&&bt(N,qe.user)},Yn=e=>{N&&bt(N,qe.error,e)},Ht=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=N;if(!(!o||!K.getState().active))for(let{value:l,type:c}of e){if(!l)continue;let s=o.last_seen.get(l);if(o.last_seen.set(l,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===$e.once){zt(o),(i=o.resolve)==null||i.call(o,{value:l,type:c});return}K.setState(d=>({last_value:l,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,_t.result,{value:l,type:c})}}},Er={1:Z.code128,2:Z.code39,4:Z.code93,8:Z.codabar,16:Z.dataMatrix,32:Z.ean13,64:Z.ean8,128:Z.itf,256:Z.qr,512:Z.upcA,1024:Z.upcE,2048:Z.pdf417,4096:Z.aztec},Rr=2500,zn=2e3,qt=e=>{K.setState({notice:e}),setTimeout(()=>{K.getState().notice===e&&K.setState({notice:null})},Rr)},Xn=async()=>{var t,n;let e=N;if(!(!e||K.getState().is_picking)){e.requesting_permission=!0,K.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:zn,maxHeight:zn}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||N!==e)return;if(r.errorCode||!i){qt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),l=await a.scan(i);if(N!==e)return;let c=l.map(({value:s,format:d})=>({value:s,code_type:Er[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!c.length){qt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}Ht(c,Date.now(),!0)}catch{N===e&&qt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await wt(),e.requesting_permission=!1,N===e&&K.setState({is_picking:!1})}}};var St=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},Zn=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===St&&typeof t.method=="string"?t:null}catch{return null}},rt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Qn=(e,t)=>rt({id:e,result:t}),eo=(e,t)=>rt({id:e,error:{code:t.code,message:t.message}}),to=(e,t)=>rt({event:e,data:t}),Gt=e=>rt({event:"context",data:e});var no=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -8,7 +8,7 @@
8
8
  else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
9
9
  else { parts.push(String(a)); }
10
10
  }
11
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${At}, method: 'log', level: level, text: parts.join(' ') }));
11
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${St}, method: 'log', level: level, text: parts.join(' ') }));
12
12
  } catch (e) {}
13
13
  };
14
14
  ['log', 'info', 'warn', 'error'].forEach(function (level) {
@@ -30,7 +30,7 @@
30
30
  function report(at_top) {
31
31
  if (at_top === last) { return; }
32
32
  last = at_top;
33
- window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${At}, method: 'touchAtTop', at_top: at_top }));
33
+ window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${St}, method: 'touchAtTop', at_top: at_top }));
34
34
  }
35
35
  document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
36
36
  // Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
@@ -59,11 +59,11 @@
59
59
  },
60
60
  });
61
61
  };
62
- })(); true;`,io=e=>ot({event:e}),so=(e,t)=>{let n=ao(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${Gt(e)}`},ao=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),co=(e,t={})=>{let n=ao(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${At} };
62
+ })(); true;`,io=e=>rt({event:e}),so=(e,t)=>{let n=ao(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
+ ${Gt(e)}`},ao=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),co=(e,t={})=>{let n=ao(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${St} };
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
66
- true;`},lo={partner:"partner_token",chatbox:"chatbox_token"},po=(e,t)=>{let n={...e};for(let o of Object.values(lo))t.includes(o)||delete n[o];return n},Jt=new Set,tt=async(e,t)=>{if(Jt.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Jt.add(e);try{return await t()}finally{Jt.delete(e)}},uo=()=>`(function () {
66
+ true;`},lo={partner:"partner_token",chatbox:"chatbox_token"},po=(e,t)=>{let n={...e};for(let o of Object.values(lo))t.includes(o)||delete n[o];return n},Jt=new Set,nt=async(e,t)=>{if(Jt.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Jt.add(e);try{return await t()}finally{Jt.delete(e)}},uo=()=>`(function () {
67
67
  try {
68
68
  var AudioCtx = window.AudioContext || window.webkitAudioContext;
69
69
  if (!AudioCtx) { return; }
@@ -79,4 +79,4 @@
79
79
  oscillator.start(ctx.currentTime);
80
80
  oscillator.stop(ctx.currentTime + 0.08);
81
81
  } catch (e) {}
82
- })(); true;`,Rr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),bt=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},go=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:l,instance_id:c,options:s,emit:d,isActive:m,playBeep:y})=>{var T,x,b,Q,ee,oe,_e;let u=s==null?void 0:s.handlers,w={app_id:l,instance_id:c,close:a},C=()=>{var h;(h=s==null?void 0:s.haptic)==null||h.call(s,"impactLight"),y==null||y()},M=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=hn(t);return tt(e,()=>yn(h,m))}case"speech.start":{if(!d)throw M();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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let E of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[E])!==void 0){if(typeof t[E]!="boolean")throw new g("INVALID_PARAMS",`${E} ph\u1EA3i l\xE0 boolean`);h[E]=t[E]}return Vn(c,h,d,m)}case"speech.stop":return Bn(c);case ze.scan:return Jn(c,$t(t),m,C);case ze.start:{if(!d)throw M();return Gn(c,$t(t),d,m,C)}case ze.stop:return Kn(c);case"uploadFiles":{let{task_id:h,...E}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ln(xn(E),{instance_id:c,app_id:l,getContext:r,task_id:h,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>tt("uploadFiles.pick",j)})}case"uploadFiles.cancel":In(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return On(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await Ft()).getAvailability();case"authenticateBiometric":{let h=bt(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let E=t==null?void 0:t.cancelButtonText;if(E!==void 0&&(typeof E!="string"||!E.trim()||E.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return tt(e,async()=>{var P;return((P=s==null?void 0:s.biometrics)!=null?P:await Ft()).authenticate({reason:h,cancelButtonText:E})})}case"requestPayment":{let h=u==null?void 0:u.requestPayment;if(!h)throw M();let E=t==null?void 0:t.amount;if(typeof E!="number"||!Number.isFinite(E)||E<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:E,currency:bt(t==null?void 0:t.currency,"currency")};return tt(e,()=>h(j,w))}case"printImage":{let h=u==null?void 0:u.printImage;if(!h)throw M();let E=bt(t==null?void 0:t.image,"image");await tt(e,()=>h({image:E},w));return}case"openScreen":if(!(u!=null&&u.openScreen))throw M();await u.openScreen({screen:bt(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},w);return;case"closeApp":a();return;case"openWebview":{let h=String((x=t==null?void 0:t.url)!=null?x:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(h):nt.Linking.openURL(h));return}case"openLink":{let h=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(h):nt.Linking.openURL(h))}catch(E){throw new g("NOT_SUPPORTED",String((ee=(Q=E==null?void 0:E.message)!=null?Q:E)!=null?ee:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=Dn(t);if(!h||(m==null?void 0:m())===!1)return;s!=null&&s.showToast?s.showToast(h.message,{type:h.type}):Nn(h.message,h.type);return}case"haptic":{let h=Rr.has(t==null?void 0:t.type)?t.type:"selection";(oe=s==null?void 0:s.haptic)==null||oe.call(s,h);return}case"getSystemInfo":return{platform:nt.Platform.OS==="ios"?"ios":"android",appVersion:(_e=s==null?void 0:s.app_version)!=null?_e:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let P=n().access_token;if(!P)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return P}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let E=lo[h];if(!o().includes(E))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${E} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=h==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${E}`);return j}case"getUserInfo":{let h=n().user;if(!h)throw new g("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 g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Yt=e=>`bundle:${e}`,Xt=()=>`${B().file_system.document_dir}/miniapps`,Zt=Xt,Qt=(e,t,n="index.html",o=!1,r=[])=>{let i=`${Zt()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Kt=e=>{var t;B().storage.setString(Yt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Tr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,U=e=>{let t=B().storage.getString(Yt(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return Qt(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Me=e=>B().file_system.exists(e.entry_uri.replace("file://","")),en=async e=>{let t=U(e.app_id);return(t==null?void 0:t.version)===e.version&&await Me(t)},fo=async(e,t)=>{let n=B().file_system,o=`${Zt()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},ho=async e=>{var t;await((t=it[e])==null?void 0:t.catch(()=>{})),B().storage.setString(Yt(e),""),await B().file_system.remove(`${Zt()}/${e}`).catch(()=>{})},We=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},it={},yo=(e,t)=>{var i;let o=((i=it[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return it[e]=r,r.then(()=>{it[e]===r&&delete it[e]}),o},Pr=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let l=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(l)return l}return 0},wo=({manifest:e,zip_path:t})=>yo(e.app_id,async()=>{var i;let n=B().file_system,o=U(e.app_id);if(o&&Pr(o.version,e.version)>=0&&await Me(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=Qt(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),Kt(e),pe("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),fo(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),tn=(e,{base_url:t,onProgress:n}={})=>{let o=B().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(i)throw new We},c=async()=>{var m;l();let s=U(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return Kt(e),U(e.app_id);l();let d=o.download({url:t?Tr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,u)=>{var C;let w=u>0?u:(C=e.size)!=null?C:0;w>0&&(n==null||n(Math.min(1,y/w)))}});r=d;try{let{status:y}=await d.promise;if(l(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else pe("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let u=Qt(e.app_id,e.version,e.entry,!!e.context_update,(m=e.permissions)!=null?m:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(a,u.dir),Kt(e),fo(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),u}catch(y){throw i?new We:y}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:yo(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},rt={},Cr=__DEV__?0:60*1e3,mo={},_o=(e,t)=>{var o,r;let n=U(e);return n&&Date.now()-((o=mo[t])!=null?o:0)<Cr?Promise.resolve(n):((r=rt[e])!=null||(rt[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),l=await tn(a,{base_url:t}).promise;return mo[t]=Date.now(),l})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),U(e))).finally(()=>{rt[e]=void 0})),rt[e])};var St=new Map,bo=(e,t)=>(St.set(e,t),()=>{St.get(e)===t&&St.delete(e)}),Ao=(e,t)=>{let n=St.get(e);return n?n(t):!1};var $=require("react"),f=require("react-native");var v=require("react/jsx-runtime"),st="#22C55E",Or="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",kr=2,Mt=18,Ir=1600,at=14,Lr=2e3,So=2,Fr=8,Dr=2e3,je=2e3,Nr=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:at},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:at},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:at},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:at}],vo=({color:e})=>(0,v.jsx)(v.Fragment,{children:Nr.map((t,n)=>(0,v.jsx)(f.View,{style:[S.corner,t,{borderColor:e}]},n))}),vt=({style:e,children:t,...n})=>{let o=(0,$.useRef)(new f.Animated.Value(1)).current,r=i=>f.Animated.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return(0,v.jsx)(f.Pressable,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:(0,v.jsx)(f.Animated.View,{style:[e,{transform:[{scale:o}]}],children:t})})},on=({scanner:e})=>{var pt,Ge,Ke;let{vision:t,types:n,mode:o,layout:r,hint:i,glass_view:a}=e,l=r===ve.top,c=t.useCameraDevice("back"),s=(0,$.useRef)(new f.Animated.Value(1)).current,d=(0,$.useRef)(new f.Animated.Value(0)).current,[m,y]=(0,$.useState)(!1),[u,w]=(0,$.useState)(1),C=(0,$.useRef)(null),[M,T]=(0,$.useState)({width:0,height:0,window_y:0}),x=W(K,p=>p.last_value),b=W(K,p=>p.hit_tick),Q=W(K,p=>p.scan_count),ee=W(K,p=>p.notice),oe=W(K,p=>p.is_picking),_e=(0,$.useRef)(null),h=f.Platform.OS==="ios"?54:(pt=f.StatusBar.currentHeight)!=null?pt:0,E=(0,$.useRef)(new f.Animated.Value(0)).current,j=(0,$.useRef)(new f.Animated.Value(0)).current,P=(0,$.useRef)(new f.Animated.Value(0)).current,L=Math.round(M.width*(l?.8:.78)),V=Math.round(l?M.height*.46:L*.78),z=Math.round((M.height-V)/2),D=Math.round((M.width-L)/2),te=t.useCodeScanner({codeTypes:n,onCodeScanned:(0,$.useCallback)(p=>Ht(p),[])});(0,$.useEffect)(()=>{let p=f.BackHandler.addEventListener("hardwareBackPress",()=>(jt(),!0));return()=>p.remove()},[]);let Le=(0,$.useRef)(b);(0,$.useEffect)(()=>{if(b===Le.current)return;E.setValue(1),P.setValue(1);let p=f.Animated.parallel([f.Animated.timing(E,{toValue:0,duration:450,useNativeDriver:!0}),f.Animated.sequence([f.Animated.delay(Lr),f.Animated.timing(P,{toValue:0,duration:250,useNativeDriver:!0})])]);return p.start(),()=>p.stop()},[b,E,P]),(0,$.useEffect)(()=>{let p=H=>f.Animated.timing(j,{toValue:H,duration:Ir,easing:f.Easing.inOut(f.Easing.quad),useNativeDriver:!0}),_=f.Animated.loop(f.Animated.sequence([p(1),p(0)]));return _.start(),()=>_.stop()},[j]);let fe=(0,$.useCallback)(()=>{f.Animated.timing(s,{toValue:0,duration:220,useNativeDriver:!0}).start()},[s]);(0,$.useEffect)(()=>{let p=setTimeout(fe,Dr);return()=>clearTimeout(p)},[fe]);let ne=!!(c!=null&&c.hasTorch),Ee=(Ge=c==null?void 0:c.neutralZoom)!=null?Ge:1,be=c?Math.min(c.maxZoom/Ee,Fr):1,Re=Ee*Math.min(u,be),Fe=p=>{var re;let{touches:_}=p.nativeEvent;if(_.length!==2){C.current=null;return}let H=Math.hypot(_[0].pageX-_[1].pageX,_[0].pageY-_[1].pageY);(re=C.current)!=null||(C.current={distance:H,level:u}),w(Math.max(1,Math.min(be,C.current.level*(H/C.current.distance))))},kt=(0,v.jsx)(f.Text,{style:[S.hint,!!ee&&S.hint_notice],numberOfLines:1,children:(Ke=ee!=null?ee:i)!=null?Ke:Or});return(0,v.jsx)(f.View,{ref:_e,onTouchMove:Fe,onTouchEnd:()=>{C.current=null},style:l?S.top:S.full,onLayout:({nativeEvent:{layout:p}})=>{var _;(_=_e.current)==null||_.measureInWindow((H,re)=>{T({width:p.width,height:p.height,window_y:re||0}),f.Animated.timing(d,{toValue:1,duration:180,useNativeDriver:!0}).start()})},children:(0,v.jsxs)(f.Animated.View,{style:[S.content,{opacity:d}],children:[c&&(0,v.jsx)(t.Camera,{style:f.StyleSheet.absoluteFill,device:c,isActive:!oe,codeScanner:te,torch:m&&ne?"on":"off",zoom:Re,onPreviewStarted:fe,onError:p=>Yn(p.message)}),(0,v.jsx)(f.Animated.View,{style:[S.preview_cover,{opacity:s}],pointerEvents:"none"}),M.height>0&&(0,v.jsxs)(f.View,{style:S.overlay,pointerEvents:"none",children:[(0,v.jsx)(f.View,{style:[S.dim_ring,{top:z-je,left:D-je,width:L+je*2,height:V+je*2}]}),(0,v.jsxs)(f.View,{style:{position:"absolute",top:z,left:D,width:L,height:V},children:[(0,v.jsx)(vo,{color:"#FFFFFF"}),(0,v.jsx)(f.Animated.View,{style:[f.StyleSheet.absoluteFill,{opacity:E}],children:(0,v.jsx)(vo,{color:st})}),(0,v.jsxs)(f.Animated.View,{style:[S.scan_line_wrap,{transform:[{translateY:j.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,V-Mt)]})}]}],children:[(0,v.jsx)(f.View,{style:S.scan_glow_outer}),(0,v.jsx)(f.View,{style:S.scan_glow_inner}),(0,v.jsx)(f.View,{style:S.scan_line})]})]}),(0,v.jsx)(f.View,{style:[S.hint_slot,l?{top:0,height:z-6,justifyContent:"flex-end"}:{top:z+V+20}],children:kt}),o===qe.continuous&&!!x&&(0,v.jsx)(f.Animated.View,{style:[S.result_slot,l?S.result_slot_top:{top:z+V+52},{opacity:P}],children:(0,v.jsxs)(f.View,{style:S.result,children:[(0,v.jsx)(f.View,{style:S.check_badge,children:(0,v.jsx)(f.View,{style:S.check_mark})}),(0,v.jsx)(f.Text,{style:S.result_text,numberOfLines:1,children:x}),(0,v.jsxs)(f.Text,{style:S.result_count,children:["\xB7 ",Q," m\xE3"]})]})})]}),M.height>0&&(0,v.jsx)(f.View,{style:[S.close_slot,{top:Math.max(12,h-M.window_y+12)}],children:(0,v.jsxs)(vt,{style:[S.close_button,!!a&&S.glass_surface],onPress:jt,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&(0,v.jsx)(a,{style:S.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(f.View,{style:[S.close_bar,S.close_bar_a]}),(0,v.jsx)(f.View,{style:[S.close_bar,S.close_bar_b]})]})}),(0,v.jsx)(f.View,{style:[S.toolbar_wrap,!l&&S.toolbar_wrap_full],pointerEvents:"box-none",children:(0,v.jsxs)(f.View,{style:[S.toolbar,!!a&&S.glass_surface],children:[a&&(0,v.jsx)(a,{style:S.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(vt,{style:S.tool,onPress:Xn,disabled:oe,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:(0,v.jsxs)(f.View,{style:S.image_icon,children:[(0,v.jsx)(f.View,{style:S.image_icon_dot}),(0,v.jsx)(f.View,{style:S.image_icon_hill})]})}),!!c&&be>=So&&(0,v.jsx)(vt,{style:[S.tool,u>1&&S.tool_on],onPress:()=>w(p=>p>1?1:So),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:(0,v.jsxs)(f.Text,{style:[S.zoom_text,u>1&&S.zoom_text_on],children:[Math.round(u*10)/10,"x"]})}),ne&&(0,v.jsx)(vt,{style:[S.tool,m&&S.tool_on],onPress:()=>y(p=>!p),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:m},children:(0,v.jsx)(f.Text,{style:[S.torch_icon,m&&S.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},Ur="rgba(0,0,0,0.5)",nn=50,S=f.StyleSheet.create({top:{height:"38%",overflow:"hidden"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,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:je,borderColor:Ur,borderRadius:je+at},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:Mt,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Mt,borderRadius:Mt/2,backgroundColor:st,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:st,opacity:.2},scan_line:{height:kr,borderRadius:1,backgroundColor:st},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_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_wrap_full:{bottom:f.Platform.OS==="ios"?34:20},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:nn,height:nn,borderRadius:nn/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_slot_top:{top:8},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:st},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 ge=require("react"),R=require("react-native");var Y=require("react/jsx-runtime"),Vr={[ue.info]:"#3B82F6",[ue.success]:"#22C55E",[ue.error]:"#EF4444"},Mo=-120,Br=({type:e})=>e===ue.success?(0,Y.jsx)(R.View,{style:ie.check_mark}):e===ue.error?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(R.View,{style:[ie.cross_bar,ie.cross_a]}),(0,Y.jsx)(R.View,{style:[ie.cross_bar,ie.cross_b]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(R.View,{style:ie.info_dot}),(0,Y.jsx)(R.View,{style:ie.info_bar})]}),Eo=()=>{let e=W(et,y=>y.message),t=W(et,y=>y.type),n=W(et,y=>y.tick),o=(0,ge.useRef)(new R.Animated.Value(Mo)).current,r=(0,ge.useRef)(new R.Animated.Value(0)).current,i=(0,ge.useRef)(new R.Animated.Value(.92)).current,a=(0,ge.useRef)(new R.Animated.Value(0)).current,[l,c]=(0,ge.useState)(),[s,d]=(0,ge.useState)(!1);(0,ge.useEffect)(()=>{let y=!0;return Wt().then(u=>{y&&u&&c(()=>u)}),()=>{y=!1}},[]);let m=(0,ge.useRef)(n);return(0,ge.useEffect)(()=>{if(n===m.current)return;R.AccessibilityInfo.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let y=R.Animated.sequence([R.Animated.parallel([R.Animated.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),R.Animated.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),R.Animated.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),R.Animated.sequence([R.Animated.delay(90),R.Animated.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),R.Animated.delay(Fn[t]),R.Animated.parallel([R.Animated.timing(o,{toValue:Mo,duration:240,useNativeDriver:!0}),R.Animated.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return y.start(({finished:u})=>{u&&d(!1)}),()=>y.stop()},[n]),s?(0,Y.jsx)(R.View,{style:ie.layer,pointerEvents:"none",children:(0,Y.jsxs)(R.Animated.View,{style:[ie.toast,!!l&&ie.toast_glass,{opacity:l?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[l&&(0,Y.jsx)(l,{style:ie.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),(0,Y.jsx)(R.Animated.View,{style:[ie.badge,{backgroundColor:Vr[t],transform:[{scale:a}]}],children:(0,Y.jsx)(Br,{type:t})}),(0,Y.jsx)(R.Text,{style:ie.message,numberOfLines:2,children:e})]})}):null},xo,ie=R.StyleSheet.create({layer:{position:"absolute",top:(R.Platform.OS==="ios"?54:(xo=R.StatusBar.currentHeight)!=null?xo:0)+8,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_glass:{backgroundColor:"transparent"},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"},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 se=Pe({active_key:null,instances:{}}),Ro=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var l;let a=(l=B().keep_alive)==null?void 0:l.max_webviews;se.setState(c=>{let s=t!=null?t:e.app_id,d={...c.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},m=Object.keys(d);return a&&a>0&&m.length>a&&m.filter(y=>y!==s).sort((y,u)=>d[y].last_used_at-d[u].last_used_at).slice(0,m.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},To=e=>Ro(e,!0),Po=e=>Ro(e,!1),He=()=>se.setState({active_key:null}),xt=e=>{se.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Co="catalog",qr="paused_apps",$r="removed_apps",zr=10*1e3,Wr=2,jr=3e3,Hr=()=>{var e;try{return JSON.parse((e=B().storage.getString(Co))!=null?e:"{}")}catch{return{}}},F=Pe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Oo=e=>{var t;return!!((t=B().manual_update)!=null&&t.includes(e))},Tt=new Set,ko=e=>{let t=new Set,n=()=>B().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=B().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},we=ko(qr),Ie=ko($r);gn(()=>{we.load(),Ie.load();let e=Hr(),t={};Object.keys(e).filter(n=>!Ie.has(n)).forEach(n=>{let o=U(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:we.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),F.setState({catalog:e,downloads:t})});var Pt=e=>W(F,t=>e?t.downloads[e]:void 0),Io=()=>W(F,e=>e.pause_reasons.length>0),ye=(...e)=>pe("queue",...e),X=[],xe={},O=null,Et=new Set,$e={},rn=new Set,Oe=e=>{rn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Lo=e=>(rn.add(e),()=>{rn.delete(e)}),Fo=()=>F.getState().downloads,ae=(e,t)=>{let n=!!U(e),o=F.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};F.setState(a=>({downloads:{...a.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?Oe({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Oe({type:"progress",app_id:e,progress:i.progress,version:i.version})},Rt=(e,t)=>{var n;(n=$e[e])==null||n.forEach(o=>o(t)),delete $e[e]},Jr=()=>F.getState().pause_reasons.length>0,ke=e=>{var l;if(O)return;let t=e?X.indexOf(e):Jr()?-1:X.findIndex(c=>!we.has(c));if(t<0||t>=X.length)return;let[n]=X.splice(t,1),o=F.getState().catalog[n];if(!o){Rt(n,U(n)),ke();return}let r=Date.now();xe[n]=((l=xe[n])!=null?l:0)+1,ae(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=tn(o,{onProgress:c=>{let s=Math.floor(c*100);s!==i&&(i=s,ae(n,{progress:s/100,version:o.version}))}});O={app_id:n,handle:a,forced:!!e},ye("start",n,o.version,e?"(forced)":""),a.promise.then(c=>{ye("installed",n,o.version,`${Date.now()-r}ms`),ae(n,{status:"installed",progress:1,version:o.version}),Rt(n,c)}).catch(c=>{var d;if(c instanceof We){if(Et.has(n))return;ye("paused",n),xe[n]-=1,X.unshift(n),ae(n,{status:we.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=c==null?void 0:c.message)!=null?d:c);if(console.warn("[miniapp-queue] failed",n,s),xe[n]<Wr){ae(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var m;X.includes(n)||(O==null?void 0:O.app_id)===n||(X.push(n),ke((m=$e[n])!=null&&m.length?n:void 0))},jr);return}ae(n,{status:"failed",progress:0,version:o.version,error:s}),Rt(n,U(n))}).finally(()=>{O=null;let c=X.find(s=>{var d;return(d=$e[s])==null?void 0:d.length});ke(c)})},Ct=(e,{front:t=!1}={})=>{if((O==null?void 0:O.app_id)===e)return;let n=X.indexOf(e);if(n>=0){if(!t)return;X.splice(n,1)}t?X.unshift(e):X.push(e)},Gr=async e=>{let{host_id:t,client_token:n}=B(),o=new AbortController,r=setTimeout(()=>o.abort(),zr);try{let i=`${dt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},ct=null,Ot=()=>(ct!=null||(ct=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(B().channels.map(Gr)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(F.getState().catalog).filter(c=>!o[c]);B().storage.setString(Co,JSON.stringify(o)),F.setState({catalog:o}),await Promise.all(r.map(c=>Do(c,{by_user:!1}))),r.forEach(c=>Ie.delete(c));let i=Object.keys(o).filter(c=>!Ie.has(c)),a=[],l={};for(let c of i.map(s=>o[s])){if(await en(c)){ae(c.app_id,{status:"installed",progress:1,version:c.version});continue}let s=U(c.app_id);if(Oo(c.app_id)&&!Tt.has(c.app_id)&&s&&await Me(s)){ae(c.app_id,{status:"installed",progress:1,version:s.version}),l[c.app_id]={app_id:c.app_id,current_version:s.version,next_version:c.version};continue}a.push(c)}return F.setState({updates:l}),a.forEach(c=>{xe[c.app_id]=0,ae(c.app_id,{status:we.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),Ct(c.app_id)}),ye("catalog",i.length,"apps, outdated",a.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),Oe({type:"sync_complete",app_ids:i,removed:r}),Object.values(l).forEach(c=>Oe({type:"update_available",...c})),ke(),{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),Oe({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{ct=null}})()),ct),Do=async(e,{by_user:t})=>{var r,i,a,l;if(t&&Ie.add(e),Et.has(e))return;Et.add(e),we.delete(e);let n=X.indexOf(e);n>=0&&X.splice(n,1),(O==null?void 0:O.app_id)===e&&O.handle.cancel();let o=(l=(a=(r=F.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=U(e))==null?void 0:i.version)!=null?l:"";ae(e,{status:"uninstalling",progress:0,version:o}),await ho(e),xt(e),F.setState(c=>{let s={...c.downloads};return delete s[e],{downloads:s}}),delete xe[e],Et.delete(e),Rt(e,null),ye("uninstalled",e,t?"(user)":"(not in list)"),Oe({type:"uninstalled",app_id:e})},No=e=>Do(e,{by_user:!0}),Uo=e=>{let t=Je(e);return t?(Ie.delete(e),(O==null?void 0:O.app_id)===e||X.includes(e)||(xe[e]=0,ae(e,{status:we.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ct(e),ke(),ye("restore",e)),!0):!1},Vo=e=>{if(we.has(e))return;if(we.add(e),ye("pause app",e),(O==null?void 0:O.app_id)===e&&!O.forced){O.handle.cancel();return}let t=F.getState().downloads[e];X.includes(e)&&t&&ae(e,{status:"paused",progress:0,version:t.version})},Bo=e=>{if(!we.delete(e))return;ye("resume app",e);let t=F.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!X.includes(e)&&Je(e)&&(xe[e]=0,Ct(e)),X.includes(e)&&t&&ae(e,{status:"queued",progress:0,version:t.version}),ke()},qo=e=>{let{pause_reasons:t}=F.getState();t.includes(e)||(F.setState({pause_reasons:[...t,e]}),ye("pause",e),t.length===0&&Oe({type:"pause_change",paused:!0,reasons:[e]}),O&&!O.forced&&O.handle.cancel())},$o=e=>{let{pause_reasons:t}=F.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);F.setState({pause_reasons:n}),ye("resume",e),n.length===0&&Oe({type:"pause_change",paused:!1,reasons:n}),ke()},sn=e=>F.getState().updates[e],zo=async e=>{var n,o;let t=sn(e);Tt.add(e);try{let r=await lt(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=Je(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(F.setState(a=>{var c;let l={...a.updates};return delete l[e],{updates:l,apply_ticks:{...a.apply_ticks,[e]:((c=a.apply_ticks[e])!=null?c:0)+1}}}),ye("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Tt.delete(e)}},Wo=()=>Object.values(F.getState().catalog).map(e=>({...e,installed:!!U(e.app_id),removed_by_user:Ie.has(e.app_id)})),Je=e=>F.getState().catalog[e],lt=async e=>{let t=Je(e);if(!t)return;if(we.delete(e),Ie.delete(e),await en(t))return U(e);let n=U(e);if(Oo(e)&&!Tt.has(e)&&n&&await Me(n))return n;let o=new Promise(r=>{var i;((i=$e[e])!=null?i:$e[e]=[]).push(r)});return(O==null?void 0:O.app_id)===e?O.forced=!0:(xe[e]=0,Ct(e,{front:!0}),O&&!O.forced?O.handle.cancel():ke(e)),o};var I=require("react/jsx-runtime"),an=e=>(e!=null?e:"").replace(/\?[^#]*/,""),jo=0,Kr=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Yr=A.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:l,opaque_background:c,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var Ge,Ke;let m=(0,A.useRef)(null),y=(0,A.useRef)(!1),u=W(se,p=>p.instances[e]),w=u==null?void 0:u.app.app_id,C=u==null?void 0:u.app.manifest_url,M=u==null?void 0:u.context,T=u==null?void 0:u.url_params,x=W(K,p=>{var _;return((_=p.active)==null?void 0:_.owner)===e?p.active:null}),[b,Q]=(0,A.useState)(()=>w?U(w):null),[ee,oe]=(0,A.useState)(!1),[_e,h]=(0,A.useState)(0),[E,j]=(0,A.useState)(0),[P,L]=(0,A.useState)(!1),V=(0,A.useRef)(null),z=p=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{V.current=null,L(!0)},p)};(0,A.useEffect)(()=>()=>{V.current&&clearTimeout(V.current)},[]),(0,A.useEffect)(()=>{if(!w||!t&&b)return;let p=!0;return oe(!1),(async()=>{let _=U(w),H=_?await Me(_):!1;if(!p||(Q(H?he=>!he||he.version!==_.version||he.permissions.join(",")!==_.permissions.join(",")?_:he:null),__DEV__&&Date.now()-jo>1e4&&(jo=Date.now(),await Ot()),!p))return;let re=await lt(w),De=re!==void 0?re:C?await _o(w,C):U(w);if(p){if(!De){oe(!0);return}Q(he=>he!=null?he:De)}})(),()=>{p=!1}},[t,w,C,_e]),(0,A.useEffect)(()=>bo(e,p=>m.current?(m.current.postMessage(p),!0):!1),[e]);let D=W(F,p=>{let _=w?p.downloads[w]:void 0;return(_==null?void 0:_.status)==="installed"?_.version:void 0});(0,A.useEffect)(()=>{if(t||!w||!b)return;let p=U(w);if(!p||p.version===b.version)return;let _=!0;return Me(p).then(H=>{!_||!H||(pe(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",b.version,"\u2192",p.version),Q(p))}),()=>{_=!1}},[t,w,D,b==null?void 0:b.version]);let te=W(F,p=>{var _;return w&&(_=p.apply_ticks[w])!=null?_:0});(0,A.useEffect)(()=>{if(!te||!w)return;let p=U(w);if(!p||p.version===(b==null?void 0:b.version))return;let _=!0;return Me(p).then(H=>{!_||!H||(pe(`webview:${e}`,"c\u1EADp nh\u1EADt",b==null?void 0:b.version,"\u2192",p.version),L(!1),Q(p))}),()=>{_=!1}},[te]),(0,A.useEffect)(()=>{var H;let p=(H=B().keep_alive)==null?void 0:H.idle_close_ms;if(t||!p||p<=0)return;let _=setTimeout(()=>{xt(e)},p);return()=>clearTimeout(_)},[t,e]),(0,A.useEffect)(()=>{r>0&&(oe(!1),L(!1),j(p=>p+1),h(p=>p+1))},[r]);let Le=(0,A.useRef)(t);(0,A.useEffect)(()=>{var p;Le.current!==t&&(Le.current=t,y.current&&((p=m.current)==null||p.injectJavaScript(io(t?"resumed":"paused"))))},[t]);let fe=`${(Ge=b==null?void 0:b.version)!=null?Ge:"none"}:${(Ke=b==null?void 0:b.permissions.join(","))!=null?Ke:""}:${E}`,ne=(0,A.useMemo)(()=>JSON.stringify([M!=null?M:{},T!=null?T:{}]),[M,T]),Ee=(0,A.useMemo)(()=>{var p;return po(T!=null?T:{},(p=b==null?void 0:b.permissions)!=null?p:[])},[ne,b==null?void 0:b.permissions]),be=(0,A.useMemo)(()=>co(M!=null?M:{},Ee)+oo()+(k.Platform.OS==="android"?ro():"")+(B().debug?no():""),[Ee]),Re=(0,A.useRef)(null),Fe=(0,A.useRef)(null);(0,A.useEffect)(()=>{var _,H,re;if(!b)return;if(Fe.current!==fe){Fe.current=fe,Re.current=ne;return}if(Re.current===ne)return;let p=((H=JSON.parse((_=Re.current)!=null?_:"[]")[0])!=null?H:{}).org_id;if(Re.current=ne,p===(M==null?void 0:M.org_id)&&y.current){L(!1),z(1500),(re=m.current)==null||re.injectJavaScript(so(M!=null?M:{},Ee));return}L(!1),j(De=>De+1)},[ne,b,fe]),(0,A.useEffect)(()=>(t||(Se(e),Ce(e),Ue(e)),()=>{Se(e),Ce(e),Ue(e)}),[t,e,fe,r]),(0,A.useEffect)(()=>{let p=k.AppState.addEventListener("change",_=>{_==="background"&&!Un()&&Se(e),_==="background"&&!Wn()&&Ce(e)});return()=>p.remove()},[e]);let kt=(0,A.useCallback)(async p=>{var H,re,De,he,It;let _=Zn(p.nativeEvent.data);if(!_){if(w&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(p.nativeEvent.data,{app_id:w,instance_id:e})).catch(q=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,q)})}catch(q){console.warn("[miniapp] onWebEvent l\u1ED7i",w,q)}return}if(_.method==="log"){let{level:q,text:J}=_;pe(`web:${e}`,q!=null?q:"log",J!=null?J:"");return}if(_.method==="pong"){V.current||L(!0);return}if(_.method==="touchAtTop"){i.emit(!!_.at_top);return}if(_.method==="contextApplied"){V.current&&clearTimeout(V.current),V.current=null,L(!0);return}if(_.method==="ready"){y.current=!0,L(!0);let q=(H=se.getState().instances[e])==null?void 0:H.context;q&&((re=m.current)==null||re.injectJavaScript(Gt(q)));return}try{let q=await go(_,{getHostData:()=>{var J,ce;return(ce=(J=se.getState().instances[e])==null?void 0:J.host_data)!=null?ce:{}},getPermissions:()=>{var J,ce;return w?(ce=(J=U(w))==null?void 0:J.permissions)!=null?ce:[]:[]},getContext:()=>{var J,ce;return(ce=(J=se.getState().instances[e])==null?void 0:J.context)!=null?ce:{}},is_dark:o,close:He,app_id:w!=null?w:"",instance_id:e,options:l,emit:(J,ce)=>{var ln;(ln=m.current)==null||ln.injectJavaScript(to(J,ce))},playBeep:()=>{var J;(J=m.current)==null||J.injectJavaScript(uo())},isActive:()=>se.getState().active_key===e&&k.AppState.currentState!=="background"});_.id&&((De=m.current)==null||De.injectJavaScript(Qn(_.id,q)))}catch(q){if(!_.id)return;let J=q==null?void 0:q.code,ce=q instanceof g?q:new g(typeof J=="string"?J:"HOST_ERROR",String((he=q==null?void 0:q.message)!=null?he:q));(It=m.current)==null||It.injectJavaScript(eo(_.id,ce))}},[e,o,w,i,l]),pt=(0,A.useCallback)(()=>{oe(!1),j(p=>p+1),h(p=>p+1)},[]);return(0,I.jsxs)(k.View,{style:[k.StyleSheet.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&me.behind],pointerEvents:t?"auto":"none",children:[(x==null?void 0:x.layout)===ve.top&&(0,I.jsx)(on,{scanner:x}),b?(0,I.jsx)(Jo.default,{ref:m,source:{uri:b.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?Xt():b.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:be,onMessage:kt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{Se(e),Ce(e),Ue(e),pe(`webview:${e}`,"load start",an(p.nativeEvent.url)),y.current=!1,L(!1)},onError:p=>{Se(e),Ce(e),Ue(e),pe(`webview:${e}`,"load error",an(p.nativeEvent.url),p.nativeEvent.description),oe(!0),L(!1)},onLoadEnd:p=>{let _=p.nativeEvent.url;pe(`webview:${e}`,"load end",an(_)),w&&(d==null||d({app_id:w,instance_id:e,url:_})),z(1500)},onContentProcessDidTerminate:()=>{Se(e),Ce(e),Ue(e),y.current=!1,L(!1),j(p=>p+1)},onRenderProcessGone:()=>(Se(e),Ce(e),Ue(e),y.current=!1,L(!1),j(p=>p+1),!0),style:me.webview},fe):null,(x==null?void 0:x.layout)===ve.full&&(0,I.jsx)(on,{scanner:x}),u&&(0,I.jsx)(Zr,{visible:!b||!P,interactive:ee,children:(0,I.jsx)(Xr,{splash:a,app:u.app,is_dark:o,error:ee,has_bundle:!!b,retry:pt})})]})}),Xr=A.default.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,l=Pt(t.app_id),c=o?"error":!r&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return(0,I.jsx)(a,{app:t,is_dark:n,status:c,progress:c==="downloading"?l==null?void 0:l.progress:void 0,retry:i})}),Zr=({visible:e,interactive:t,children:n})=>{let o=(0,A.useRef)(new k.Animated.Value(e?1:0)).current,[r,i]=(0,A.useState)(e);return(0,A.useEffect)(()=>{if(e){i(!0),o.setValue(1);return}let a=k.Animated.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:l})=>{l&&i(!1)}),()=>a.stop()},[e,o]),r?(0,I.jsx)(k.Animated.View,{style:[k.StyleSheet.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},cn=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return(0,I.jsxs)(k.View,{style:[me.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,I.jsx)(k.View,{style:[me.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,I.jsx)(k.Image,{source:{uri:e.icon},style:me.splash_icon_image}):(0,I.jsx)(k.Text,{style:me.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,I.jsx)(k.Text,{style:[me.splash_name,{color:i}],children:e.name}),n==="error"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(k.Text,{style:me.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,I.jsx)(k.TouchableOpacity,{activeOpacity:.7,style:[me.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,I.jsx)(k.Text,{style:[me.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(k.ActivityIndicator,{style:me.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,I.jsxs)(k.Text,{style:me.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},Ho=(e,t)=>{let n=(0,A.useRef)(t),o=(0,A.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.`))},Qr=({container:e,splash:t=cn,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:l})=>{Ho("container",e),Ho("splash",t);let c=e,s=W(se,x=>x.active_key),d=(0,A.useRef)(s);s&&(d.current=s);let m=W(se,x=>Object.keys(x.instances).join("|")),y=W(se,x=>{var b;return x.active_key?(b=x.instances[x.active_key])==null?void 0:b.app.name:void 0}),u=(0,A.useMemo)(()=>m?m.split("|"):[],[m]),[w,C]=(0,A.useState)({}),M=(0,A.useRef)(Kr()).current;(0,A.useEffect)(()=>{if(!s||!r)return;let x=k.BackHandler.addEventListener("hardwareBackPress",()=>(He(),!0));return()=>x.remove()},[s,r]);let T=(0,A.useCallback)(()=>{let x=se.getState().active_key;x&&C(b=>({...b,[x]:(b[x]||0)+1}))},[]);return u.length?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(c,{visible:!!s,title:y!=null?y:"",is_dark:n,close:He,reload:T,subscribeWebAtTop:M.subscribe,children:u.map(x=>(0,I.jsx)(Yr,{instance_key:x,is_active:s===x,is_front:(s!=null?s:d.current)===x,is_dark:n,reload_tick:w[x]||0,web_at_top:M,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:l},x))}),(0,I.jsx)(Eo,{})]}):null},me=k.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"}}),Go=A.default.memo(Qr);0&&(module.exports={CodeType,DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,ScannerEndReason,ScannerEvent,ScannerLayout,ScannerMethod,ToastType,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
82
+ })(); true;`,Pr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),At=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},go=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:l,instance_id:c,options:s,emit:d,isActive:m,playBeep:y})=>{var P,x,b,Q,ee,oe,_e;let u=s==null?void 0:s.handlers,w={app_id:l,instance_id:c,close:a},C=()=>{var h;(h=s==null?void 0:s.haptic)==null||h.call(s,"impactLight"),y==null||y()},M=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=hn(t);return nt(e,()=>yn(h,m))}case"speech.start":{if(!d)throw M();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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let E of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[E])!==void 0){if(typeof t[E]!="boolean")throw new g("INVALID_PARAMS",`${E} ph\u1EA3i l\xE0 boolean`);h[E]=t[E]}return Vn(c,h,d,m)}case"speech.stop":return Bn(c);case We.scan:return Jn(c,$t(t),m,C);case We.start:{if(!d)throw M();return Gn(c,$t(t),d,m,C)}case We.stop:return Kn(c);case"uploadFiles":{let{task_id:h,...E}=t!=null?t:{};if(h!==void 0&&(typeof h!="string"||!h))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ln(xn(E),{instance_id:c,app_id:l,getContext:r,task_id:h,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>nt("uploadFiles.pick",j)})}case"uploadFiles.cancel":In(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return On(s==null?void 0:s.upload);case"getBiometricAvailability":return((P=s==null?void 0:s.biometrics)!=null?P:await Dt()).getAvailability();case"authenticateBiometric":{let h=At(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let E=t==null?void 0:t.cancelButtonText;if(E!==void 0&&(typeof E!="string"||!E.trim()||E.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return nt(e,async()=>{var T;return((T=s==null?void 0:s.biometrics)!=null?T:await Dt()).authenticate({reason:h,cancelButtonText:E})})}case"requestPayment":{let h=u==null?void 0:u.requestPayment;if(!h)throw M();let E=t==null?void 0:t.amount;if(typeof E!="number"||!Number.isFinite(E)||E<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:E,currency:At(t==null?void 0:t.currency,"currency")};return nt(e,()=>h(j,w))}case"printImage":{let h=u==null?void 0:u.printImage;if(!h)throw M();let E=At(t==null?void 0:t.image,"image");await nt(e,()=>h({image:E},w));return}case"openScreen":if(!(u!=null&&u.openScreen))throw M();await u.openScreen({screen:At(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},w);return;case"closeApp":a();return;case"openWebview":{let h=String((x=t==null?void 0:t.url)!=null?x:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(h):ot.Linking.openURL(h));return}case"openLink":{let h=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(h):ot.Linking.openURL(h))}catch(E){throw new g("NOT_SUPPORTED",String((ee=(Q=E==null?void 0:E.message)!=null?Q:E)!=null?ee:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let h=Dn(t);if(!h||(m==null?void 0:m())===!1)return;s!=null&&s.showToast?s.showToast(h.message,{type:h.type}):Nn(h.message,h.type);return}case"haptic":{let h=Pr.has(t==null?void 0:t.type)?t.type:"selection";(oe=s==null?void 0:s.haptic)==null||oe.call(s,h);return}case"getSystemInfo":return{platform:ot.Platform.OS==="ios"?"ios":"android",appVersion:(_e=s==null?void 0:s.app_version)!=null?_e:"",theme:i?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("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 T=n().access_token;if(!T)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return T}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let E=lo[h];if(!o().includes(E))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${E} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=h==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${E}`);return j}case"getUserInfo":{let h=n().user;if(!h)throw new g("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 g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Yt=e=>`bundle:${e}`,Xt=()=>`${B().file_system.document_dir}/miniapps`,Zt=Xt,Qt=(e,t,n="index.html",o=!1,r=[])=>{let i=`${Zt()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Kt=e=>{var t;B().storage.setString(Yt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Tr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,U=e=>{let t=B().storage.getString(Yt(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return Qt(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Me=e=>B().file_system.exists(e.entry_uri.replace("file://","")),en=async e=>{let t=U(e.app_id);return(t==null?void 0:t.version)===e.version&&await Me(t)},fo=async(e,t)=>{let n=B().file_system,o=`${Zt()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},ho=async e=>{var t;await((t=st[e])==null?void 0:t.catch(()=>{})),B().storage.setString(Yt(e),""),await B().file_system.remove(`${Zt()}/${e}`).catch(()=>{})},je=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},st={},yo=(e,t)=>{var i;let o=((i=st[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return st[e]=r,r.then(()=>{st[e]===r&&delete st[e]}),o},Cr=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let l=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(l)return l}return 0},wo=({manifest:e,zip_path:t})=>yo(e.app_id,async()=>{var i;let n=B().file_system,o=U(e.app_id);if(o&&Cr(o.version,e.version)>=0&&await Me(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=Qt(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),Kt(e),pe("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),fo(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),tn=(e,{base_url:t,onProgress:n}={})=>{let o=B().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(i)throw new je},c=async()=>{var m;l();let s=U(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return Kt(e),U(e.app_id);l();let d=o.download({url:t?Tr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(y,u)=>{var C;let w=u>0?u:(C=e.size)!=null?C:0;w>0&&(n==null||n(Math.min(1,y/w)))}});r=d;try{let{status:y}=await d.promise;if(l(),y!==200)throw new Error(`bundle ${y}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else pe("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let u=Qt(e.app_id,e.version,e.entry,!!e.context_update,(m=e.permissions)!=null?m:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(a,u.dir),Kt(e),fo(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),u}catch(y){throw i?new je:y}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:yo(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},it={},Or=__DEV__?0:60*1e3,mo={},_o=(e,t)=>{var o,r;let n=U(e);return n&&Date.now()-((o=mo[t])!=null?o:0)<Or?Promise.resolve(n):((r=it[e])!=null||(it[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),l=await tn(a,{base_url:t}).promise;return mo[t]=Date.now(),l})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),U(e))).finally(()=>{it[e]=void 0})),it[e])};var vt=new Map,bo=(e,t)=>(vt.set(e,t),()=>{vt.get(e)===t&&vt.delete(e)}),Ao=(e,t)=>{let n=vt.get(e);return n?n(t):!1};var $=require("react"),f=require("react-native");var v=require("react/jsx-runtime"),at="#22C55E",kr="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",Ir=2,xt=18,Lr=1600,ct=14,Fr=2e3,So=2,Dr=8,Nr=2e3,He=2e3,Ur=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:ct},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:ct},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:ct},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:ct}],vo=({color:e})=>(0,v.jsx)(v.Fragment,{children:Ur.map((t,n)=>(0,v.jsx)(f.View,{style:[S.corner,t,{borderColor:e}]},n))}),Mt=({style:e,children:t,...n})=>{let o=(0,$.useRef)(new f.Animated.Value(1)).current,r=i=>f.Animated.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return(0,v.jsx)(f.Pressable,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:(0,v.jsx)(f.Animated.View,{style:[e,{transform:[{scale:o}]}],children:t})})},on=({scanner:e})=>{var ut,Ke,Ye;let{vision:t,types:n,mode:o,layout:r,hint:i,glass_view:a}=e,l=r===ve.top,c=t.useCameraDevice("back"),s=(0,$.useRef)(new f.Animated.Value(1)).current,d=(0,$.useRef)(new f.Animated.Value(0)).current,[m,y]=(0,$.useState)(!1),[u,w]=(0,$.useState)(1),C=(0,$.useRef)(null),[M,P]=(0,$.useState)({width:0,height:0,window_y:0}),x=W(K,p=>p.last_value),b=W(K,p=>p.hit_tick),Q=W(K,p=>p.scan_count),ee=W(K,p=>p.notice),oe=W(K,p=>p.is_picking),_e=(0,$.useRef)(null),h=f.Platform.OS==="ios"?54:(ut=f.StatusBar.currentHeight)!=null?ut:0,E=(0,$.useRef)(new f.Animated.Value(0)).current,j=(0,$.useRef)(new f.Animated.Value(0)).current,T=(0,$.useRef)(new f.Animated.Value(0)).current,L=Math.round(M.width*(l?.8:.78)),V=Math.round(l?M.height*.46:L*.78),z=Math.round((M.height-V)/2),D=Math.round((M.width-L)/2),te=t.useCodeScanner({codeTypes:n,onCodeScanned:(0,$.useCallback)(p=>Ht(p),[])});(0,$.useEffect)(()=>{let p=f.BackHandler.addEventListener("hardwareBackPress",()=>(jt(),!0));return()=>p.remove()},[]);let Fe=(0,$.useRef)(b);(0,$.useEffect)(()=>{if(b===Fe.current)return;E.setValue(1),T.setValue(1);let p=f.Animated.parallel([f.Animated.timing(E,{toValue:0,duration:450,useNativeDriver:!0}),f.Animated.sequence([f.Animated.delay(Fr),f.Animated.timing(T,{toValue:0,duration:250,useNativeDriver:!0})])]);return p.start(),()=>p.stop()},[b,E,T]),(0,$.useEffect)(()=>{let p=H=>f.Animated.timing(j,{toValue:H,duration:Lr,easing:f.Easing.inOut(f.Easing.quad),useNativeDriver:!0}),_=f.Animated.loop(f.Animated.sequence([p(1),p(0)]));return _.start(),()=>_.stop()},[j]);let fe=(0,$.useCallback)(()=>{f.Animated.timing(s,{toValue:0,duration:220,useNativeDriver:!0}).start()},[s]);(0,$.useEffect)(()=>{let p=setTimeout(fe,Nr);return()=>clearTimeout(p)},[fe]);let ne=!!(c!=null&&c.hasTorch),Ee=(Ke=c==null?void 0:c.neutralZoom)!=null?Ke:1,be=c?Math.min(c.maxZoom/Ee,Dr):1,Re=Ee*Math.min(u,be),De=p=>{var re;let{touches:_}=p.nativeEvent;if(_.length!==2){C.current=null;return}let H=Math.hypot(_[0].pageX-_[1].pageX,_[0].pageY-_[1].pageY);(re=C.current)!=null||(C.current={distance:H,level:u}),w(Math.max(1,Math.min(be,C.current.level*(H/C.current.distance))))},It=(0,v.jsx)(f.Text,{style:[S.hint,!!ee&&S.hint_notice],numberOfLines:1,children:(Ye=ee!=null?ee:i)!=null?Ye:kr});return(0,v.jsx)(f.View,{ref:_e,onTouchMove:De,onTouchEnd:()=>{C.current=null},style:l?S.top:S.full,onLayout:({nativeEvent:{layout:p}})=>{var _;(_=_e.current)==null||_.measureInWindow((H,re)=>{P({width:p.width,height:p.height,window_y:re||0}),f.Animated.timing(d,{toValue:1,duration:180,useNativeDriver:!0}).start()})},children:(0,v.jsxs)(f.Animated.View,{style:[S.content,{opacity:d}],children:[c&&(0,v.jsx)(t.Camera,{style:f.StyleSheet.absoluteFill,device:c,isActive:!oe,codeScanner:te,torch:m&&ne?"on":"off",zoom:Re,onPreviewStarted:fe,onError:p=>Yn(p.message)}),(0,v.jsx)(f.Animated.View,{style:[S.preview_cover,{opacity:s}],pointerEvents:"none"}),M.height>0&&(0,v.jsxs)(f.View,{style:S.overlay,pointerEvents:"none",children:[(0,v.jsx)(f.View,{style:[S.dim_ring,{top:z-He,left:D-He,width:L+He*2,height:V+He*2}]}),(0,v.jsxs)(f.View,{style:{position:"absolute",top:z,left:D,width:L,height:V},children:[(0,v.jsx)(vo,{color:"#FFFFFF"}),(0,v.jsx)(f.Animated.View,{style:[f.StyleSheet.absoluteFill,{opacity:E}],children:(0,v.jsx)(vo,{color:at})}),(0,v.jsxs)(f.Animated.View,{style:[S.scan_line_wrap,{transform:[{translateY:j.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,V-xt)]})}]}],children:[(0,v.jsx)(f.View,{style:S.scan_glow_outer}),(0,v.jsx)(f.View,{style:S.scan_glow_inner}),(0,v.jsx)(f.View,{style:S.scan_line})]})]}),(0,v.jsx)(f.View,{style:[S.hint_slot,l?{top:0,height:z-6,justifyContent:"flex-end"}:{top:z+V+20}],children:It}),o===$e.continuous&&!!x&&(0,v.jsx)(f.Animated.View,{style:[S.result_slot,l?S.result_slot_top:{top:z+V+52},{opacity:T}],children:(0,v.jsxs)(f.View,{style:S.result,children:[(0,v.jsx)(f.View,{style:S.check_badge,children:(0,v.jsx)(f.View,{style:S.check_mark})}),(0,v.jsx)(f.Text,{style:S.result_text,numberOfLines:1,children:x}),(0,v.jsxs)(f.Text,{style:S.result_count,children:["\xB7 ",Q," m\xE3"]})]})})]}),M.height>0&&(0,v.jsx)(f.View,{style:[S.close_slot,{top:Math.max(12,h-M.window_y+12)}],children:(0,v.jsxs)(Mt,{style:[S.close_button,!!a&&S.glass_surface],onPress:jt,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&(0,v.jsx)(a,{style:S.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(f.View,{style:[S.close_bar,S.close_bar_a]}),(0,v.jsx)(f.View,{style:[S.close_bar,S.close_bar_b]})]})}),(0,v.jsx)(f.View,{style:[S.toolbar_wrap,!l&&S.toolbar_wrap_full],pointerEvents:"box-none",children:(0,v.jsxs)(f.View,{style:[S.toolbar,!!a&&S.glass_surface],children:[a&&(0,v.jsx)(a,{style:S.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),(0,v.jsx)(Mt,{style:S.tool,onPress:Xn,disabled:oe,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:(0,v.jsxs)(f.View,{style:S.image_icon,children:[(0,v.jsx)(f.View,{style:S.image_icon_dot}),(0,v.jsx)(f.View,{style:S.image_icon_hill})]})}),!!c&&be>=So&&(0,v.jsx)(Mt,{style:[S.tool,u>1&&S.tool_on],onPress:()=>w(p=>p>1?1:So),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:(0,v.jsxs)(f.Text,{style:[S.zoom_text,u>1&&S.zoom_text_on],children:[Math.round(u*10)/10,"x"]})}),ne&&(0,v.jsx)(Mt,{style:[S.tool,m&&S.tool_on],onPress:()=>y(p=>!p),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:m},children:(0,v.jsx)(f.Text,{style:[S.torch_icon,m&&S.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},Vr="rgba(0,0,0,0.5)",nn=50,S=f.StyleSheet.create({top:{height:"38%",overflow:"hidden"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,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:He,borderColor:Vr,borderRadius:He+ct},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:xt,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:xt,borderRadius:xt/2,backgroundColor:at,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:at,opacity:.2},scan_line:{height:Ir,borderRadius:1,backgroundColor:at},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_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_wrap_full:{bottom:f.Platform.OS==="ios"?34:20},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:nn,height:nn,borderRadius:nn/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_slot_top:{top:8},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:at},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 ge=require("react"),R=require("react-native");var Y=require("react/jsx-runtime"),Br={[ue.info]:"#3B82F6",[ue.success]:"#22C55E",[ue.error]:"#EF4444"},Mo=-120,qr=({type:e})=>e===ue.success?(0,Y.jsx)(R.View,{style:ie.check_mark}):e===ue.error?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(R.View,{style:[ie.cross_bar,ie.cross_a]}),(0,Y.jsx)(R.View,{style:[ie.cross_bar,ie.cross_b]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(R.View,{style:ie.info_dot}),(0,Y.jsx)(R.View,{style:ie.info_bar})]}),Eo=()=>{let e=W(tt,y=>y.message),t=W(tt,y=>y.type),n=W(tt,y=>y.tick),o=(0,ge.useRef)(new R.Animated.Value(Mo)).current,r=(0,ge.useRef)(new R.Animated.Value(0)).current,i=(0,ge.useRef)(new R.Animated.Value(.92)).current,a=(0,ge.useRef)(new R.Animated.Value(0)).current,[l,c]=(0,ge.useState)(),[s,d]=(0,ge.useState)(!1);(0,ge.useEffect)(()=>{let y=!0;return Wt().then(u=>{y&&u&&c(()=>u)}),()=>{y=!1}},[]);let m=(0,ge.useRef)(n);return(0,ge.useEffect)(()=>{if(n===m.current)return;R.AccessibilityInfo.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let y=R.Animated.sequence([R.Animated.parallel([R.Animated.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),R.Animated.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),R.Animated.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),R.Animated.sequence([R.Animated.delay(90),R.Animated.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),R.Animated.delay(Fn[t]),R.Animated.parallel([R.Animated.timing(o,{toValue:Mo,duration:240,useNativeDriver:!0}),R.Animated.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return y.start(({finished:u})=>{u&&d(!1)}),()=>y.stop()},[n]),s?(0,Y.jsx)(R.View,{style:ie.layer,pointerEvents:"none",children:(0,Y.jsxs)(R.Animated.View,{style:[ie.toast,!!l&&ie.toast_glass,{opacity:l?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[l&&(0,Y.jsx)(l,{style:ie.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),(0,Y.jsx)(R.Animated.View,{style:[ie.badge,{backgroundColor:Br[t],transform:[{scale:a}]}],children:(0,Y.jsx)(qr,{type:t})}),(0,Y.jsx)(R.Text,{style:ie.message,numberOfLines:2,children:e})]})}):null},xo,ie=R.StyleSheet.create({layer:{position:"absolute",top:(R.Platform.OS==="ios"?54:(xo=R.StatusBar.currentHeight)!=null?xo:0)+8,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_glass:{backgroundColor:"transparent"},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"},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 se=Te({active_key:null,instances:{}}),Ro=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var l;let a=(l=B().keep_alive)==null?void 0:l.max_webviews;se.setState(c=>{let s=t!=null?t:e.app_id,d={...c.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},m=Object.keys(d);return a&&a>0&&m.length>a&&m.filter(y=>y!==s).sort((y,u)=>d[y].last_used_at-d[u].last_used_at).slice(0,m.length-a).forEach(y=>{delete d[y]}),i?{active_key:s,instances:d}:{instances:d}})},Po=e=>Ro(e,!0),To=e=>Ro(e,!1),Je=()=>se.setState({active_key:null}),Et=e=>{se.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var Co="catalog",$r="paused_apps",zr="removed_apps",Wr=10*1e3,jr=2,Hr=3e3,Jr=()=>{var e;try{return JSON.parse((e=B().storage.getString(Co))!=null?e:"{}")}catch{return{}}},F=Te({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Oo=e=>{var t;return!!((t=B().manual_update)!=null&&t.includes(e))},Tt=new Set,ko=e=>{let t=new Set,n=()=>B().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=B().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},we=ko($r),Le=ko(zr);gn(()=>{we.load(),Le.load();let e=Jr(),t={};Object.keys(e).filter(n=>!Le.has(n)).forEach(n=>{let o=U(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:we.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),F.setState({catalog:e,downloads:t})});var Ct=e=>W(F,t=>e?t.downloads[e]:void 0),Io=()=>W(F,e=>e.pause_reasons.length>0),ye=(...e)=>pe("queue",...e),X=[],xe={},O=null,Rt=new Set,ze={},rn=new Set,ke=e=>{rn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Lo=e=>(rn.add(e),()=>{rn.delete(e)}),Fo=()=>F.getState().downloads,ae=(e,t)=>{let n=!!U(e),o=F.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};F.setState(a=>({downloads:{...a.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?ke({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&ke({type:"progress",app_id:e,progress:i.progress,version:i.version})},Pt=(e,t)=>{var n;(n=ze[e])==null||n.forEach(o=>o(t)),delete ze[e]},Gr=()=>F.getState().pause_reasons.length>0,Ie=e=>{var l;if(O)return;let t=e?X.indexOf(e):Gr()?-1:X.findIndex(c=>!we.has(c));if(t<0||t>=X.length)return;let[n]=X.splice(t,1),o=F.getState().catalog[n];if(!o){Pt(n,U(n)),Ie();return}let r=Date.now();xe[n]=((l=xe[n])!=null?l:0)+1,ae(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=tn(o,{onProgress:c=>{let s=Math.floor(c*100);s!==i&&(i=s,ae(n,{progress:s/100,version:o.version}))}});O={app_id:n,handle:a,forced:!!e},ye("start",n,o.version,e?"(forced)":""),a.promise.then(c=>{ye("installed",n,o.version,`${Date.now()-r}ms`),ae(n,{status:"installed",progress:1,version:o.version}),Pt(n,c)}).catch(c=>{var d;if(c instanceof je){if(Rt.has(n))return;ye("paused",n),xe[n]-=1,X.unshift(n),ae(n,{status:we.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=c==null?void 0:c.message)!=null?d:c);if(console.warn("[miniapp-queue] failed",n,s),xe[n]<jr){ae(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var m;X.includes(n)||(O==null?void 0:O.app_id)===n||(X.push(n),Ie((m=ze[n])!=null&&m.length?n:void 0))},Hr);return}ae(n,{status:"failed",progress:0,version:o.version,error:s}),Pt(n,U(n))}).finally(()=>{O=null;let c=X.find(s=>{var d;return(d=ze[s])==null?void 0:d.length});Ie(c)})},Ot=(e,{front:t=!1}={})=>{if((O==null?void 0:O.app_id)===e)return;let n=X.indexOf(e);if(n>=0){if(!t)return;X.splice(n,1)}t?X.unshift(e):X.push(e)},Kr=async e=>{let{host_id:t,client_token:n}=B(),o=new AbortController,r=setTimeout(()=>o.abort(),Wr);try{let i=`${gt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},lt=null,kt=()=>(lt!=null||(lt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(B().channels.map(Kr)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(F.getState().catalog).filter(c=>!o[c]);B().storage.setString(Co,JSON.stringify(o)),F.setState({catalog:o}),await Promise.all(r.map(c=>Do(c,{by_user:!1}))),r.forEach(c=>Le.delete(c));let i=Object.keys(o).filter(c=>!Le.has(c)),a=[],l={};for(let c of i.map(s=>o[s])){if(await en(c)){ae(c.app_id,{status:"installed",progress:1,version:c.version});continue}let s=U(c.app_id);if(Oo(c.app_id)&&!Tt.has(c.app_id)&&s&&await Me(s)){ae(c.app_id,{status:"installed",progress:1,version:s.version}),l[c.app_id]={app_id:c.app_id,current_version:s.version,next_version:c.version};continue}a.push(c)}return F.setState({updates:l}),a.forEach(c=>{xe[c.app_id]=0,ae(c.app_id,{status:we.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),Ot(c.app_id)}),ye("catalog",i.length,"apps, outdated",a.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),ke({type:"sync_complete",app_ids:i,removed:r}),Object.values(l).forEach(c=>ke({type:"update_available",...c})),Ie(),{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),ke({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{lt=null}})()),lt),Do=async(e,{by_user:t})=>{var r,i,a,l;if(t&&Le.add(e),Rt.has(e))return;Rt.add(e),we.delete(e);let n=X.indexOf(e);n>=0&&X.splice(n,1),(O==null?void 0:O.app_id)===e&&O.handle.cancel();let o=(l=(a=(r=F.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=U(e))==null?void 0:i.version)!=null?l:"";ae(e,{status:"uninstalling",progress:0,version:o}),await ho(e),Et(e),F.setState(c=>{let s={...c.downloads};return delete s[e],{downloads:s}}),delete xe[e],Rt.delete(e),Pt(e,null),ye("uninstalled",e,t?"(user)":"(not in list)"),ke({type:"uninstalled",app_id:e})},No=e=>Do(e,{by_user:!0}),Uo=e=>{let t=Ge(e);return t?(Le.delete(e),(O==null?void 0:O.app_id)===e||X.includes(e)||(xe[e]=0,ae(e,{status:we.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ot(e),Ie(),ye("restore",e)),!0):!1},Vo=e=>{if(we.has(e))return;if(we.add(e),ye("pause app",e),(O==null?void 0:O.app_id)===e&&!O.forced){O.handle.cancel();return}let t=F.getState().downloads[e];X.includes(e)&&t&&ae(e,{status:"paused",progress:0,version:t.version})},Bo=e=>{if(!we.delete(e))return;ye("resume app",e);let t=F.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!X.includes(e)&&Ge(e)&&(xe[e]=0,Ot(e)),X.includes(e)&&t&&ae(e,{status:"queued",progress:0,version:t.version}),Ie()},qo=e=>{let{pause_reasons:t}=F.getState();t.includes(e)||(F.setState({pause_reasons:[...t,e]}),ye("pause",e),t.length===0&&ke({type:"pause_change",paused:!0,reasons:[e]}),O&&!O.forced&&O.handle.cancel())},$o=e=>{let{pause_reasons:t}=F.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);F.setState({pause_reasons:n}),ye("resume",e),n.length===0&&ke({type:"pause_change",paused:!1,reasons:n}),Ie()},sn=e=>F.getState().updates[e],zo=async e=>{var n,o;let t=sn(e);Tt.add(e);try{let r=await pt(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=Ge(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(F.setState(a=>{var c;let l={...a.updates};return delete l[e],{updates:l,apply_ticks:{...a.apply_ticks,[e]:((c=a.apply_ticks[e])!=null?c:0)+1}}}),ye("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Tt.delete(e)}},Wo=()=>Object.values(F.getState().catalog).map(e=>({...e,installed:!!U(e.app_id),removed_by_user:Le.has(e.app_id)})),Ge=e=>F.getState().catalog[e],pt=async e=>{let t=Ge(e);if(!t)return;if(we.delete(e),Le.delete(e),await en(t))return U(e);let n=U(e);if(Oo(e)&&!Tt.has(e)&&n&&await Me(n))return n;let o=new Promise(r=>{var i;((i=ze[e])!=null?i:ze[e]=[]).push(r)});return(O==null?void 0:O.app_id)===e?O.forced=!0:(xe[e]=0,Ot(e,{front:!0}),O&&!O.forced?O.handle.cancel():Ie(e)),o};var I=require("react/jsx-runtime"),an=e=>(e!=null?e:"").replace(/\?[^#]*/,""),jo=0,Yr=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Xr=A.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:l,opaque_background:c,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var Ke,Ye;let m=(0,A.useRef)(null),y=(0,A.useRef)(!1),u=W(se,p=>p.instances[e]),w=u==null?void 0:u.app.app_id,C=u==null?void 0:u.app.manifest_url,M=u==null?void 0:u.context,P=u==null?void 0:u.url_params,x=W(K,p=>{var _;return((_=p.active)==null?void 0:_.owner)===e?p.active:null}),[b,Q]=(0,A.useState)(()=>w?U(w):null),[ee,oe]=(0,A.useState)(!1),[_e,h]=(0,A.useState)(0),[E,j]=(0,A.useState)(0),[T,L]=(0,A.useState)(!1),V=(0,A.useRef)(null),z=p=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{V.current=null,L(!0)},p)};(0,A.useEffect)(()=>()=>{V.current&&clearTimeout(V.current)},[]),(0,A.useEffect)(()=>{if(!w||!t&&b)return;let p=!0;return oe(!1),(async()=>{let _=U(w),H=_?await Me(_):!1;if(!p||(Q(H?he=>!he||he.version!==_.version||he.permissions.join(",")!==_.permissions.join(",")?_:he:null),__DEV__&&Date.now()-jo>1e4&&(jo=Date.now(),await kt()),!p))return;let re=await pt(w),Ne=re!==void 0?re:C?await _o(w,C):U(w);if(p){if(!Ne){oe(!0);return}Q(he=>he!=null?he:Ne)}})(),()=>{p=!1}},[t,w,C,_e]),(0,A.useEffect)(()=>bo(e,p=>m.current?(m.current.postMessage(p),!0):!1),[e]);let D=W(F,p=>{let _=w?p.downloads[w]:void 0;return(_==null?void 0:_.status)==="installed"?_.version:void 0});(0,A.useEffect)(()=>{if(t||!w||!b)return;let p=U(w);if(!p||p.version===b.version)return;let _=!0;return Me(p).then(H=>{!_||!H||(pe(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",b.version,"\u2192",p.version),Q(p))}),()=>{_=!1}},[t,w,D,b==null?void 0:b.version]);let te=W(F,p=>{var _;return w&&(_=p.apply_ticks[w])!=null?_:0});(0,A.useEffect)(()=>{if(!te||!w)return;let p=U(w);if(!p||p.version===(b==null?void 0:b.version))return;let _=!0;return Me(p).then(H=>{!_||!H||(pe(`webview:${e}`,"c\u1EADp nh\u1EADt",b==null?void 0:b.version,"\u2192",p.version),L(!1),Q(p))}),()=>{_=!1}},[te]),(0,A.useEffect)(()=>{var H;let p=(H=B().keep_alive)==null?void 0:H.idle_close_ms;if(t||!p||p<=0)return;let _=setTimeout(()=>{Et(e)},p);return()=>clearTimeout(_)},[t,e]),(0,A.useEffect)(()=>{r>0&&(oe(!1),L(!1),j(p=>p+1),h(p=>p+1))},[r]);let Fe=(0,A.useRef)(t);(0,A.useEffect)(()=>{var p;Fe.current!==t&&(Fe.current=t,y.current&&((p=m.current)==null||p.injectJavaScript(io(t?"resumed":"paused"))))},[t]);let fe=`${(Ke=b==null?void 0:b.version)!=null?Ke:"none"}:${(Ye=b==null?void 0:b.permissions.join(","))!=null?Ye:""}:${E}`,ne=(0,A.useMemo)(()=>JSON.stringify([M!=null?M:{},P!=null?P:{}]),[M,P]),Ee=(0,A.useMemo)(()=>{var p;return po(P!=null?P:{},(p=b==null?void 0:b.permissions)!=null?p:[])},[ne,b==null?void 0:b.permissions]),be=(0,A.useMemo)(()=>co(M!=null?M:{},Ee)+oo()+(k.Platform.OS==="android"?ro():"")+(B().debug?no():""),[Ee]),Re=(0,A.useRef)(null),De=(0,A.useRef)(null);(0,A.useEffect)(()=>{var _,H,re;if(!b)return;if(De.current!==fe){De.current=fe,Re.current=ne;return}if(Re.current===ne)return;let p=((H=JSON.parse((_=Re.current)!=null?_:"[]")[0])!=null?H:{}).org_id;if(Re.current=ne,p===(M==null?void 0:M.org_id)&&y.current){L(!1),z(1500),(re=m.current)==null||re.injectJavaScript(so(M!=null?M:{},Ee));return}L(!1),j(Ne=>Ne+1)},[ne,b,fe]),(0,A.useEffect)(()=>(t||(Se(e),Oe(e),Ve(e)),()=>{Se(e),Oe(e),Ve(e)}),[t,e,fe,r]),(0,A.useEffect)(()=>{let p=k.AppState.addEventListener("change",_=>{_==="background"&&!Un()&&Se(e),_==="background"&&!Wn()&&Oe(e)});return()=>p.remove()},[e]);let It=(0,A.useCallback)(async p=>{var H,re,Ne,he,Lt;let _=Zn(p.nativeEvent.data);if(!_){if(w&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(p.nativeEvent.data,{app_id:w,instance_id:e})).catch(q=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,q)})}catch(q){console.warn("[miniapp] onWebEvent l\u1ED7i",w,q)}return}if(_.method==="log"){let{level:q,text:J}=_;pe(`web:${e}`,q!=null?q:"log",J!=null?J:"");return}if(_.method==="pong"){V.current||L(!0);return}if(_.method==="touchAtTop"){i.emit(!!_.at_top);return}if(_.method==="contextApplied"){V.current&&clearTimeout(V.current),V.current=null,L(!0);return}if(_.method==="ready"){y.current=!0,L(!0);let q=(H=se.getState().instances[e])==null?void 0:H.context;q&&((re=m.current)==null||re.injectJavaScript(Gt(q)));return}try{let q=await go(_,{getHostData:()=>{var J,ce;return(ce=(J=se.getState().instances[e])==null?void 0:J.host_data)!=null?ce:{}},getPermissions:()=>{var J,ce;return w?(ce=(J=U(w))==null?void 0:J.permissions)!=null?ce:[]:[]},getContext:()=>{var J,ce;return(ce=(J=se.getState().instances[e])==null?void 0:J.context)!=null?ce:{}},is_dark:o,close:Je,app_id:w!=null?w:"",instance_id:e,options:l,emit:(J,ce)=>{var ln;(ln=m.current)==null||ln.injectJavaScript(to(J,ce))},playBeep:()=>{var J;(J=m.current)==null||J.injectJavaScript(uo())},isActive:()=>se.getState().active_key===e&&k.AppState.currentState!=="background"});_.id&&((Ne=m.current)==null||Ne.injectJavaScript(Qn(_.id,q)))}catch(q){if(!_.id)return;let J=q==null?void 0:q.code,ce=q instanceof g?q:new g(typeof J=="string"?J:"HOST_ERROR",String((he=q==null?void 0:q.message)!=null?he:q));(Lt=m.current)==null||Lt.injectJavaScript(eo(_.id,ce))}},[e,o,w,i,l]),ut=(0,A.useCallback)(()=>{oe(!1),j(p=>p+1),h(p=>p+1)},[]);return(0,I.jsxs)(k.View,{style:[k.StyleSheet.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&me.behind],pointerEvents:t?"auto":"none",children:[(x==null?void 0:x.layout)===ve.top&&(0,I.jsx)(on,{scanner:x}),b?(0,I.jsx)(Jo.default,{ref:m,source:{uri:b.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?Xt():b.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:be,onMessage:It,bounces:!1,overScrollMode:"never",onLoadStart:p=>{Se(e),Oe(e),Ve(e),pe(`webview:${e}`,"load start",an(p.nativeEvent.url)),y.current=!1,L(!1)},onError:p=>{Se(e),Oe(e),Ve(e),pe(`webview:${e}`,"load error",an(p.nativeEvent.url),p.nativeEvent.description),oe(!0),L(!1)},onLoadEnd:p=>{let _=p.nativeEvent.url;pe(`webview:${e}`,"load end",an(_)),w&&(d==null||d({app_id:w,instance_id:e,url:_})),z(1500)},onContentProcessDidTerminate:()=>{Se(e),Oe(e),Ve(e),y.current=!1,L(!1),j(p=>p+1)},onRenderProcessGone:()=>(Se(e),Oe(e),Ve(e),y.current=!1,L(!1),j(p=>p+1),!0),style:me.webview},fe):null,(x==null?void 0:x.layout)===ve.full&&(0,I.jsx)(on,{scanner:x}),u&&(0,I.jsx)(Qr,{visible:!b||!T,interactive:ee,children:(0,I.jsx)(Zr,{splash:a,app:u.app,is_dark:o,error:ee,has_bundle:!!b,retry:ut})})]})}),Zr=A.default.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,l=Ct(t.app_id),c=o?"error":!r&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return(0,I.jsx)(a,{app:t,is_dark:n,status:c,progress:c==="downloading"?l==null?void 0:l.progress:void 0,retry:i})}),Qr=({visible:e,interactive:t,children:n})=>{let o=(0,A.useRef)(new k.Animated.Value(e?1:0)).current,[r,i]=(0,A.useState)(e);return(0,A.useEffect)(()=>{if(e){i(!0),o.setValue(1);return}let a=k.Animated.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:l})=>{l&&i(!1)}),()=>a.stop()},[e,o]),r?(0,I.jsx)(k.Animated.View,{style:[k.StyleSheet.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},cn=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return(0,I.jsxs)(k.View,{style:[me.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,I.jsx)(k.View,{style:[me.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,I.jsx)(k.Image,{source:{uri:e.icon},style:me.splash_icon_image}):(0,I.jsx)(k.Text,{style:me.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,I.jsx)(k.Text,{style:[me.splash_name,{color:i}],children:e.name}),n==="error"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(k.Text,{style:me.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,I.jsx)(k.TouchableOpacity,{activeOpacity:.7,style:[me.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:(0,I.jsx)(k.Text,{style:[me.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(k.ActivityIndicator,{style:me.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,I.jsxs)(k.Text,{style:me.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},Ho=(e,t)=>{let n=(0,A.useRef)(t),o=(0,A.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.`))},ei=({container:e,splash:t=cn,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:l})=>{Ho("container",e),Ho("splash",t);let c=e,s=W(se,x=>x.active_key),d=(0,A.useRef)(s);s&&(d.current=s);let m=W(se,x=>Object.keys(x.instances).join("|")),y=W(se,x=>{var b;return x.active_key?(b=x.instances[x.active_key])==null?void 0:b.app.name:void 0}),u=(0,A.useMemo)(()=>m?m.split("|"):[],[m]),[w,C]=(0,A.useState)({}),M=(0,A.useRef)(Yr()).current;(0,A.useEffect)(()=>{if(!s||!r)return;let x=k.BackHandler.addEventListener("hardwareBackPress",()=>(Je(),!0));return()=>x.remove()},[s,r]);let P=(0,A.useCallback)(()=>{let x=se.getState().active_key;x&&C(b=>({...b,[x]:(b[x]||0)+1}))},[]);return u.length?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(c,{visible:!!s,title:y!=null?y:"",is_dark:n,close:Je,reload:P,subscribeWebAtTop:M.subscribe,children:u.map(x=>(0,I.jsx)(Xr,{instance_key:x,is_active:s===x,is_front:(s!=null?s:d.current)===x,is_dark:n,reload_tick:w[x]||0,web_at_top:M,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:l},x))}),(0,I.jsx)(Eo,{})]}):null},me=k.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"}}),Go=A.default.memo(ei);0&&(module.exports={CodeType,DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,ScannerEndReason,ScannerEvent,ScannerLayout,ScannerMethod,ToastType,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Lt="https://retion-miniapp-platform.vercel.app",De=null,wn=new Set,Xo=e=>{De=e,wn.forEach(t=>t())},F=()=>{if(!De)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return De},_n=e=>{wn.add(e),De&&e()},ae=(...e)=>{De!=null&&De.debug&&console.log("[miniapp]",...e)};var Zo=(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:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:c})=>r==null?void 0:r(l,c)});return{promise:a.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(i)}}}),Qo=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import fn,{useCallback as dn,useEffect as ie,useMemo as Ot,useRef as fe,useState as qe}from"react";import{AppState as Jo,ActivityIndicator as Ai,Animated as pn,BackHandler as Si,Image as vi,Platform as Mi,StyleSheet as hn,Text as dt,TouchableOpacity as xi,View as gn}from"react-native";import Ei from"react-native-webview";import{Linking as ao,Platform as Tr}from"react-native";var bn=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),mt,Ft=()=>(mt||(mt=import("react-native-biometrics").then(({default:e})=>bn(new e({allowDeviceCredentials:!1}))).catch(e=>{throw mt=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),mt);import{PermissionsAndroid as Ne,Platform as er}from"react-native";var An=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("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 g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,l]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<a||c>l))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${l} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},Sn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,s)=>{r||(r=!0,clearTimeout(a),c?o(c):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),l=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!l())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(l()){if(er.OS==="android"){let s=Ne.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ne.PERMISSIONS.ACCESS_COARSE_LOCATION,m=await Ne.check(s);if(!l())return;let h=m||await Ne.check(d);if(!l())return;if(!m&&!h){let u=await Ne.requestMultiple([s,d]);if(!l())return;if(u[s]!==Ne.RESULTS.GRANTED&&u[d]!==Ne.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}l()&&c.getCurrentPosition(s=>{l()&&i(void 0,s)},s=>{var m;if(!l())return;let d=(m={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?m:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(c=>i(c))});import{Platform as Pn}from"react-native";var Dt=20,vn=20,Cn=/^[a-z][a-z0-9_-]{0,31}$/,tr=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,nr=["low","medium","high"],Re=e=>!!e&&typeof e=="object"&&!Array.isArray(e),W=e=>new g("INVALID_PARAMS",e),Ze=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Mn=(e,t)=>{if(e===void 0)return{};if(!Re(e)||Object.keys(e).length>vn||Object.values(e).some(n=>typeof n!="string"))throw W(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${vn} key)`);return e},On=e=>{var n,o,r,i;if(e!==void 0&&!Re(e))throw W("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Cn.test(t.source)))throw W("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!tr.test(a))))throw W("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ze(t.max_count,1,Dt))throw W(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Dt}`);if(t.max_size!==void 0&&!Ze(t.max_size,1,Number.MAX_SAFE_INTEGER))throw W("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ze(t.concurrency,1,5))throw W("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(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:or(t.process),target:rr(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},or=e=>{if(e===void 0)return{};if(!Re(e))throw W("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Re(n))throw W("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Ze(n[o],1,1e4))throw W(`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 W("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(!Re(n))throw W("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ze(n.max_duration,1,3600))throw W("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!nr.includes(n.quality))throw W("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},rr=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Re(e))throw W("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Cn.test(t))throw W("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Re(e.params))throw W("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 W("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw W(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Mn(e.headers,"upload.headers"),form_data:Mn(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},kn=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},ir=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=kn(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},sr=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"},Ke,ar=()=>(Ke!=null||(Ke=import("react-native-image-picker").catch(e=>{throw Ke=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ke),xn=e=>async({accept:t,max_count:n,process:o})=>{var c,s,d,m,h,u,y,E,A;let r=await ar(),i=sr(t),a={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(m=(d=o.image)==null?void 0:d.quality)!=null?m:.8,videoQuality:(u=(h=o.video)==null?void 0:h.quality)!=null?u:"medium",durationLimit:(y=o.video)==null?void 0:y.max_duration,assetRepresentationMode:"compatible"},l=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(l.didCancel)return[];if(l.errorCode){let M=l.errorCode==="permission"?"PERMISSION_DENIED":l.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(M,(E=l.errorMessage)!=null?E:l.errorCode)}return((A=l.assets)!=null?A:[]).filter(M=>M.uri).map((M,S)=>{var _,K,Y;return{uri:M.uri,name:(_=M.fileName)!=null?_:`file_${S+1}`,mime_type:(K=M.type)!=null?K:"application/octet-stream",size:M.fileSize,width:M.width,height:M.height,duration:M.duration,processed:!((Y=M.type)!=null&&Y.startsWith("video/"))||Pn.OS==="ios"}})},cr={"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"},lr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},pr=e=>async({accept:t,max_count:n})=>{var i,a,l,c;let o=t.map(s=>{var d;return(d=cr[s])!=null?d:lr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,y)=>{var E,A,M;return{uri:u.uri,name:(E=u.name)!=null?E:`file_${y+1}`,mime_type:(A=u.type)!=null?A:"application/octet-stream",size:(M=u.size)!=null?M:void 0}});if(Pn.OS!=="android"||!e.keepLocalCopy||!d.some(u=>u.uri.startsWith("content://")))return d;let m=await e.keepLocalCopy({files:d.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),h=new Map(m.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return d.map(u=>{var y;return{...u,uri:(y=h.get(u.uri))!=null?y:u.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((c=(l=e.errorCodes)==null?void 0:l.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Ye,ur=async e=>(Ye!=null||(Ye=import("@react-native-documents/picker").then(t=>pr(t)).catch(t=>{throw Ye=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Ye)(e)),In={library:xn("library"),camera:xn("camera"),document:ur},En={type:"image",label:"\u1EA2nh",accept:["image/*"]},Rn={type:"video",label:"Video",accept:["video/*"]},Tn={library:[En,Rn],camera:[En,Rn],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"]}]},Xe,Ln=()=>(Xe!=null||(Xe=import("react-native-compressor").catch(()=>(Xe=void 0,null))),Xe),Fn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},dr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),gr={low:640,medium:1280,high:1920},mr=async(e,{image:t})=>{var o;if(!t||!dr.has(e.mime_type.toLowerCase()))return e;let n=await Ln();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 Fn(n,r,e.size),processed:!0}}catch{return e}},fr=async(e,{video:t})=>{var o;let n=await Ln();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:gr[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Fn(n,r,e.size),processed:!0}}catch{return e}},hr={image:mr,video:fr},yr=(e,t)=>t.split(".").reduce((n,o)=>Re(n)?n[o]:void 0,e),Dn=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let l=new XMLHttpRequest,c=new FormData;Object.entries(a.form_data).forEach(([m,h])=>c.append(m,h)),c.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>l.abort();o.addEventListener("abort",s);let d=m=>{o.removeEventListener("abort",s),m()};l.open("POST",a.url),Object.entries(a.headers).forEach(([m,h])=>l.setRequestHeader(m,h)),l.upload.onprogress=m=>n(m.loaded,m.total||e.size||0),l.onload=()=>d(()=>{let m=l.responseText;try{m=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${l.status}`));return}let h=yr(m,a.url_field);if(typeof h!="string"||!h){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:h,response:m})}),l.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),l.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),l.send(c)}),Nn=e=>{var o,r;let t={...In};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Dn};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},Un=e=>{let{sources:t,targets:n}=Nn(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===In[i]&&Tn[i]).map(i=>[i,Tn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Dt}},ht=new Map,Vn=(e,t)=>`${e}:${t}`,wr=0,Bn=(e,t)=>{var n;typeof t=="string"&&((n=ht.get(Vn(e,t)))==null||n.abort())},Ue=e=>{for(let[t,n]of ht)t.startsWith(`${e}:`)&&n.abort()},ft=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),_r=(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)}},qn=async(e,t)=>{var c;let{sources:n,targets:o}=Nn(t.config),r=n[e.source];if(!r)throw new g("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 g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,l=Vn(t.instance_id,(c=t.task_id)!=null?c:`auto-${++wr}`);ht.set(l,a);try{return await br(e,t,r,i,a.signal)}finally{ht.delete(l)}},br=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:l=m=>m()},c,s,d)=>{var f,v,B;let m={app_id:n!=null?n:"",instance_id:t,context:{...(f=o==null?void 0:o())!=null?f:{}}},h=(await l(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:m}))).slice(0,e.max_count);if(d.aborted)throw ft();if(!h.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],y=h.filter(x=>ir(x,e.accept)?!0:(u.push({name:x.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${x.mime_type||kn(x.name)}`}),!1)),E=y.map(()=>0),A=y.map(x=>{var P;return(P=x.size)!=null?P:0}),M=0,S=0,_=(x=!1)=>{if(!a||!r)return;let P=Date.now();if(!x&&P-S<200)return;S=P;let I=A.reduce((O,Z)=>O+Z,0),U=E.reduce((O,Z)=>O+Z,0);a("upload.progress",{task_id:r,loaded:U,total:I,percent:I?Math.min(100,Math.round(U/I*100)):0,done_count:M,count:y.length})},K=[],Y=0,ee=async()=>{var x,P,I;for(;Y<y.length;){let U=Y++,O=y[U];try{if(d.aborted)throw ft();let Z=O.mime_type.startsWith("image/")?"image":O.mime_type.startsWith("video/")?"video":void 0,Ie=Z&&!O.processed?(P=(x=i==null?void 0:i.processors)==null?void 0:x[Z])!=null?P:hr[Z]:void 0;if(Ie&&(O=await Ie(O,e.process),A[U]=(I=O.size)!=null?I:A[U],d.aborted))throw ft();if(e.max_size&&O.size&&O.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${O.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let pe=(Ee,Le)=>{E[U]=Ee,Le&&(A[U]=Le),_()},Q=await s({file:O,target:e.target,onProgress:pe,signal:d,caller:m});if(typeof(Q==null?void 0:Q.url)!="string"||!Q.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:xe,...ye}=Q;K[U]={url:xe,name:O.name,mime_type:O.mime_type,size:O.size,width:O.width,height:O.height,duration:O.duration,...Object.keys(ye).length?{response:"response"in ye?ye.response:ye}:{}},E[U]=A[U]}catch(Z){u.push(_r(y[U].name,Z))}finally{M++,_(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,y.length)},ee)),d.aborted)throw ft();let he=K.filter(x=>!!x);if(!he.length){let x=u[0];throw new g((v=x==null?void 0:x.code)!=null?v:"UPLOAD_FAILED",(B=x==null?void 0:x.message)!=null?B:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:he,failed:u}};import{useRef as Ar,useSyncExternalStore as Sr}from"react";var Te=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)})}},V=(e,t,n=Object.is)=>{let o=Ar(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let l=t(i),c=a&&n(a.value,l)?a.value:l;return o.current={state:i,selector:t,value:c},c};return Sr(e.subscribe,r)};var de={info:"info",success:"success",error:"error"},vr=200,$n={info:2e3,success:2e3,error:3e3},Qe=Te({message:"",type:de.info,tick:0}),zn=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,vr);return o?{message:o,type:Object.values(de).includes(n)?n:de.info}:null},Wn=(e,t=de.info)=>{Qe.setState(n=>({message:e,type:t,tick:n.tick+1}))};import{Platform as Zn}from"react-native";import{AppState as jn,Platform as Ut}from"react-native";var ce,Hn=()=>Ut.OS==="android"&&!!(ce!=null&&ce.requesting_permission),Mr=1500,yt=()=>new Promise(e=>{if(Ut.OS!=="android"||jn.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,Mr),o=jn.addEventListener("change",r=>{r==="active"&&t()})}),Nt=e=>{var t;if(ce===e&&(ce=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Ut.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Jn=async(e,t,n,o=()=>!0)=>{var i,a,l,c,s;if(ce)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};ce=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let m=d.ExpoSpeechRecognitionModule;if(r.native=m,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let h;try{h=await m.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await yt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!h.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await m.getStateAsync()!=="inactive")throw new g("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 g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(m.addListener("result",u=>{var y,E;ce!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(E=(y=u.results[0])==null?void 0:y.transcript)!=null?E:""})}),m.addListener("error",u=>{ce===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),m.addListener("end",()=>{ce===r&&(Nt(r),n("speech.end"))})),r.started=!0,m.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(l=t.interimResults)!=null?l:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Nt(r),d}},Gn=e=>{let t=ce;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},be=e=>{let t=ce;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Nt(t)}};var Kn={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"},X={...Kn,all:Object.values(Kn)},et={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},Bt={result:"scanner.result",end:"scanner.end"},$e={user:"user",web:"web",closed:"closed",error:"error"},Ae={top:"top",full:"full"},Ve={once:"once",continuous:"continuous"},xr=1500,Yn=6e4,k,j=Te({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Qn=()=>Zn.OS==="android"&&!!(k!=null&&k.requesting_permission),qt=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r}=e!=null?e:{},i={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(a=>X.all.includes(a)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");i.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Yn)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Yn}`);i.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");i.hint=o}if(r!==void 0){if(!Object.values(Ae).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");i.layout=r}return i},$t=e=>k!==e?!1:(k=void 0,j.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),eo=async(e,t)=>{if(k)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");k=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n(),e.requesting_permission=!0;let r;try{r=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await yt(),n(),r!=="granted")throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera");if(!o.Camera.getAvailableCameraDevices().some(a=>a.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let i=await zt();n(),j.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,hint:e.hint,vision:o,glass_view:i},last_value:null,scan_count:0,notice:null})}catch(o){throw $t(e),o}},zt=async()=>{if(Zn.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},to=(e,t,n)=>{var o,r,i;return{owner:e,mode:t,types:(o=n.types)!=null?o:X.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:xr,hint:n.hint,layout:t===Ve.once?Ae.full:(i=n.layout)!=null?i:Ae.top,cancelled:!1,requesting_permission:!1,last_seen:new Map}},no=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=to(e,Ve.once,t);a.onHit=o,a.resolve=r,a.reject=i,eo(a,n).catch(i)}),oo=(e,t,n,o=()=>!0,r)=>{let i=to(e,Ve.continuous,t);return i.emit=n,i.onHit=r,eo(i,o)},wt=(e,t,n)=>{var o,r;if(!j.getState().active){e.cancelled=!0;return}if($t(e)){if(e.mode===Ve.once){(o=e.reject)==null||o.call(e,t===$e.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,Bt.end,n?{reason:t,message:n}:{reason:t})}},ro=e=>{(k==null?void 0:k.owner)===e&&wt(k,$e.web)},Pe=e=>{(k==null?void 0:k.owner)===e&&wt(k,$e.closed)},Wt=()=>{k&&wt(k,$e.user)},io=e=>{k&&wt(k,$e.error,e)},jt=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=k;if(!(!o||!j.getState().active))for(let{value:l,type:c}of e){if(!l)continue;let s=o.last_seen.get(l);if(o.last_seen.set(l,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Ve.once){$t(o),(i=o.resolve)==null||i.call(o,{value:l,type:c});return}j.setState(d=>({last_value:l,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,Bt.result,{value:l,type:c})}}},Er={1:X.code128,2:X.code39,4:X.code93,8:X.codabar,16:X.dataMatrix,32:X.ean13,64:X.ean8,128:X.itf,256:X.qr,512:X.upcA,1024:X.upcE,2048:X.pdf417,4096:X.aztec},Rr=2500,Xn=2e3,Vt=e=>{j.setState({notice:e}),setTimeout(()=>{j.getState().notice===e&&j.setState({notice:null})},Rr)},so=async()=>{var t,n;let e=k;if(!(!e||j.getState().is_picking)){e.requesting_permission=!0,j.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:Xn,maxHeight:Xn}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||k!==e)return;if(r.errorCode||!i){Vt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),l=await a.scan(i);if(k!==e)return;let c=l.map(({value:s,format:d})=>({value:s,code_type:Er[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!c.length){Vt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}jt(c,Date.now(),!0)}catch{k===e&&Vt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await yt(),e.requesting_permission=!1,k===e&&j.setState({is_picking:!1})}}};var bt=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},co=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===bt&&typeof t.method=="string"?t:null}catch{return null}},nt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,lo=(e,t)=>nt({id:e,result:t}),po=(e,t)=>nt({id:e,error:{code:t.code,message:t.message}}),uo=(e,t)=>nt({event:e,data:t}),Jt=e=>nt({event:"context",data:e});var go=()=>`(function () {
1
+ var Lt="https://retion-miniapp-platform.vercel.app",De=null,_n=new Set,Xo=e=>{De=e,_n.forEach(t=>t())},F=()=>{if(!De)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return De},bn=e=>{_n.add(e),De&&e()},ae=(...e)=>{De!=null&&De.debug&&console.log("[miniapp]",...e)};var Zo=(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:a}=e.downloadFile({fromUrl:n,toFile:o,progressInterval:250,begin:()=>{},progress:({bytesWritten:l,contentLength:c})=>r==null?void 0:r(l,c)});return{promise:a.then(({statusCode:l})=>({status:l})),cancel:()=>e.stopDownload(i)}}}),Qo=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import hn,{useCallback as gn,useEffect as ie,useMemo as Ot,useRef as fe,useState as qe}from"react";import{AppState as Jo,ActivityIndicator as Mi,Animated as un,BackHandler as xi,Image as Ei,Platform as Ri,StyleSheet as yn,Text as dt,TouchableOpacity as Pi,View as mn}from"react-native";import Ti from"react-native-webview";import{Linking as ao,Platform as Or}from"react-native";var An=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),mt,Ft=()=>(mt||(mt=import("react-native-biometrics").then(({default:e})=>An(new e({allowDeviceCredentials:!1}))).catch(e=>{throw mt=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),mt);import{PermissionsAndroid as Ne,Platform as er}from"react-native";var Sn=e=>{var n,o,r;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("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 g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[i,a,l]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let c=t[i];if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<a||c>l))throw new g("INVALID_PARAMS",`${i} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${l} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(o=t.timeout)!=null?o:15e3,maximumAge:(r=t.maximumAge)!=null?r:0}},vn=(e,t=()=>!0)=>new Promise((n,o)=>{let r=!1,i=(c,s)=>{r||(r=!0,clearTimeout(a),c?o(c):n(s))},a=setTimeout(()=>i(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),l=()=>r?!1:t()?!0:(i(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!l())return;let c;try{c=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(l()){if(er.OS==="android"){let s=Ne.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ne.PERMISSIONS.ACCESS_COARSE_LOCATION,m=await Ne.check(s);if(!l())return;let h=m||await Ne.check(d);if(!l())return;if(!m&&!h){let u=await Ne.requestMultiple([s,d]);if(!l())return;if(u[s]!==Ne.RESULTS.GRANTED&&u[d]!==Ne.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}l()&&c.getCurrentPosition(s=>{l()&&i(void 0,s)},s=>{var m;if(!l())return;let d=(m={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?m:"LOCATION_ERROR";i(new g(d,s.message))},e)}})().catch(c=>i(c))});import{Platform as Cn}from"react-native";var Dt=20,Mn=20,On=/^[a-z][a-z0-9_-]{0,31}$/,tr=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,nr=["low","medium","high"],Re=e=>!!e&&typeof e=="object"&&!Array.isArray(e),W=e=>new g("INVALID_PARAMS",e),Ze=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,xn=(e,t)=>{if(e===void 0)return{};if(!Re(e)||Object.keys(e).length>Mn||Object.values(e).some(n=>typeof n!="string"))throw W(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Mn} key)`);return e},kn=e=>{var n,o,r,i;if(e!==void 0&&!Re(e))throw W("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!On.test(t.source)))throw W("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(a=>typeof a!="string"||!tr.test(a))))throw W("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ze(t.max_count,1,Dt))throw W(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Dt}`);if(t.max_size!==void 0&&!Ze(t.max_size,1,Number.MAX_SAFE_INTEGER))throw W("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ze(t.concurrency,1,5))throw W("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(a=>a.toLowerCase()),max_count:(r=t.max_count)!=null?r:1,max_size:t.max_size,process:or(t.process),target:rr(t.upload),concurrency:(i=t.concurrency)!=null?i:3}},or=e=>{if(e===void 0)return{};if(!Re(e))throw W("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!Re(n))throw W("process.image ph\u1EA3i l\xE0 object");for(let o of["max_width","max_height"])if(n[o]!==void 0&&!Ze(n[o],1,1e4))throw W(`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 W("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(!Re(n))throw W("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ze(n.max_duration,1,3600))throw W("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!nr.includes(n.quality))throw W("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},rr=e=>{var n,o,r,i;if(e===void 0)return{target:"host",params:{}};if(!Re(e))throw W("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!On.test(t))throw W("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!Re(e.params))throw W("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 W("upload.url ph\u1EA3i l\xE0 https");for(let a of["field_name","url_field"])if(e[a]!==void 0&&(typeof e[a]!="string"||!e[a]))throw W(`upload.${a} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:xn(e.headers,"upload.headers"),form_data:xn(e.form_data,"upload.form_data"),field_name:(r=e.field_name)!=null?r:"file",url_field:(i=e.url_field)!=null?i:"url"}},In=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},ir=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),o=In(e.name);return t.some(r=>r==="*/*"?!0:r.startsWith(".")?r===o:r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)},sr=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"},Ke,ar=()=>(Ke!=null||(Ke=import("react-native-image-picker").catch(e=>{throw Ke=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),Ke),En=e=>async({accept:t,max_count:n,process:o})=>{var c,s,d,m,h,u,y,E,A;let r=await ar(),i=sr(t),a={mediaType:i==="image"?"photo":i,maxWidth:(c=o.image)==null?void 0:c.max_width,maxHeight:(s=o.image)==null?void 0:s.max_height,quality:(m=(d=o.image)==null?void 0:d.quality)!=null?m:.8,videoQuality:(u=(h=o.video)==null?void 0:h.quality)!=null?u:"medium",durationLimit:(y=o.video)==null?void 0:y.max_duration,assetRepresentationMode:"compatible"},l=e==="camera"?await r.launchCamera({...a,saveToPhotos:!1}):await r.launchImageLibrary({...a,selectionLimit:n});if(l.didCancel)return[];if(l.errorCode){let M=l.errorCode==="permission"?"PERMISSION_DENIED":l.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new g(M,(E=l.errorMessage)!=null?E:l.errorCode)}return((A=l.assets)!=null?A:[]).filter(M=>M.uri).map((M,S)=>{var _,K,Y;return{uri:M.uri,name:(_=M.fileName)!=null?_:`file_${S+1}`,mime_type:(K=M.type)!=null?K:"application/octet-stream",size:M.fileSize,width:M.width,height:M.height,duration:M.duration,processed:!((Y=M.type)!=null&&Y.startsWith("video/"))||Cn.OS==="ios"}})},cr={"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"},lr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},pr=e=>async({accept:t,max_count:n})=>{var i,a,l,c;let o=t.map(s=>{var d;return(d=cr[s])!=null?d:lr[s]}),r=!t.length||o.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(o)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:r,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,y)=>{var E,A,M;return{uri:u.uri,name:(E=u.name)!=null?E:`file_${y+1}`,mime_type:(A=u.type)!=null?A:"application/octet-stream",size:(M=u.size)!=null?M:void 0}});if(Cn.OS!=="android"||!e.keepLocalCopy||!d.some(u=>u.uri.startsWith("content://")))return d;let m=await e.keepLocalCopy({files:d.map(u=>({uri:u.uri,fileName:u.name})),destination:"cachesDirectory"}),h=new Map(m.map(u=>[u.sourceUri,u.status==="success"?u.localUri:void 0]));return d.map(u=>{var y;return{...u,uri:(y=h.get(u.uri))!=null?y:u.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((a=(i=e.errorCodes)==null?void 0:i.OPERATION_CANCELED)!=null?a:"OPERATION_CANCELED"))return[];throw d===((c=(l=e.errorCodes)==null?void 0:l.IN_PROGRESS)!=null?c:"ASYNC_OP_IN_PROGRESS")?new g("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Ye,ur=async e=>(Ye!=null||(Ye=import("@react-native-documents/picker").then(t=>pr(t)).catch(t=>{throw Ye=void 0,new g("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Ye)(e)),Ln={library:En("library"),camera:En("camera"),document:ur},Rn={type:"image",label:"\u1EA2nh",accept:["image/*"]},Pn={type:"video",label:"Video",accept:["video/*"]},Tn={library:[Rn,Pn],camera:[Rn,Pn],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"]}]},Xe,Fn=()=>(Xe!=null||(Xe=import("react-native-compressor").catch(()=>(Xe=void 0,null))),Xe),Dn=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},dr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),gr={low:640,medium:1280,high:1920},mr=async(e,{image:t})=>{var o;if(!t||!dr.has(e.mime_type.toLowerCase()))return e;let n=await Fn();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 Dn(n,r,e.size),processed:!0}}catch{return e}},fr=async(e,{video:t})=>{var o;let n=await Fn();if(!n)return e;try{let r=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:gr[(o=t==null?void 0:t.quality)!=null?o:"medium"],minimumFileSizeForCompress:2});return{...e,uri:r,mime_type:"video/mp4",size:await Dn(n,r,e.size),processed:!0}}catch{return e}},hr={image:mr,video:fr},yr=(e,t)=>t.split(".").reduce((n,o)=>Re(n)?n[o]:void 0,e),Nn=({file:e,target:t,onProgress:n,signal:o})=>new Promise((r,i)=>{if(t.target!=="url"||!("url"in t)){i(new g("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let a=t;if(o.aborted){i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let l=new XMLHttpRequest,c=new FormData;Object.entries(a.form_data).forEach(([m,h])=>c.append(m,h)),c.append(a.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>l.abort();o.addEventListener("abort",s);let d=m=>{o.removeEventListener("abort",s),m()};l.open("POST",a.url),Object.entries(a.headers).forEach(([m,h])=>l.setRequestHeader(m,h)),l.upload.onprogress=m=>n(m.loaded,m.total||e.size||0),l.onload=()=>d(()=>{let m=l.responseText;try{m=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){i(new g("UPLOAD_FAILED",`HTTP ${l.status}`));return}let h=yr(m,a.url_field);if(typeof h!="string"||!h){i(new g("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${a.url_field}"`));return}r({url:h,response:m})}),l.onerror=()=>d(()=>i(new g("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),l.onabort=()=>d(()=>i(new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),l.send(c)}),Un=e=>{var o,r;let t={...Ln};for(let[i,a]of Object.entries((o=e==null?void 0:e.sources)!=null?o:{}))a?t[i]=a:delete t[i];let n={url:Nn};for(let[i,a]of Object.entries((r=e==null?void 0:e.targets)!=null?r:{}))i!=="url"&&a&&(n[i]=a);return{sources:t,targets:n}},Vn=e=>{let{sources:t,targets:n}=Un(e),o=Object.keys(t),r=Object.fromEntries(o.filter(i=>t[i]===Ln[i]&&Tn[i]).map(i=>[i,Tn[i]]));return{sources:o,file_types:r,targets:Object.keys(n),max_count:Dt}},ht=new Map,Bn=(e,t)=>`${e}:${t}`,wr=0,qn=(e,t)=>{var n;typeof t=="string"&&((n=ht.get(Bn(e,t)))==null||n.abort())},Ue=e=>{for(let[t,n]of ht)t.startsWith(`${e}:`)&&n.abort()},ft=()=>new g("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),_r=(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)}},$n=async(e,t)=>{var c;let{sources:n,targets:o}=Un(t.config),r=n[e.source];if(!r)throw new g("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 g("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let a=new AbortController,l=Bn(t.instance_id,(c=t.task_id)!=null?c:`auto-${++wr}`);ht.set(l,a);try{return await br(e,t,r,i,a.signal)}finally{ht.delete(l)}},br=async(e,{instance_id:t,app_id:n,getContext:o,task_id:r,config:i,emit:a,exclusivePick:l=m=>m()},c,s,d)=>{var f,v,B;let m={app_id:n!=null?n:"",instance_id:t,context:{...(f=o==null?void 0:o())!=null?f:{}}},h=(await l(()=>c({accept:e.accept,max_count:e.max_count,process:e.process,caller:m}))).slice(0,e.max_count);if(d.aborted)throw ft();if(!h.length)throw new g("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let u=[],y=h.filter(x=>ir(x,e.accept)?!0:(u.push({name:x.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${x.mime_type||In(x.name)}`}),!1)),E=y.map(()=>0),A=y.map(x=>{var T;return(T=x.size)!=null?T:0}),M=0,S=0,_=(x=!1)=>{if(!a||!r)return;let T=Date.now();if(!x&&T-S<200)return;S=T;let I=A.reduce((O,Z)=>O+Z,0),U=E.reduce((O,Z)=>O+Z,0);a("upload.progress",{task_id:r,loaded:U,total:I,percent:I?Math.min(100,Math.round(U/I*100)):0,done_count:M,count:y.length})},K=[],Y=0,ee=async()=>{var x,T,I;for(;Y<y.length;){let U=Y++,O=y[U];try{if(d.aborted)throw ft();let Z=O.mime_type.startsWith("image/")?"image":O.mime_type.startsWith("video/")?"video":void 0,Ie=Z&&!O.processed?(T=(x=i==null?void 0:i.processors)==null?void 0:x[Z])!=null?T:hr[Z]:void 0;if(Ie&&(O=await Ie(O,e.process),A[U]=(I=O.size)!=null?I:A[U],d.aborted))throw ft();if(e.max_size&&O.size&&O.size>e.max_size)throw new g("FILE_TOO_LARGE",`File ${O.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let pe=(Ee,Le)=>{E[U]=Ee,Le&&(A[U]=Le),_()},Q=await s({file:O,target:e.target,onProgress:pe,signal:d,caller:m});if(typeof(Q==null?void 0:Q.url)!="string"||!Q.url)throw new g("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:xe,...ye}=Q;K[U]={url:xe,name:O.name,mime_type:O.mime_type,size:O.size,width:O.width,height:O.height,duration:O.duration,...Object.keys(ye).length?{response:"response"in ye?ye.response:ye}:{}},E[U]=A[U]}catch(Z){u.push(_r(y[U].name,Z))}finally{M++,_(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,y.length)},ee)),d.aborted)throw ft();let he=K.filter(x=>!!x);if(!he.length){let x=u[0];throw new g((v=x==null?void 0:x.code)!=null?v:"UPLOAD_FAILED",(B=x==null?void 0:x.message)!=null?B:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:he,failed:u}};import{useRef as Ar,useSyncExternalStore as Sr}from"react";var Pe=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)})}},V=(e,t,n=Object.is)=>{let o=Ar(null),r=()=>{let i=e.getState(),a=o.current;if(a&&a.state===i&&a.selector===t)return a.value;let l=t(i),c=a&&n(a.value,l)?a.value:l;return o.current={state:i,selector:t,value:c},c};return Sr(e.subscribe,r)};var de={info:"info",success:"success",error:"error"},vr=200,zn={info:2e3,success:2e3,error:3e3},Qe=Pe({message:"",type:de.info,tick:0}),Wn=e=>{let{message:t,type:n}=e!=null?e:{},o=String(t!=null?t:"").trim().slice(0,vr);return o?{message:o,type:Object.values(de).includes(n)?n:de.info}:null},jn=(e,t=de.info)=>{Qe.setState(n=>({message:e,type:t,tick:n.tick+1}))};import{Alert as xr,Linking as Er,Platform as Bt}from"react-native";import{AppState as Hn,Platform as Ut}from"react-native";var ce,Jn=()=>Ut.OS==="android"&&!!(ce!=null&&ce.requesting_permission),Mr=1500,yt=()=>new Promise(e=>{if(Ut.OS!=="android"||Hn.currentState==="active"){e();return}let t=()=>{clearTimeout(n),o.remove(),e()},n=setTimeout(t,Mr),o=Hn.addEventListener("change",r=>{r==="active"&&t()})}),Nt=e=>{var t;if(ce===e&&(ce=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Ut.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Gn=async(e,t,n,o=()=>!0)=>{var i,a,l,c,s;if(ce)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!o())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let r={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};ce=r;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let m=d.ExpoSpeechRecognitionModule;if(r.native=m,r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.requesting_permission=!0;let h;try{h=await m.requestPermissionsAsync()}finally{r.requesting_permission=!1}if(await yt(),r.cancelled||!o())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!h.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await m.getStateAsync()!=="inactive")throw new g("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 g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");r.subscriptions.push(m.addListener("result",u=>{var y,E;ce!==r||r.cancelled||n(u.isFinal?"speech.final":"speech.partial",{...u,text:(E=(y=u.results[0])==null?void 0:y.transcript)!=null?E:""})}),m.addListener("error",u=>{ce===r&&!r.cancelled&&n("speech.error",{...u,code:u.error})}),m.addListener("end",()=>{ce===r&&(Nt(r),n("speech.end"))})),r.started=!0,m.start({lang:(i=t.lang)!=null?i:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(l=t.interimResults)!=null?l:!0,addsPunctuation:(c=t.addsPunctuation)!=null?c:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw Nt(r),d}},Kn=e=>{let t=ce;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},be=e=>{let t=ce;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Nt(t)}};var Yn={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"},X={...Yn,all:Object.values(Yn)},et={scan:"scanner.scan",start:"scanner.start",stop:"scanner.stop"},qt={result:"scanner.result",end:"scanner.end"},$e={user:"user",web:"web",closed:"closed",error:"error"},Ae={top:"top",full:"full"},Ve={once:"once",continuous:"continuous"},Rr=1500,Xn=6e4,k,j=Pe({active:null,last_value:null,hit_tick:0,scan_count:0,notice:null,is_picking:!1}),Qn=()=>Bt.OS==="android"&&!!(k!=null&&k.requesting_permission),$t=e=>{let{types:t,cooldown_ms:n,hint:o,layout:r}=e!=null?e:{},i={};if(t!==void 0){if(!Array.isArray(t)||!t.length||!t.every(a=>X.all.includes(a)))throw new g("INVALID_PARAMS","types ph\u1EA3i l\xE0 m\u1EA3ng CodeType");i.types=t}if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n)||n<0||n>Xn)throw new g("INVALID_PARAMS",`cooldown_ms ph\u1EA3i t\u1EEB 0 \u0111\u1EBFn ${Xn}`);i.cooldown_ms=n}if(o!==void 0){if(typeof o!="string"||!o.trim()||o.length>80)throw new g("INVALID_PARAMS","hint ph\u1EA3i c\xF3 1\u201380 k\xFD t\u1EF1");i.hint=o}if(r!==void 0){if(!Object.values(Ae).includes(r))throw new g("INVALID_PARAMS","layout ph\u1EA3i l\xE0 ScannerLayout");i.layout=r}return i},zt=e=>k!==e?!1:(k=void 0,j.setState({active:null,last_value:null,scan_count:0,notice:null,is_picking:!1}),!0),Pr=()=>xr.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:()=>{Er.openSettings().catch(()=>{})}}]),eo=async(e,t)=>{if(k)throw new g("BUSY","Camera qu\xE9t m\xE3 \u0111ang \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng");if(!t())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");k=e;let n=()=>{if(e.cancelled||!t())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng")};try{let o;try{o=await import("react-native-vision-camera")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module camera trong b\u1EA3n native")}n();let r=Bt.OS==="ios"&&o.Camera.getCameraPermissionStatus()==="denied";e.requesting_permission=!0;let i;try{i=await o.Camera.requestCameraPermission()}finally{e.requesting_permission=!1}if(await yt(),n(),i!=="granted")throw r&&Pr(),new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n camera");if(!o.Camera.getAvailableCameraDevices().some(l=>l.position==="back"))throw new g("NOT_SUPPORTED","Thi\u1EBFt b\u1ECB kh\xF4ng c\xF3 camera sau");let a=await Wt();n(),j.setState({active:{owner:e.owner,mode:e.mode,types:e.types,layout:e.layout,hint:e.hint,vision:o,glass_view:a},last_value:null,scan_count:0,notice:null})}catch(o){throw zt(e),o}},Wt=async()=>{if(Bt.OS==="ios")try{let e=await import("expo-glass-effect");return e.isLiquidGlassAvailable()?e.GlassView:void 0}catch{return}},to=(e,t,n)=>{var o,r,i;return{owner:e,mode:t,types:(o=n.types)!=null?o:X.all,cooldown_ms:(r=n.cooldown_ms)!=null?r:Rr,hint:n.hint,layout:t===Ve.once?Ae.full:(i=n.layout)!=null?i:Ae.top,cancelled:!1,requesting_permission:!1,last_seen:new Map}},no=(e,t,n=()=>!0,o)=>new Promise((r,i)=>{let a=to(e,Ve.once,t);a.onHit=o,a.resolve=r,a.reject=i,eo(a,n).catch(i)}),oo=(e,t,n,o=()=>!0,r)=>{let i=to(e,Ve.continuous,t);return i.emit=n,i.onHit=r,eo(i,o)},wt=(e,t,n)=>{var o,r;if(!j.getState().active){e.cancelled=!0;return}if(zt(e)){if(e.mode===Ve.once){(o=e.reject)==null||o.call(e,t===$e.error?new g("HOST_ERROR",n!=null?n:"L\u1ED7i camera"):new g("CANCELLED","\u0110\xE3 \u0111\xF3ng camera qu\xE9t m\xE3"));return}(r=e.emit)==null||r.call(e,qt.end,n?{reason:t,message:n}:{reason:t})}},ro=e=>{(k==null?void 0:k.owner)===e&&wt(k,$e.web)},Te=e=>{(k==null?void 0:k.owner)===e&&wt(k,$e.closed)},jt=()=>{k&&wt(k,$e.user)},io=e=>{k&&wt(k,$e.error,e)},Ht=(e,t=Date.now(),n=!1)=>{var r,i,a;let o=k;if(!(!o||!j.getState().active))for(let{value:l,type:c}of e){if(!l)continue;let s=o.last_seen.get(l);if(o.last_seen.set(l,t),!(!n&&s!==void 0&&t-s<o.cooldown_ms)){if((r=o.onHit)==null||r.call(o),o.mode===Ve.once){zt(o),(i=o.resolve)==null||i.call(o,{value:l,type:c});return}j.setState(d=>({last_value:l,hit_tick:d.hit_tick+1,scan_count:d.scan_count+1,notice:null})),(a=o.emit)==null||a.call(o,qt.result,{value:l,type:c})}}},Tr={1:X.code128,2:X.code39,4:X.code93,8:X.codabar,16:X.dataMatrix,32:X.ean13,64:X.ean8,128:X.itf,256:X.qr,512:X.upcA,1024:X.upcE,2048:X.pdf417,4096:X.aztec},Cr=2500,Zn=2e3,Vt=e=>{j.setState({notice:e}),setTimeout(()=>{j.getState().notice===e&&j.setState({notice:null})},Cr)},so=async()=>{var t,n;let e=k;if(!(!e||j.getState().is_picking)){e.requesting_permission=!0,j.setState({is_picking:!0,notice:null});try{let{launchImageLibrary:o}=await import("react-native-image-picker"),r=await o({mediaType:"photo",selectionLimit:1,maxWidth:Zn,maxHeight:Zn}),i=(n=(t=r.assets)==null?void 0:t[0])==null?void 0:n.uri;if(r.didCancel||k!==e)return;if(r.errorCode||!i){Vt("Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c \u1EA3nh");return}let{default:a}=await import("@react-native-ml-kit/barcode-scanning"),l=await a.scan(i);if(k!==e)return;let c=l.map(({value:s,format:d})=>({value:s,code_type:Tr[d]})).filter(({code_type:s})=>!s||e.types.includes(s)).map(({value:s,code_type:d})=>({value:s,type:d!=null?d:"unknown"}));if(!c.length){Vt("Kh\xF4ng t\xECm th\u1EA5y m\xE3 trong \u1EA3nh");return}Ht(c,Date.now(),!0)}catch{k===e&&Vt("Kh\xF4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c m\xE3 t\u1EEB \u1EA3nh")}finally{await yt(),e.requesting_permission=!1,k===e&&j.setState({is_picking:!1})}}};var bt=1,g=class extends Error{constructor(n,o){super(o);this.code=n}},co=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===bt&&typeof t.method=="string"?t:null}catch{return null}},nt=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,lo=(e,t)=>nt({id:e,result:t}),po=(e,t)=>nt({id:e,error:{code:t.code,message:t.message}}),uo=(e,t)=>nt({event:e,data:t}),Gt=e=>nt({event:"context",data:e});var go=()=>`(function () {
2
2
  var post = function (level, args) {
3
3
  try {
4
4
  var parts = [];
@@ -60,10 +60,10 @@ var Lt="https://retion-miniapp-platform.vercel.app",De=null,wn=new Set,Xo=e=>{De
60
60
  });
61
61
  };
62
62
  })(); true;`,ho=e=>nt({event:e}),yo=(e,t)=>{let n=wo(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
63
- ${Jt(e)}`},wo=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),_o=(e,t={})=>{let n=wo(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${bt} };
63
+ ${Gt(e)}`},wo=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),_o=(e,t={})=>{let n=wo(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${bt} };
64
64
  window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
65
65
  ${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
66
- true;`},bo={partner:"partner_token",chatbox:"chatbox_token"},Ao=(e,t)=>{let n={...e};for(let o of Object.values(bo))t.includes(o)||delete n[o];return n},Ht=new Set,tt=async(e,t)=>{if(Ht.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ht.add(e);try{return await t()}finally{Ht.delete(e)}},So=()=>`(function () {
66
+ true;`},bo={partner:"partner_token",chatbox:"chatbox_token"},Ao=(e,t)=>{let n={...e};for(let o of Object.values(bo))t.includes(o)||delete n[o];return n},Jt=new Set,tt=async(e,t)=>{if(Jt.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Jt.add(e);try{return await t()}finally{Jt.delete(e)}},So=()=>`(function () {
67
67
  try {
68
68
  var AudioCtx = window.AudioContext || window.webkitAudioContext;
69
69
  if (!AudioCtx) { return; }
@@ -79,4 +79,4 @@ var Lt="https://retion-miniapp-platform.vercel.app",De=null,wn=new Set,Xo=e=>{De
79
79
  oscillator.start(ctx.currentTime);
80
80
  oscillator.stop(ctx.currentTime + 0.08);
81
81
  } catch (e) {}
82
- })(); true;`,Pr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),_t=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},vo=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:l,instance_id:c,options:s,emit:d,isActive:m,playBeep:h})=>{var M,S,_,K,Y,ee,he;let u=s==null?void 0:s.handlers,y={app_id:l,instance_id:c,close:a},E=()=>{var f;(f=s==null?void 0:s.haptic)==null||f.call(s,"impactLight"),h==null||h()},A=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let f=An(t);return tt(e,()=>Sn(f,m))}case"speech.start":{if(!d)throw A();let f={};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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");f.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new g("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);f[v]=t[v]}return Jn(c,f,d,m)}case"speech.stop":return Gn(c);case et.scan:return no(c,qt(t),m,E);case et.start:{if(!d)throw A();return oo(c,qt(t),d,m,E)}case et.stop:return ro(c);case"uploadFiles":{let{task_id:f,...v}=t!=null?t:{};if(f!==void 0&&(typeof f!="string"||!f))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return qn(On(v),{instance_id:c,app_id:l,getContext:r,task_id:f,config:s==null?void 0:s.upload,emit:d,exclusivePick:B=>tt("uploadFiles.pick",B)})}case"uploadFiles.cancel":Bn(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Un(s==null?void 0:s.upload);case"getBiometricAvailability":return((M=s==null?void 0:s.biometrics)!=null?M:await Ft()).getAvailability();case"authenticateBiometric":{let f=_t(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return tt(e,async()=>{var x;return((x=s==null?void 0:s.biometrics)!=null?x:await Ft()).authenticate({reason:f,cancelButtonText:v})})}case"requestPayment":{let f=u==null?void 0:u.requestPayment;if(!f)throw A();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let B={...t,amount:v,currency:_t(t==null?void 0:t.currency,"currency")};return tt(e,()=>f(B,y))}case"printImage":{let f=u==null?void 0:u.printImage;if(!f)throw A();let v=_t(t==null?void 0:t.image,"image");await tt(e,()=>f({image:v},y));return}case"openScreen":if(!(u!=null&&u.openScreen))throw A();await u.openScreen({screen:_t(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":a();return;case"openWebview":{let f=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(f))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(f):ao.openURL(f));return}case"openLink":{let f=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(f):ao.openURL(f))}catch(v){throw new g("NOT_SUPPORTED",String((Y=(K=v==null?void 0:v.message)!=null?K:v)!=null?Y:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let f=zn(t);if(!f||(m==null?void 0:m())===!1)return;s!=null&&s.showToast?s.showToast(f.message,{type:f.type}):Wn(f.message,f.type);return}case"haptic":{let f=Pr.has(t==null?void 0:t.type)?t.type:"selection";(ee=s==null?void 0:s.haptic)==null||ee.call(s,f);return}case"getSystemInfo":return{platform:Tr.OS==="ios"?"ios":"android",appVersion:(he=s==null?void 0:s.app_version)!=null?he:"",theme:i?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let x=n().access_token;if(!x)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return x}if(f!=="partner"&&f!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let v=bo[f];if(!o().includes(v))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let B=f==="partner"?n().partner_token:n().chatbox_token;if(!B)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return B}case"getUserInfo":{let f=n().user;if(!f)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Kt=e=>`bundle:${e}`,Yt=()=>`${F().file_system.document_dir}/miniapps`,Xt=Yt,Zt=(e,t,n="index.html",o=!1,r=[])=>{let i=`${Xt()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Gt=e=>{var t;F().storage.setString(Kt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Cr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,L=e=>{let t=F().storage.getString(Kt(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return Zt(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Se=e=>F().file_system.exists(e.entry_uri.replace("file://","")),Qt=async e=>{let t=L(e.app_id);return(t==null?void 0:t.version)===e.version&&await Se(t)},xo=async(e,t)=>{let n=F().file_system,o=`${Xt()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},Eo=async e=>{var t;await((t=rt[e])==null?void 0:t.catch(()=>{})),F().storage.setString(Kt(e),""),await F().file_system.remove(`${Xt()}/${e}`).catch(()=>{})},ze=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},rt={},Ro=(e,t)=>{var i;let o=((i=rt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return rt[e]=r,r.then(()=>{rt[e]===r&&delete rt[e]}),o},Or=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let l=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(l)return l}return 0},kr=({manifest:e,zip_path:t})=>Ro(e.app_id,async()=>{var i;let n=F().file_system,o=L(e.app_id);if(o&&Or(o.version,e.version)>=0&&await Se(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=Zt(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),Gt(e),ae("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),xo(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),en=(e,{base_url:t,onProgress:n}={})=>{let o=F().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(i)throw new ze},c=async()=>{var m;l();let s=L(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return Gt(e),L(e.app_id);l();let d=o.download({url:t?Cr(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(h,u)=>{var E;let y=u>0?u:(E=e.size)!=null?E:0;y>0&&(n==null||n(Math.min(1,h/y)))}});r=d;try{let{status:h}=await d.promise;if(l(),h!==200)throw new Error(`bundle ${h}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else ae("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let u=Zt(e.app_id,e.version,e.entry,!!e.context_update,(m=e.permissions)!=null?m:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(a,u.dir),Gt(e),xo(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),u}catch(h){throw i?new ze:h}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:Ro(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},ot={},Ir=__DEV__?0:60*1e3,Mo={},To=(e,t)=>{var o,r;let n=L(e);return n&&Date.now()-((o=Mo[t])!=null?o:0)<Ir?Promise.resolve(n):((r=ot[e])!=null||(ot[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),l=await en(a,{base_url:t}).promise;return Mo[t]=Date.now(),l})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),L(e))).finally(()=>{ot[e]=void 0})),ot[e])};var At=new Map,Po=(e,t)=>(At.set(e,t),()=>{At.get(e)===t&&At.delete(e)}),Lr=(e,t)=>{let n=At.get(e);return n?n(t):!1};import{useCallback as Co,useEffect as St,useRef as ve,useState as tn}from"react";import{Animated as D,BackHandler as Fr,Easing as Oo,Platform as Lo,Pressable as Dr,StatusBar as Nr,StyleSheet as on,Text as it,View as z}from"react-native";import{Fragment as Hr,jsx as R,jsxs as we}from"react/jsx-runtime";var st="#22C55E",Ur="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",Vr=2,Mt=18,Br=1600,at=14,qr=2e3,ko=2,$r=8,zr=2e3,We=2e3,Wr=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:at},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:at},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:at},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:at}],Io=({color:e})=>R(Hr,{children:Wr.map((t,n)=>R(z,{style:[b.corner,t,{borderColor:e}]},n))}),vt=({style:e,children:t,...n})=>{let o=ve(new D.Value(1)).current,r=i=>D.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return R(Dr,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:R(D.View,{style:[e,{transform:[{scale:o}]}],children:t})})},rn=({scanner:e})=>{var gt,Je,Ge;let{vision:t,types:n,mode:o,layout:r,hint:i,glass_view:a}=e,l=r===Ae.top,c=t.useCameraDevice("back"),s=ve(new D.Value(1)).current,d=ve(new D.Value(0)).current,[m,h]=tn(!1),[u,y]=tn(1),E=ve(null),[A,M]=tn({width:0,height:0,window_y:0}),S=V(j,p=>p.last_value),_=V(j,p=>p.hit_tick),K=V(j,p=>p.scan_count),Y=V(j,p=>p.notice),ee=V(j,p=>p.is_picking),he=ve(null),f=Lo.OS==="ios"?54:(gt=Nr.currentHeight)!=null?gt:0,v=ve(new D.Value(0)).current,B=ve(new D.Value(0)).current,x=ve(new D.Value(0)).current,P=Math.round(A.width*(l?.8:.78)),I=Math.round(l?A.height*.46:P*.78),U=Math.round((A.height-I)/2),O=Math.round((A.width-P)/2),Z=t.useCodeScanner({codeTypes:n,onCodeScanned:Co(p=>jt(p),[])});St(()=>{let p=Fr.addEventListener("hardwareBackPress",()=>(Wt(),!0));return()=>p.remove()},[]);let Ie=ve(_);St(()=>{if(_===Ie.current)return;v.setValue(1),x.setValue(1);let p=D.parallel([D.timing(v,{toValue:0,duration:450,useNativeDriver:!0}),D.sequence([D.delay(qr),D.timing(x,{toValue:0,duration:250,useNativeDriver:!0})])]);return p.start(),()=>p.stop()},[_,v,x]),St(()=>{let p=q=>D.timing(B,{toValue:q,duration:Br,easing:Oo.inOut(Oo.quad),useNativeDriver:!0}),w=D.loop(D.sequence([p(1),p(0)]));return w.start(),()=>w.stop()},[B]);let pe=Co(()=>{D.timing(s,{toValue:0,duration:220,useNativeDriver:!0}).start()},[s]);St(()=>{let p=setTimeout(pe,zr);return()=>clearTimeout(p)},[pe]);let Q=!!(c!=null&&c.hasTorch),xe=(Je=c==null?void 0:c.neutralZoom)!=null?Je:1,ye=c?Math.min(c.maxZoom/xe,$r):1,Ee=xe*Math.min(u,ye),Le=p=>{var te;let{touches:w}=p.nativeEvent;if(w.length!==2){E.current=null;return}let q=Math.hypot(w[0].pageX-w[1].pageX,w[0].pageY-w[1].pageY);(te=E.current)!=null||(E.current={distance:q,level:u}),y(Math.max(1,Math.min(ye,E.current.level*(q/E.current.distance))))},kt=R(it,{style:[b.hint,!!Y&&b.hint_notice],numberOfLines:1,children:(Ge=Y!=null?Y:i)!=null?Ge:Ur});return R(z,{ref:he,onTouchMove:Le,onTouchEnd:()=>{E.current=null},style:l?b.top:b.full,onLayout:({nativeEvent:{layout:p}})=>{var w;(w=he.current)==null||w.measureInWindow((q,te)=>{M({width:p.width,height:p.height,window_y:te||0}),D.timing(d,{toValue:1,duration:180,useNativeDriver:!0}).start()})},children:we(D.View,{style:[b.content,{opacity:d}],children:[c&&R(t.Camera,{style:on.absoluteFill,device:c,isActive:!ee,codeScanner:Z,torch:m&&Q?"on":"off",zoom:Ee,onPreviewStarted:pe,onError:p=>io(p.message)}),R(D.View,{style:[b.preview_cover,{opacity:s}],pointerEvents:"none"}),A.height>0&&we(z,{style:b.overlay,pointerEvents:"none",children:[R(z,{style:[b.dim_ring,{top:U-We,left:O-We,width:P+We*2,height:I+We*2}]}),we(z,{style:{position:"absolute",top:U,left:O,width:P,height:I},children:[R(Io,{color:"#FFFFFF"}),R(D.View,{style:[on.absoluteFill,{opacity:v}],children:R(Io,{color:st})}),we(D.View,{style:[b.scan_line_wrap,{transform:[{translateY:B.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,I-Mt)]})}]}],children:[R(z,{style:b.scan_glow_outer}),R(z,{style:b.scan_glow_inner}),R(z,{style:b.scan_line})]})]}),R(z,{style:[b.hint_slot,l?{top:0,height:U-6,justifyContent:"flex-end"}:{top:U+I+20}],children:kt}),o===Ve.continuous&&!!S&&R(D.View,{style:[b.result_slot,l?b.result_slot_top:{top:U+I+52},{opacity:x}],children:we(z,{style:b.result,children:[R(z,{style:b.check_badge,children:R(z,{style:b.check_mark})}),R(it,{style:b.result_text,numberOfLines:1,children:S}),we(it,{style:b.result_count,children:["\xB7 ",K," m\xE3"]})]})})]}),A.height>0&&R(z,{style:[b.close_slot,{top:Math.max(12,f-A.window_y+12)}],children:we(vt,{style:[b.close_button,!!a&&b.glass_surface],onPress:Wt,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&R(a,{style:b.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),R(z,{style:[b.close_bar,b.close_bar_a]}),R(z,{style:[b.close_bar,b.close_bar_b]})]})}),R(z,{style:[b.toolbar_wrap,!l&&b.toolbar_wrap_full],pointerEvents:"box-none",children:we(z,{style:[b.toolbar,!!a&&b.glass_surface],children:[a&&R(a,{style:b.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),R(vt,{style:b.tool,onPress:so,disabled:ee,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:we(z,{style:b.image_icon,children:[R(z,{style:b.image_icon_dot}),R(z,{style:b.image_icon_hill})]})}),!!c&&ye>=ko&&R(vt,{style:[b.tool,u>1&&b.tool_on],onPress:()=>y(p=>p>1?1:ko),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:we(it,{style:[b.zoom_text,u>1&&b.zoom_text_on],children:[Math.round(u*10)/10,"x"]})}),Q&&R(vt,{style:[b.tool,m&&b.tool_on],onPress:()=>h(p=>!p),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:m},children:R(it,{style:[b.torch_icon,m&&b.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},jr="rgba(0,0,0,0.5)",nn=50,b=on.create({top:{height:"38%",overflow:"hidden"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,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:We,borderColor:jr,borderRadius:We+at},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:Mt,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Mt,borderRadius:Mt/2,backgroundColor:st,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:st,opacity:.2},scan_line:{height:Vr,borderRadius:1,backgroundColor:st},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_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_wrap_full:{bottom:Lo.OS==="ios"?34:20},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:nn,height:nn,borderRadius:nn/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_slot_top:{top:8},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:st},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 Fo,useRef as ct,useState as Do}from"react";import{AccessibilityInfo as Jr,Animated as H,Platform as Gr,StatusBar as Kr,StyleSheet as Yr,Text as Xr,View as je}from"react-native";import{Fragment as Uo,jsx as _e,jsxs as sn}from"react/jsx-runtime";var Zr={[de.info]:"#3B82F6",[de.success]:"#22C55E",[de.error]:"#EF4444"},No=-120,Qr=({type:e})=>e===de.success?_e(je,{style:ne.check_mark}):e===de.error?sn(Uo,{children:[_e(je,{style:[ne.cross_bar,ne.cross_a]}),_e(je,{style:[ne.cross_bar,ne.cross_b]})]}):sn(Uo,{children:[_e(je,{style:ne.info_dot}),_e(je,{style:ne.info_bar})]}),Bo=()=>{let e=V(Qe,h=>h.message),t=V(Qe,h=>h.type),n=V(Qe,h=>h.tick),o=ct(new H.Value(No)).current,r=ct(new H.Value(0)).current,i=ct(new H.Value(.92)).current,a=ct(new H.Value(0)).current,[l,c]=Do(),[s,d]=Do(!1);Fo(()=>{let h=!0;return zt().then(u=>{h&&u&&c(()=>u)}),()=>{h=!1}},[]);let m=ct(n);return Fo(()=>{if(n===m.current)return;Jr.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let h=H.sequence([H.parallel([H.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),H.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),H.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),H.sequence([H.delay(90),H.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),H.delay($n[t]),H.parallel([H.timing(o,{toValue:No,duration:240,useNativeDriver:!0}),H.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return h.start(({finished:u})=>{u&&d(!1)}),()=>h.stop()},[n]),s?_e(je,{style:ne.layer,pointerEvents:"none",children:sn(H.View,{style:[ne.toast,!!l&&ne.toast_glass,{opacity:l?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[l&&_e(l,{style:ne.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),_e(H.View,{style:[ne.badge,{backgroundColor:Zr[t],transform:[{scale:a}]}],children:_e(Qr,{type:t})}),_e(Xr,{style:ne.message,numberOfLines:2,children:e})]})}):null},Vo,ne=Yr.create({layer:{position:"absolute",top:(Gr.OS==="ios"?54:(Vo=Kr.currentHeight)!=null?Vo:0)+8,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_glass:{backgroundColor:"transparent"},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"},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 oe=Te({active_key:null,instances:{}}),qo=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var l;let a=(l=F().keep_alive)==null?void 0:l.max_webviews;oe.setState(c=>{let s=t!=null?t:e.app_id,d={...c.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},m=Object.keys(d);return a&&a>0&&m.length>a&&m.filter(h=>h!==s).sort((h,u)=>d[h].last_used_at-d[u].last_used_at).slice(0,m.length-a).forEach(h=>{delete d[h]}),i?{active_key:s,instances:d}:{instances:d}})},ei=e=>qo(e,!0),ti=e=>qo(e,!1),lt=()=>oe.setState({active_key:null}),xt=e=>{oe.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var $o="catalog",ni="paused_apps",oi="removed_apps",ri=10*1e3,ii=2,si=3e3,ai=()=>{var e;try{return JSON.parse((e=F().storage.getString($o))!=null?e:"{}")}catch{return{}}},C=Te({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),zo=e=>{var t;return!!((t=F().manual_update)!=null&&t.includes(e))},Tt=new Set,Wo=e=>{let t=new Set,n=()=>F().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=F().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},me=Wo(ni),ke=Wo(oi);_n(()=>{me.load(),ke.load();let e=ai(),t={};Object.keys(e).filter(n=>!ke.has(n)).forEach(n=>{let o=L(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:me.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),C.setState({catalog:e,downloads:t})});var cn=e=>V(C,t=>e?t.downloads[e]:void 0),ci=()=>V(C,e=>e.pause_reasons.length>0),ge=(...e)=>ae("queue",...e),J=[],Me={},T=null,Et=new Set,Be={},an=new Set,Ce=e=>{an.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},li=e=>(an.add(e),()=>{an.delete(e)}),pi=()=>C.getState().downloads,re=(e,t)=>{let n=!!L(e),o=C.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};C.setState(a=>({downloads:{...a.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?Ce({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Ce({type:"progress",app_id:e,progress:i.progress,version:i.version})},Rt=(e,t)=>{var n;(n=Be[e])==null||n.forEach(o=>o(t)),delete Be[e]},ui=()=>C.getState().pause_reasons.length>0,Oe=e=>{var l;if(T)return;let t=e?J.indexOf(e):ui()?-1:J.findIndex(c=>!me.has(c));if(t<0||t>=J.length)return;let[n]=J.splice(t,1),o=C.getState().catalog[n];if(!o){Rt(n,L(n)),Oe();return}let r=Date.now();Me[n]=((l=Me[n])!=null?l:0)+1,re(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=en(o,{onProgress:c=>{let s=Math.floor(c*100);s!==i&&(i=s,re(n,{progress:s/100,version:o.version}))}});T={app_id:n,handle:a,forced:!!e},ge("start",n,o.version,e?"(forced)":""),a.promise.then(c=>{ge("installed",n,o.version,`${Date.now()-r}ms`),re(n,{status:"installed",progress:1,version:o.version}),Rt(n,c)}).catch(c=>{var d;if(c instanceof ze){if(Et.has(n))return;ge("paused",n),Me[n]-=1,J.unshift(n),re(n,{status:me.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=c==null?void 0:c.message)!=null?d:c);if(console.warn("[miniapp-queue] failed",n,s),Me[n]<ii){re(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var m;J.includes(n)||(T==null?void 0:T.app_id)===n||(J.push(n),Oe((m=Be[n])!=null&&m.length?n:void 0))},si);return}re(n,{status:"failed",progress:0,version:o.version,error:s}),Rt(n,L(n))}).finally(()=>{T=null;let c=J.find(s=>{var d;return(d=Be[s])==null?void 0:d.length});Oe(c)})},Pt=(e,{front:t=!1}={})=>{if((T==null?void 0:T.app_id)===e)return;let n=J.indexOf(e);if(n>=0){if(!t)return;J.splice(n,1)}t?J.unshift(e):J.push(e)},di=async e=>{let{host_id:t,client_token:n}=F(),o=new AbortController,r=setTimeout(()=>o.abort(),ri);try{let i=`${Lt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},pt=null,ln=()=>(pt!=null||(pt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(F().channels.map(di)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(C.getState().catalog).filter(c=>!o[c]);F().storage.setString($o,JSON.stringify(o)),C.setState({catalog:o}),await Promise.all(r.map(c=>jo(c,{by_user:!1}))),r.forEach(c=>ke.delete(c));let i=Object.keys(o).filter(c=>!ke.has(c)),a=[],l={};for(let c of i.map(s=>o[s])){if(await Qt(c)){re(c.app_id,{status:"installed",progress:1,version:c.version});continue}let s=L(c.app_id);if(zo(c.app_id)&&!Tt.has(c.app_id)&&s&&await Se(s)){re(c.app_id,{status:"installed",progress:1,version:s.version}),l[c.app_id]={app_id:c.app_id,current_version:s.version,next_version:c.version};continue}a.push(c)}return C.setState({updates:l}),a.forEach(c=>{Me[c.app_id]=0,re(c.app_id,{status:me.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),Pt(c.app_id)}),ge("catalog",i.length,"apps, outdated",a.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),Ce({type:"sync_complete",app_ids:i,removed:r}),Object.values(l).forEach(c=>Ce({type:"update_available",...c})),Oe(),{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),Ce({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{pt=null}})()),pt),jo=async(e,{by_user:t})=>{var r,i,a,l;if(t&&ke.add(e),Et.has(e))return;Et.add(e),me.delete(e);let n=J.indexOf(e);n>=0&&J.splice(n,1),(T==null?void 0:T.app_id)===e&&T.handle.cancel();let o=(l=(a=(r=C.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=L(e))==null?void 0:i.version)!=null?l:"";re(e,{status:"uninstalling",progress:0,version:o}),await Eo(e),xt(e),C.setState(c=>{let s={...c.downloads};return delete s[e],{downloads:s}}),delete Me[e],Et.delete(e),Rt(e,null),ge("uninstalled",e,t?"(user)":"(not in list)"),Ce({type:"uninstalled",app_id:e})},gi=e=>jo(e,{by_user:!0}),mi=e=>{let t=ut(e);return t?(ke.delete(e),(T==null?void 0:T.app_id)===e||J.includes(e)||(Me[e]=0,re(e,{status:me.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Pt(e),Oe(),ge("restore",e)),!0):!1},fi=e=>{if(me.has(e))return;if(me.add(e),ge("pause app",e),(T==null?void 0:T.app_id)===e&&!T.forced){T.handle.cancel();return}let t=C.getState().downloads[e];J.includes(e)&&t&&re(e,{status:"paused",progress:0,version:t.version})},hi=e=>{if(!me.delete(e))return;ge("resume app",e);let t=C.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!J.includes(e)&&ut(e)&&(Me[e]=0,Pt(e)),J.includes(e)&&t&&re(e,{status:"queued",progress:0,version:t.version}),Oe()},yi=e=>{let{pause_reasons:t}=C.getState();t.includes(e)||(C.setState({pause_reasons:[...t,e]}),ge("pause",e),t.length===0&&Ce({type:"pause_change",paused:!0,reasons:[e]}),T&&!T.forced&&T.handle.cancel())},wi=e=>{let{pause_reasons:t}=C.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);C.setState({pause_reasons:n}),ge("resume",e),n.length===0&&Ce({type:"pause_change",paused:!1,reasons:n}),Oe()},Ho=e=>C.getState().updates[e],_i=async e=>{var n,o;let t=Ho(e);Tt.add(e);try{let r=await Ct(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=ut(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(C.setState(a=>{var c;let l={...a.updates};return delete l[e],{updates:l,apply_ticks:{...a.apply_ticks,[e]:((c=a.apply_ticks[e])!=null?c:0)+1}}}),ge("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Tt.delete(e)}},bi=()=>Object.values(C.getState().catalog).map(e=>({...e,installed:!!L(e.app_id),removed_by_user:ke.has(e.app_id)})),ut=e=>C.getState().catalog[e],Ct=async e=>{let t=ut(e);if(!t)return;if(me.delete(e),ke.delete(e),await Qt(t))return L(e);let n=L(e);if(zo(e)&&!Tt.has(e)&&n&&await Se(n))return n;let o=new Promise(r=>{var i;((i=Be[e])!=null?i:Be[e]=[]).push(r)});return(T==null?void 0:T.app_id)===e?T.forced=!0:(Me[e]=0,Pt(e,{front:!0}),T&&!T.forced?T.handle.cancel():Oe(e)),o};import{Fragment as mn,jsx as G,jsxs as He}from"react/jsx-runtime";var un=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Go=0,Ri=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Ti=fn.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:l,opaque_background:c,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var Je,Ge;let m=fe(null),h=fe(!1),u=V(oe,p=>p.instances[e]),y=u==null?void 0:u.app.app_id,E=u==null?void 0:u.app.manifest_url,A=u==null?void 0:u.context,M=u==null?void 0:u.url_params,S=V(j,p=>{var w;return((w=p.active)==null?void 0:w.owner)===e?p.active:null}),[_,K]=qe(()=>y?L(y):null),[Y,ee]=qe(!1),[he,f]=qe(0),[v,B]=qe(0),[x,P]=qe(!1),I=fe(null),U=p=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,P(!0)},p)};ie(()=>()=>{I.current&&clearTimeout(I.current)},[]),ie(()=>{if(!y||!t&&_)return;let p=!0;return ee(!1),(async()=>{let w=L(y),q=w?await Se(w):!1;if(!p||(K(q?ue=>!ue||ue.version!==w.version||ue.permissions.join(",")!==w.permissions.join(",")?w:ue:null),__DEV__&&Date.now()-Go>1e4&&(Go=Date.now(),await ln()),!p))return;let te=await Ct(y),Fe=te!==void 0?te:E?await To(y,E):L(y);if(p){if(!Fe){ee(!0);return}K(ue=>ue!=null?ue:Fe)}})(),()=>{p=!1}},[t,y,E,he]),ie(()=>Po(e,p=>m.current?(m.current.postMessage(p),!0):!1),[e]);let O=V(C,p=>{let w=y?p.downloads[y]:void 0;return(w==null?void 0:w.status)==="installed"?w.version:void 0});ie(()=>{if(t||!y||!_)return;let p=L(y);if(!p||p.version===_.version)return;let w=!0;return Se(p).then(q=>{!w||!q||(ae(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",_.version,"\u2192",p.version),K(p))}),()=>{w=!1}},[t,y,O,_==null?void 0:_.version]);let Z=V(C,p=>{var w;return y&&(w=p.apply_ticks[y])!=null?w:0});ie(()=>{if(!Z||!y)return;let p=L(y);if(!p||p.version===(_==null?void 0:_.version))return;let w=!0;return Se(p).then(q=>{!w||!q||(ae(`webview:${e}`,"c\u1EADp nh\u1EADt",_==null?void 0:_.version,"\u2192",p.version),P(!1),K(p))}),()=>{w=!1}},[Z]),ie(()=>{var q;let p=(q=F().keep_alive)==null?void 0:q.idle_close_ms;if(t||!p||p<=0)return;let w=setTimeout(()=>{xt(e)},p);return()=>clearTimeout(w)},[t,e]),ie(()=>{r>0&&(ee(!1),P(!1),B(p=>p+1),f(p=>p+1))},[r]);let Ie=fe(t);ie(()=>{var p;Ie.current!==t&&(Ie.current=t,h.current&&((p=m.current)==null||p.injectJavaScript(ho(t?"resumed":"paused"))))},[t]);let pe=`${(Je=_==null?void 0:_.version)!=null?Je:"none"}:${(Ge=_==null?void 0:_.permissions.join(","))!=null?Ge:""}:${v}`,Q=Ot(()=>JSON.stringify([A!=null?A:{},M!=null?M:{}]),[A,M]),xe=Ot(()=>{var p;return Ao(M!=null?M:{},(p=_==null?void 0:_.permissions)!=null?p:[])},[Q,_==null?void 0:_.permissions]),ye=Ot(()=>_o(A!=null?A:{},xe)+mo()+(Mi.OS==="android"?fo():"")+(F().debug?go():""),[xe]),Ee=fe(null),Le=fe(null);ie(()=>{var w,q,te;if(!_)return;if(Le.current!==pe){Le.current=pe,Ee.current=Q;return}if(Ee.current===Q)return;let p=((q=JSON.parse((w=Ee.current)!=null?w:"[]")[0])!=null?q:{}).org_id;if(Ee.current=Q,p===(A==null?void 0:A.org_id)&&h.current){P(!1),U(1500),(te=m.current)==null||te.injectJavaScript(yo(A!=null?A:{},xe));return}P(!1),B(Fe=>Fe+1)},[Q,_,pe]),ie(()=>(t||(be(e),Pe(e),Ue(e)),()=>{be(e),Pe(e),Ue(e)}),[t,e,pe,r]),ie(()=>{let p=Jo.addEventListener("change",w=>{w==="background"&&!Hn()&&be(e),w==="background"&&!Qn()&&Pe(e)});return()=>p.remove()},[e]);let kt=dn(async p=>{var q,te,Fe,ue,It;let w=co(p.nativeEvent.data);if(!w){if(y&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(p.nativeEvent.data,{app_id:y,instance_id:e})).catch(N=>{console.warn("[miniapp] onWebEvent l\u1ED7i",y,N)})}catch(N){console.warn("[miniapp] onWebEvent l\u1ED7i",y,N)}return}if(w.method==="log"){let{level:N,text:$}=w;ae(`web:${e}`,N!=null?N:"log",$!=null?$:"");return}if(w.method==="pong"){I.current||P(!0);return}if(w.method==="touchAtTop"){i.emit(!!w.at_top);return}if(w.method==="contextApplied"){I.current&&clearTimeout(I.current),I.current=null,P(!0);return}if(w.method==="ready"){h.current=!0,P(!0);let N=(q=oe.getState().instances[e])==null?void 0:q.context;N&&((te=m.current)==null||te.injectJavaScript(Jt(N)));return}try{let N=await vo(w,{getHostData:()=>{var $,se;return(se=($=oe.getState().instances[e])==null?void 0:$.host_data)!=null?se:{}},getPermissions:()=>{var $,se;return y?(se=($=L(y))==null?void 0:$.permissions)!=null?se:[]:[]},getContext:()=>{var $,se;return(se=($=oe.getState().instances[e])==null?void 0:$.context)!=null?se:{}},is_dark:o,close:lt,app_id:y!=null?y:"",instance_id:e,options:l,emit:($,se)=>{var yn;(yn=m.current)==null||yn.injectJavaScript(uo($,se))},playBeep:()=>{var $;($=m.current)==null||$.injectJavaScript(So())},isActive:()=>oe.getState().active_key===e&&Jo.currentState!=="background"});w.id&&((Fe=m.current)==null||Fe.injectJavaScript(lo(w.id,N)))}catch(N){if(!w.id)return;let $=N==null?void 0:N.code,se=N instanceof g?N:new g(typeof $=="string"?$:"HOST_ERROR",String((ue=N==null?void 0:N.message)!=null?ue:N));(It=m.current)==null||It.injectJavaScript(po(w.id,se))}},[e,o,y,i,l]),gt=dn(()=>{ee(!1),B(p=>p+1),f(p=>p+1)},[]);return He(gn,{style:[hn.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&le.behind],pointerEvents:t?"auto":"none",children:[(S==null?void 0:S.layout)===Ae.top&&G(rn,{scanner:S}),_?G(Ei,{ref:m,source:{uri:_.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?Yt():_.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:ye,onMessage:kt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{be(e),Pe(e),Ue(e),ae(`webview:${e}`,"load start",un(p.nativeEvent.url)),h.current=!1,P(!1)},onError:p=>{be(e),Pe(e),Ue(e),ae(`webview:${e}`,"load error",un(p.nativeEvent.url),p.nativeEvent.description),ee(!0),P(!1)},onLoadEnd:p=>{let w=p.nativeEvent.url;ae(`webview:${e}`,"load end",un(w)),y&&(d==null||d({app_id:y,instance_id:e,url:w})),U(1500)},onContentProcessDidTerminate:()=>{be(e),Pe(e),Ue(e),h.current=!1,P(!1),B(p=>p+1)},onRenderProcessGone:()=>(be(e),Pe(e),Ue(e),h.current=!1,P(!1),B(p=>p+1),!0),style:le.webview},pe):null,(S==null?void 0:S.layout)===Ae.full&&G(rn,{scanner:S}),u&&G(Ci,{visible:!_||!x,interactive:Y,children:G(Pi,{splash:a,app:u.app,is_dark:o,error:Y,has_bundle:!!_,retry:gt})})]})}),Pi=fn.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,l=cn(t.app_id),c=o?"error":!r&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return G(a,{app:t,is_dark:n,status:c,progress:c==="downloading"?l==null?void 0:l.progress:void 0,retry:i})}),Ci=({visible:e,interactive:t,children:n})=>{let o=fe(new pn.Value(e?1:0)).current,[r,i]=qe(e);return ie(()=>{if(e){i(!0),o.setValue(1);return}let a=pn.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:l})=>{l&&i(!1)}),()=>a.stop()},[e,o]),r?G(pn.View,{style:[hn.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},Yo=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return He(gn,{style:[le.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[G(gn,{style:[le.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?G(vi,{source:{uri:e.icon},style:le.splash_icon_image}):G(dt,{style:le.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),G(dt,{style:[le.splash_name,{color:i}],children:e.name}),n==="error"?He(mn,{children:[G(dt,{style:le.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),G(xi,{activeOpacity:.7,style:[le.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:G(dt,{style:[le.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):He(mn,{children:[G(Ai,{style:le.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&He(dt,{style:le.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},Ko=(e,t)=>{let n=fe(t),o=fe(!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.`))},Oi=({container:e,splash:t=Yo,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:l})=>{Ko("container",e),Ko("splash",t);let c=e,s=V(oe,S=>S.active_key),d=fe(s);s&&(d.current=s);let m=V(oe,S=>Object.keys(S.instances).join("|")),h=V(oe,S=>{var _;return S.active_key?(_=S.instances[S.active_key])==null?void 0:_.app.name:void 0}),u=Ot(()=>m?m.split("|"):[],[m]),[y,E]=qe({}),A=fe(Ri()).current;ie(()=>{if(!s||!r)return;let S=Si.addEventListener("hardwareBackPress",()=>(lt(),!0));return()=>S.remove()},[s,r]);let M=dn(()=>{let S=oe.getState().active_key;S&&E(_=>({..._,[S]:(_[S]||0)+1}))},[]);return u.length?He(mn,{children:[G(c,{visible:!!s,title:h!=null?h:"",is_dark:n,close:lt,reload:M,subscribeWebAtTop:A.subscribe,children:u.map(S=>G(Ti,{instance_key:S,is_active:s===S,is_front:(s!=null?s:d.current)===S,is_dark:n,reload_tick:y[S]||0,web_at_top:A,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:l},S))}),G(Bo,{})]}):null},le=hn.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"}}),ki=fn.memo(Oi);export{X as CodeType,Yo as DefaultMiniAppSplash,Lt as MINIAPP_PLATFORM_URL,ki as MiniAppHost,g as MiniAppHostError,$e as ScannerEndReason,Bt as ScannerEvent,Ae as ScannerLayout,et as ScannerMethod,de as ToastType,lt as closeMiniApp,Xo as configureMiniApp,Qo as createMmkvStorage,bn as createReactNativeBiometrics,Zo as createRnfsFileSystem,Ct as ensureMiniApp,L as getLocalMiniApp,bi as getMiniAppCatalog,ut as getMiniAppCatalogEntry,pi as getMiniAppStatuses,Ho as getMiniAppUpdate,kr as installBundledMiniApp,li as onMiniAppEvent,ei as openMiniApp,fi as pauseMiniApp,yi as pauseMiniAppDownloads,ti as preloadMiniApp,be as releaseSpeechFor,mi as restoreMiniApp,hi as resumeMiniApp,wi as resumeMiniAppDownloads,Lr as sendEventToWeb,ln as syncMiniAppCatalog,gi as uninstallMiniApp,_i as updateMiniApp,Dn as uploadToUrl,cn as useMiniAppDownload,ci as useMiniAppDownloadsPaused};
82
+ })(); true;`,kr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),_t=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},vo=async({method:e,params:t},{getHostData:n,getPermissions:o,getContext:r,is_dark:i,close:a,app_id:l,instance_id:c,options:s,emit:d,isActive:m,playBeep:h})=>{var M,S,_,K,Y,ee,he;let u=s==null?void 0:s.handlers,y={app_id:l,instance_id:c,close:a},E=()=>{var f;(f=s==null?void 0:s.haptic)==null||f.call(s,"impactLight"),h==null||h()},A=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let f=Sn(t);return tt(e,()=>vn(f,m))}case"speech.start":{if(!d)throw A();let f={};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 g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");f.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new g("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);f[v]=t[v]}return Gn(c,f,d,m)}case"speech.stop":return Kn(c);case et.scan:return no(c,$t(t),m,E);case et.start:{if(!d)throw A();return oo(c,$t(t),d,m,E)}case et.stop:return ro(c);case"uploadFiles":{let{task_id:f,...v}=t!=null?t:{};if(f!==void 0&&(typeof f!="string"||!f))throw new g("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return $n(kn(v),{instance_id:c,app_id:l,getContext:r,task_id:f,config:s==null?void 0:s.upload,emit:d,exclusivePick:B=>tt("uploadFiles.pick",B)})}case"uploadFiles.cancel":qn(c,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Vn(s==null?void 0:s.upload);case"getBiometricAvailability":return((M=s==null?void 0:s.biometrics)!=null?M:await Ft()).getAvailability();case"authenticateBiometric":{let f=_t(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return tt(e,async()=>{var x;return((x=s==null?void 0:s.biometrics)!=null?x:await Ft()).authenticate({reason:f,cancelButtonText:v})})}case"requestPayment":{let f=u==null?void 0:u.requestPayment;if(!f)throw A();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let B={...t,amount:v,currency:_t(t==null?void 0:t.currency,"currency")};return tt(e,()=>f(B,y))}case"printImage":{let f=u==null?void 0:u.printImage;if(!f)throw A();let v=_t(t==null?void 0:t.image,"image");await tt(e,()=>f({image:v},y));return}case"openScreen":if(!(u!=null&&u.openScreen))throw A();await u.openScreen({screen:_t(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},y);return;case"closeApp":a();return;case"openWebview":{let f=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(f))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(f):ao.openURL(f));return}case"openLink":{let f=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(f):ao.openURL(f))}catch(v){throw new g("NOT_SUPPORTED",String((Y=(K=v==null?void 0:v.message)!=null?K:v)!=null?Y:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":{let f=Wn(t);if(!f||(m==null?void 0:m())===!1)return;s!=null&&s.showToast?s.showToast(f.message,{type:f.type}):jn(f.message,f.type);return}case"haptic":{let f=kr.has(t==null?void 0:t.type)?t.type:"selection";(ee=s==null?void 0:s.haptic)==null||ee.call(s,f);return}case"getSystemInfo":return{platform:Or.OS==="ios"?"ios":"android",appVersion:(he=s==null?void 0:s.app_version)!=null?he:"",theme:i?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return f}case"getToken":{let f=t==null?void 0:t.type;if(f==="access"){let x=n().access_token;if(!x)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return x}if(f!=="partner"&&f!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let v=bo[f];if(!o().includes(v))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let B=f==="partner"?n().partner_token:n().chatbox_token;if(!B)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return B}case"getUserInfo":{let f=n().user;if(!f)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return f}case"getPageInfo":{let f=n().page;if(!f)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var Yt=e=>`bundle:${e}`,Xt=()=>`${F().file_system.document_dir}/miniapps`,Zt=Xt,Qt=(e,t,n="index.html",o=!1,r=[])=>{let i=`${Zt()}/${e}/${t}`;return{app_id:e,version:t,dir:i,entry_uri:`file://${i}/${n}`,context_update:o,permissions:r}},Kt=e=>{var t;F().storage.setString(Yt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Ir=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,L=e=>{let t=F().storage.getString(Yt(e));if(!t)return null;try{let{version:n,entry:o,context_update:r,permissions:i}=JSON.parse(t);return Qt(e,n,o,!!r,Array.isArray(i)?i:[])}catch{return null}},Se=e=>F().file_system.exists(e.entry_uri.replace("file://","")),en=async e=>{let t=L(e.app_id);return(t==null?void 0:t.version)===e.version&&await Se(t)},xo=async(e,t)=>{let n=F().file_system,o=`${Zt()}/${e}`,r=await n.listDir(o).catch(()=>[]);await Promise.all(r.filter(i=>!t.includes(i)).map(i=>n.remove(`${o}/${i}`).catch(()=>{})))},Eo=async e=>{var t;await((t=rt[e])==null?void 0:t.catch(()=>{})),F().storage.setString(Yt(e),""),await F().file_system.remove(`${Zt()}/${e}`).catch(()=>{})},ze=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},rt={},Ro=(e,t)=>{var i;let o=((i=rt[e])!=null?i:Promise.resolve()).catch(()=>{}).then(t),r=o.catch(()=>{});return rt[e]=r,r.then(()=>{rt[e]===r&&delete rt[e]}),o},Lr=(e,t)=>{var r,i;let n=e.split(".").map(a=>parseInt(a,10)||0),o=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,o.length);a++){let l=((r=n[a])!=null?r:0)-((i=o[a])!=null?i:0);if(l)return l}return 0},Fr=({manifest:e,zip_path:t})=>Ro(e.app_id,async()=>{var i;let n=F().file_system,o=L(e.app_id);if(o&&Lr(o.version,e.version)>=0&&await Se(o))return o;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let r=Qt(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),Kt(e),ae("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),xo(e.app_id,[e.version,o==null?void 0:o.version].filter(Boolean)),r}),tn=(e,{base_url:t,onProgress:n}={})=>{let o=F().file_system,r=null,i=!1,a=`${o.cache_dir}/${e.app_id}-${e.version}.zip`,l=()=>{if(i)throw new ze},c=async()=>{var m;l();let s=L(e.app_id);if((s==null?void 0:s.version)===e.version&&await o.exists(s.dir))return Kt(e),L(e.app_id);l();let d=o.download({url:t?Ir(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(h,u)=>{var E;let y=u>0?u:(E=e.size)!=null?E:0;y>0&&(n==null||n(Math.min(1,h/y)))}});r=d;try{let{status:h}=await d.promise;if(l(),h!==200)throw new Error(`bundle ${h}`);if(e.sha256)if(o.sha256){if(await o.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else ae("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);l();let u=Qt(e.app_id,e.version,e.entry,!!e.context_update,(m=e.permissions)!=null?m:[]);return await o.remove(u.dir).catch(()=>{}),await o.mkdir(u.dir),await o.unzip(a,u.dir),Kt(e),xo(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),u}catch(h){throw i?new ze:h}finally{r=null,o.remove(a).catch(()=>{})}};return{promise:Ro(e.app_id,c),cancel:()=>{i=!0,r==null||r.cancel()}}},ot={},Dr=__DEV__?0:60*1e3,Mo={},Po=(e,t)=>{var o,r;let n=L(e);return n&&Date.now()-((o=Mo[t])!=null?o:0)<Dr?Promise.resolve(n):((r=ot[e])!=null||(ot[e]=(async()=>{let i=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!i.ok)throw new Error(`manifest ${i.status}`);let a=await i.json(),l=await tn(a,{base_url:t}).promise;return Mo[t]=Date.now(),l})().catch(i=>(console.warn("[miniapp] sync failed",e,i==null?void 0:i.message),L(e))).finally(()=>{ot[e]=void 0})),ot[e])};var At=new Map,To=(e,t)=>(At.set(e,t),()=>{At.get(e)===t&&At.delete(e)}),Nr=(e,t)=>{let n=At.get(e);return n?n(t):!1};import{useCallback as Co,useEffect as St,useRef as ve,useState as nn}from"react";import{Animated as D,BackHandler as Ur,Easing as Oo,Platform as Lo,Pressable as Vr,StatusBar as Br,StyleSheet as rn,Text as it,View as z}from"react-native";import{Fragment as Kr,jsx as R,jsxs as we}from"react/jsx-runtime";var st="#22C55E",qr="\u0110\u01B0a m\xE3 v\xE0o khung \u0111\u1EC3 qu\xE9t",$r=2,Mt=18,zr=1600,at=14,Wr=2e3,ko=2,jr=8,Hr=2e3,We=2e3,Jr=[{top:0,left:0,borderTopWidth:4,borderLeftWidth:4,borderTopLeftRadius:at},{top:0,right:0,borderTopWidth:4,borderRightWidth:4,borderTopRightRadius:at},{bottom:0,left:0,borderBottomWidth:4,borderLeftWidth:4,borderBottomLeftRadius:at},{bottom:0,right:0,borderBottomWidth:4,borderRightWidth:4,borderBottomRightRadius:at}],Io=({color:e})=>R(Kr,{children:Jr.map((t,n)=>R(z,{style:[b.corner,t,{borderColor:e}]},n))}),vt=({style:e,children:t,...n})=>{let o=ve(new D.Value(1)).current,r=i=>D.spring(o,{toValue:i,speed:40,bounciness:8,useNativeDriver:!0}).start();return R(Vr,{...n,onPressIn:()=>r(.88),onPressOut:()=>r(1),children:R(D.View,{style:[e,{transform:[{scale:o}]}],children:t})})},sn=({scanner:e})=>{var gt,Je,Ge;let{vision:t,types:n,mode:o,layout:r,hint:i,glass_view:a}=e,l=r===Ae.top,c=t.useCameraDevice("back"),s=ve(new D.Value(1)).current,d=ve(new D.Value(0)).current,[m,h]=nn(!1),[u,y]=nn(1),E=ve(null),[A,M]=nn({width:0,height:0,window_y:0}),S=V(j,p=>p.last_value),_=V(j,p=>p.hit_tick),K=V(j,p=>p.scan_count),Y=V(j,p=>p.notice),ee=V(j,p=>p.is_picking),he=ve(null),f=Lo.OS==="ios"?54:(gt=Br.currentHeight)!=null?gt:0,v=ve(new D.Value(0)).current,B=ve(new D.Value(0)).current,x=ve(new D.Value(0)).current,T=Math.round(A.width*(l?.8:.78)),I=Math.round(l?A.height*.46:T*.78),U=Math.round((A.height-I)/2),O=Math.round((A.width-T)/2),Z=t.useCodeScanner({codeTypes:n,onCodeScanned:Co(p=>Ht(p),[])});St(()=>{let p=Ur.addEventListener("hardwareBackPress",()=>(jt(),!0));return()=>p.remove()},[]);let Ie=ve(_);St(()=>{if(_===Ie.current)return;v.setValue(1),x.setValue(1);let p=D.parallel([D.timing(v,{toValue:0,duration:450,useNativeDriver:!0}),D.sequence([D.delay(Wr),D.timing(x,{toValue:0,duration:250,useNativeDriver:!0})])]);return p.start(),()=>p.stop()},[_,v,x]),St(()=>{let p=q=>D.timing(B,{toValue:q,duration:zr,easing:Oo.inOut(Oo.quad),useNativeDriver:!0}),w=D.loop(D.sequence([p(1),p(0)]));return w.start(),()=>w.stop()},[B]);let pe=Co(()=>{D.timing(s,{toValue:0,duration:220,useNativeDriver:!0}).start()},[s]);St(()=>{let p=setTimeout(pe,Hr);return()=>clearTimeout(p)},[pe]);let Q=!!(c!=null&&c.hasTorch),xe=(Je=c==null?void 0:c.neutralZoom)!=null?Je:1,ye=c?Math.min(c.maxZoom/xe,jr):1,Ee=xe*Math.min(u,ye),Le=p=>{var te;let{touches:w}=p.nativeEvent;if(w.length!==2){E.current=null;return}let q=Math.hypot(w[0].pageX-w[1].pageX,w[0].pageY-w[1].pageY);(te=E.current)!=null||(E.current={distance:q,level:u}),y(Math.max(1,Math.min(ye,E.current.level*(q/E.current.distance))))},kt=R(it,{style:[b.hint,!!Y&&b.hint_notice],numberOfLines:1,children:(Ge=Y!=null?Y:i)!=null?Ge:qr});return R(z,{ref:he,onTouchMove:Le,onTouchEnd:()=>{E.current=null},style:l?b.top:b.full,onLayout:({nativeEvent:{layout:p}})=>{var w;(w=he.current)==null||w.measureInWindow((q,te)=>{M({width:p.width,height:p.height,window_y:te||0}),D.timing(d,{toValue:1,duration:180,useNativeDriver:!0}).start()})},children:we(D.View,{style:[b.content,{opacity:d}],children:[c&&R(t.Camera,{style:rn.absoluteFill,device:c,isActive:!ee,codeScanner:Z,torch:m&&Q?"on":"off",zoom:Ee,onPreviewStarted:pe,onError:p=>io(p.message)}),R(D.View,{style:[b.preview_cover,{opacity:s}],pointerEvents:"none"}),A.height>0&&we(z,{style:b.overlay,pointerEvents:"none",children:[R(z,{style:[b.dim_ring,{top:U-We,left:O-We,width:T+We*2,height:I+We*2}]}),we(z,{style:{position:"absolute",top:U,left:O,width:T,height:I},children:[R(Io,{color:"#FFFFFF"}),R(D.View,{style:[rn.absoluteFill,{opacity:v}],children:R(Io,{color:st})}),we(D.View,{style:[b.scan_line_wrap,{transform:[{translateY:B.interpolate({inputRange:[0,1],outputRange:[0,Math.max(0,I-Mt)]})}]}],children:[R(z,{style:b.scan_glow_outer}),R(z,{style:b.scan_glow_inner}),R(z,{style:b.scan_line})]})]}),R(z,{style:[b.hint_slot,l?{top:0,height:U-6,justifyContent:"flex-end"}:{top:U+I+20}],children:kt}),o===Ve.continuous&&!!S&&R(D.View,{style:[b.result_slot,l?b.result_slot_top:{top:U+I+52},{opacity:x}],children:we(z,{style:b.result,children:[R(z,{style:b.check_badge,children:R(z,{style:b.check_mark})}),R(it,{style:b.result_text,numberOfLines:1,children:S}),we(it,{style:b.result_count,children:["\xB7 ",K," m\xE3"]})]})})]}),A.height>0&&R(z,{style:[b.close_slot,{top:Math.max(12,f-A.window_y+12)}],children:we(vt,{style:[b.close_button,!!a&&b.glass_surface],onPress:jt,hitSlop:8,accessibilityRole:"button",accessibilityLabel:"\u0110\xF3ng",children:[a&&R(a,{style:b.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),R(z,{style:[b.close_bar,b.close_bar_a]}),R(z,{style:[b.close_bar,b.close_bar_b]})]})}),R(z,{style:[b.toolbar_wrap,!l&&b.toolbar_wrap_full],pointerEvents:"box-none",children:we(z,{style:[b.toolbar,!!a&&b.glass_surface],children:[a&&R(a,{style:b.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.35)",isInteractive:!0}),R(vt,{style:b.tool,onPress:so,disabled:ee,accessibilityRole:"button",accessibilityLabel:"Qu\xE9t t\u1EEB \u1EA3nh",children:we(z,{style:b.image_icon,children:[R(z,{style:b.image_icon_dot}),R(z,{style:b.image_icon_hill})]})}),!!c&&ye>=ko&&R(vt,{style:[b.tool,u>1&&b.tool_on],onPress:()=>y(p=>p>1?1:ko),accessibilityRole:"button",accessibilityLabel:"Ph\xF3ng to",children:we(it,{style:[b.zoom_text,u>1&&b.zoom_text_on],children:[Math.round(u*10)/10,"x"]})}),Q&&R(vt,{style:[b.tool,m&&b.tool_on],onPress:()=>h(p=>!p),accessibilityRole:"button",accessibilityLabel:"\u0110\xE8n pin",accessibilityState:{selected:m},children:R(it,{style:[b.torch_icon,m&&b.zoom_text_on],children:"\u26A1\uFE0E"})})]})})]})})},Gr="rgba(0,0,0,0.5)",on=50,b=rn.create({top:{height:"38%",overflow:"hidden"},full:{position:"absolute",top:0,left:0,right:0,bottom:0},content:{flex:1,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:We,borderColor:Gr,borderRadius:We+at},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:Mt,alignItems:"stretch",justifyContent:"center"},scan_glow_outer:{position:"absolute",left:0,right:0,height:Mt,borderRadius:Mt/2,backgroundColor:st,opacity:.1},scan_glow_inner:{position:"absolute",left:4,right:4,height:8,borderRadius:4,backgroundColor:st,opacity:.2},scan_line:{height:$r,borderRadius:1,backgroundColor:st},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_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_wrap_full:{bottom:Lo.OS==="ios"?34:20},toolbar:{flexDirection:"row",alignItems:"center",gap:4,padding:4,borderRadius:999,backgroundColor:"rgba(24,24,27,0.72)"},tool:{width:on,height:on,borderRadius:on/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_slot_top:{top:8},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:st},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 Fo,useRef as ct,useState as Do}from"react";import{AccessibilityInfo as Yr,Animated as H,Platform as Xr,StatusBar as Zr,StyleSheet as Qr,Text as ei,View as je}from"react-native";import{Fragment as Uo,jsx as _e,jsxs as an}from"react/jsx-runtime";var ti={[de.info]:"#3B82F6",[de.success]:"#22C55E",[de.error]:"#EF4444"},No=-120,ni=({type:e})=>e===de.success?_e(je,{style:ne.check_mark}):e===de.error?an(Uo,{children:[_e(je,{style:[ne.cross_bar,ne.cross_a]}),_e(je,{style:[ne.cross_bar,ne.cross_b]})]}):an(Uo,{children:[_e(je,{style:ne.info_dot}),_e(je,{style:ne.info_bar})]}),Bo=()=>{let e=V(Qe,h=>h.message),t=V(Qe,h=>h.type),n=V(Qe,h=>h.tick),o=ct(new H.Value(No)).current,r=ct(new H.Value(0)).current,i=ct(new H.Value(.92)).current,a=ct(new H.Value(0)).current,[l,c]=Do(),[s,d]=Do(!1);Fo(()=>{let h=!0;return Wt().then(u=>{h&&u&&c(()=>u)}),()=>{h=!1}},[]);let m=ct(n);return Fo(()=>{if(n===m.current)return;Yr.announceForAccessibility(e),d(!0),a.setValue(0),i.setValue(.92);let h=H.sequence([H.parallel([H.spring(o,{toValue:0,speed:16,bounciness:7,useNativeDriver:!0}),H.spring(i,{toValue:1,speed:16,bounciness:9,useNativeDriver:!0}),H.timing(r,{toValue:1,duration:140,useNativeDriver:!0}),H.sequence([H.delay(90),H.spring(a,{toValue:1,speed:18,bounciness:14,useNativeDriver:!0})])]),H.delay(zn[t]),H.parallel([H.timing(o,{toValue:No,duration:240,useNativeDriver:!0}),H.timing(r,{toValue:0,duration:200,useNativeDriver:!0})])]);return h.start(({finished:u})=>{u&&d(!1)}),()=>h.stop()},[n]),s?_e(je,{style:ne.layer,pointerEvents:"none",children:an(H.View,{style:[ne.toast,!!l&&ne.toast_glass,{opacity:l?1:r,transform:[{translateY:o},{scale:i}]}],accessibilityLiveRegion:"polite",children:[l&&_e(l,{style:ne.glass_fill,glassEffectStyle:"regular",colorScheme:"dark",tintColor:"rgba(24,24,27,0.55)"}),_e(H.View,{style:[ne.badge,{backgroundColor:ti[t],transform:[{scale:a}]}],children:_e(ni,{type:t})}),_e(ei,{style:ne.message,numberOfLines:2,children:e})]})}):null},Vo,ne=Qr.create({layer:{position:"absolute",top:(Xr.OS==="ios"?54:(Vo=Zr.currentHeight)!=null?Vo:0)+8,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_glass:{backgroundColor:"transparent"},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"},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 oe=Pe({active_key:null,instances:{}}),qo=({app:e,instance_id:t,context:n={},url_params:o={},host_data:r={}},i)=>{var l;let a=(l=F().keep_alive)==null?void 0:l.max_webviews;oe.setState(c=>{let s=t!=null?t:e.app_id,d={...c.instances,[s]:{key:s,app:e,context:n,url_params:o,host_data:r,last_used_at:Date.now()}},m=Object.keys(d);return a&&a>0&&m.length>a&&m.filter(h=>h!==s).sort((h,u)=>d[h].last_used_at-d[u].last_used_at).slice(0,m.length-a).forEach(h=>{delete d[h]}),i?{active_key:s,instances:d}:{instances:d}})},oi=e=>qo(e,!0),ri=e=>qo(e,!1),lt=()=>oe.setState({active_key:null}),xt=e=>{oe.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var $o="catalog",ii="paused_apps",si="removed_apps",ai=10*1e3,ci=2,li=3e3,pi=()=>{var e;try{return JSON.parse((e=F().storage.getString($o))!=null?e:"{}")}catch{return{}}},C=Pe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),zo=e=>{var t;return!!((t=F().manual_update)!=null&&t.includes(e))},Pt=new Set,Wo=e=>{let t=new Set,n=()=>F().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=F().storage.getString(e))!=null?o:"[]");Array.isArray(r)&&r.forEach(i=>{typeof i=="string"&&t.add(i)})}catch{}}}},me=Wo(ii),ke=Wo(si);bn(()=>{me.load(),ke.load();let e=pi(),t={};Object.keys(e).filter(n=>!ke.has(n)).forEach(n=>{let o=L(n);o?t[n]={status:"installed",progress:1,version:o.version,has_local:!0}:me.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),C.setState({catalog:e,downloads:t})});var ln=e=>V(C,t=>e?t.downloads[e]:void 0),ui=()=>V(C,e=>e.pause_reasons.length>0),ge=(...e)=>ae("queue",...e),J=[],Me={},P=null,Et=new Set,Be={},cn=new Set,Ce=e=>{cn.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},di=e=>(cn.add(e),()=>{cn.delete(e)}),gi=()=>C.getState().downloads,re=(e,t)=>{let n=!!L(e),o=C.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};C.setState(a=>({downloads:{...a.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?Ce({type:"status_change",app_id:e,state:i}):o.progress!==i.progress&&Ce({type:"progress",app_id:e,progress:i.progress,version:i.version})},Rt=(e,t)=>{var n;(n=Be[e])==null||n.forEach(o=>o(t)),delete Be[e]},mi=()=>C.getState().pause_reasons.length>0,Oe=e=>{var l;if(P)return;let t=e?J.indexOf(e):mi()?-1:J.findIndex(c=>!me.has(c));if(t<0||t>=J.length)return;let[n]=J.splice(t,1),o=C.getState().catalog[n];if(!o){Rt(n,L(n)),Oe();return}let r=Date.now();Me[n]=((l=Me[n])!=null?l:0)+1,re(n,{status:"downloading",progress:0,version:o.version,error:void 0});let i=0,a=tn(o,{onProgress:c=>{let s=Math.floor(c*100);s!==i&&(i=s,re(n,{progress:s/100,version:o.version}))}});P={app_id:n,handle:a,forced:!!e},ge("start",n,o.version,e?"(forced)":""),a.promise.then(c=>{ge("installed",n,o.version,`${Date.now()-r}ms`),re(n,{status:"installed",progress:1,version:o.version}),Rt(n,c)}).catch(c=>{var d;if(c instanceof ze){if(Et.has(n))return;ge("paused",n),Me[n]-=1,J.unshift(n),re(n,{status:me.has(n)?"paused":"queued",progress:0,version:o.version});return}let s=String((d=c==null?void 0:c.message)!=null?d:c);if(console.warn("[miniapp-queue] failed",n,s),Me[n]<ci){re(n,{status:"queued",progress:0,version:o.version,error:s}),setTimeout(()=>{var m;J.includes(n)||(P==null?void 0:P.app_id)===n||(J.push(n),Oe((m=Be[n])!=null&&m.length?n:void 0))},li);return}re(n,{status:"failed",progress:0,version:o.version,error:s}),Rt(n,L(n))}).finally(()=>{P=null;let c=J.find(s=>{var d;return(d=Be[s])==null?void 0:d.length});Oe(c)})},Tt=(e,{front:t=!1}={})=>{if((P==null?void 0:P.app_id)===e)return;let n=J.indexOf(e);if(n>=0){if(!t)return;J.splice(n,1)}t?J.unshift(e):J.push(e)},fi=async e=>{let{host_id:t,client_token:n}=F(),o=new AbortController,r=setTimeout(()=>o.abort(),ai);try{let i=`${Lt}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(i,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:o.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(c=>({...c,channel:e}))}finally{clearTimeout(r)}},pt=null,pn=()=>(pt!=null||(pt=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(F().channels.map(fi)),o={};[...n].reverse().flat().forEach(c=>{o[c.app_id]=c});let r=Object.keys(C.getState().catalog).filter(c=>!o[c]);F().storage.setString($o,JSON.stringify(o)),C.setState({catalog:o}),await Promise.all(r.map(c=>jo(c,{by_user:!1}))),r.forEach(c=>ke.delete(c));let i=Object.keys(o).filter(c=>!ke.has(c)),a=[],l={};for(let c of i.map(s=>o[s])){if(await en(c)){re(c.app_id,{status:"installed",progress:1,version:c.version});continue}let s=L(c.app_id);if(zo(c.app_id)&&!Pt.has(c.app_id)&&s&&await Se(s)){re(c.app_id,{status:"installed",progress:1,version:s.version}),l[c.app_id]={app_id:c.app_id,current_version:s.version,next_version:c.version};continue}a.push(c)}return C.setState({updates:l}),a.forEach(c=>{Me[c.app_id]=0,re(c.app_id,{status:me.has(c.app_id)?"paused":"queued",progress:0,version:c.version,error:void 0}),Tt(c.app_id)}),ge("catalog",i.length,"apps, outdated",a.map(c=>c.app_id),"removed",r,`${Date.now()-e}ms`),Ce({type:"sync_complete",app_ids:i,removed:r}),Object.values(l).forEach(c=>Ce({type:"update_available",...c})),Oe(),{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),Ce({type:"sync_failed",error:o}),{ok:!1,error:o}}finally{pt=null}})()),pt),jo=async(e,{by_user:t})=>{var r,i,a,l;if(t&&ke.add(e),Et.has(e))return;Et.add(e),me.delete(e);let n=J.indexOf(e);n>=0&&J.splice(n,1),(P==null?void 0:P.app_id)===e&&P.handle.cancel();let o=(l=(a=(r=C.getState().downloads[e])==null?void 0:r.version)!=null?a:(i=L(e))==null?void 0:i.version)!=null?l:"";re(e,{status:"uninstalling",progress:0,version:o}),await Eo(e),xt(e),C.setState(c=>{let s={...c.downloads};return delete s[e],{downloads:s}}),delete Me[e],Et.delete(e),Rt(e,null),ge("uninstalled",e,t?"(user)":"(not in list)"),Ce({type:"uninstalled",app_id:e})},hi=e=>jo(e,{by_user:!0}),yi=e=>{let t=ut(e);return t?(ke.delete(e),(P==null?void 0:P.app_id)===e||J.includes(e)||(Me[e]=0,re(e,{status:me.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Tt(e),Oe(),ge("restore",e)),!0):!1},wi=e=>{if(me.has(e))return;if(me.add(e),ge("pause app",e),(P==null?void 0:P.app_id)===e&&!P.forced){P.handle.cancel();return}let t=C.getState().downloads[e];J.includes(e)&&t&&re(e,{status:"paused",progress:0,version:t.version})},_i=e=>{if(!me.delete(e))return;ge("resume app",e);let t=C.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!J.includes(e)&&ut(e)&&(Me[e]=0,Tt(e)),J.includes(e)&&t&&re(e,{status:"queued",progress:0,version:t.version}),Oe()},bi=e=>{let{pause_reasons:t}=C.getState();t.includes(e)||(C.setState({pause_reasons:[...t,e]}),ge("pause",e),t.length===0&&Ce({type:"pause_change",paused:!0,reasons:[e]}),P&&!P.forced&&P.handle.cancel())},Ai=e=>{let{pause_reasons:t}=C.getState();if(!t.includes(e))return;let n=t.filter(o=>o!==e);C.setState({pause_reasons:n}),ge("resume",e),n.length===0&&Ce({type:"pause_change",paused:!1,reasons:n}),Oe()},Ho=e=>C.getState().updates[e],Si=async e=>{var n,o;let t=Ho(e);Pt.add(e);try{let r=await Ct(e),i=(o=t==null?void 0:t.next_version)!=null?o:(n=ut(e))==null?void 0:n.version;return!r||!i||r.version!==i?!1:(C.setState(a=>{var c;let l={...a.updates};return delete l[e],{updates:l,apply_ticks:{...a.apply_ticks,[e]:((c=a.apply_ticks[e])!=null?c:0)+1}}}),ge("updated",e,t==null?void 0:t.current_version,"\u2192",r.version),!0)}finally{Pt.delete(e)}},vi=()=>Object.values(C.getState().catalog).map(e=>({...e,installed:!!L(e.app_id),removed_by_user:ke.has(e.app_id)})),ut=e=>C.getState().catalog[e],Ct=async e=>{let t=ut(e);if(!t)return;if(me.delete(e),ke.delete(e),await en(t))return L(e);let n=L(e);if(zo(e)&&!Pt.has(e)&&n&&await Se(n))return n;let o=new Promise(r=>{var i;((i=Be[e])!=null?i:Be[e]=[]).push(r)});return(P==null?void 0:P.app_id)===e?P.forced=!0:(Me[e]=0,Tt(e,{front:!0}),P&&!P.forced?P.handle.cancel():Oe(e)),o};import{Fragment as fn,jsx as G,jsxs as He}from"react/jsx-runtime";var dn=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Go=0,Ci=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Oi=hn.memo(({instance_key:e,is_active:t,is_front:n,is_dark:o,reload_tick:r,web_at_top:i,splash:a,bridge:l,opaque_background:c,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var Je,Ge;let m=fe(null),h=fe(!1),u=V(oe,p=>p.instances[e]),y=u==null?void 0:u.app.app_id,E=u==null?void 0:u.app.manifest_url,A=u==null?void 0:u.context,M=u==null?void 0:u.url_params,S=V(j,p=>{var w;return((w=p.active)==null?void 0:w.owner)===e?p.active:null}),[_,K]=qe(()=>y?L(y):null),[Y,ee]=qe(!1),[he,f]=qe(0),[v,B]=qe(0),[x,T]=qe(!1),I=fe(null),U=p=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,T(!0)},p)};ie(()=>()=>{I.current&&clearTimeout(I.current)},[]),ie(()=>{if(!y||!t&&_)return;let p=!0;return ee(!1),(async()=>{let w=L(y),q=w?await Se(w):!1;if(!p||(K(q?ue=>!ue||ue.version!==w.version||ue.permissions.join(",")!==w.permissions.join(",")?w:ue:null),__DEV__&&Date.now()-Go>1e4&&(Go=Date.now(),await pn()),!p))return;let te=await Ct(y),Fe=te!==void 0?te:E?await Po(y,E):L(y);if(p){if(!Fe){ee(!0);return}K(ue=>ue!=null?ue:Fe)}})(),()=>{p=!1}},[t,y,E,he]),ie(()=>To(e,p=>m.current?(m.current.postMessage(p),!0):!1),[e]);let O=V(C,p=>{let w=y?p.downloads[y]:void 0;return(w==null?void 0:w.status)==="installed"?w.version:void 0});ie(()=>{if(t||!y||!_)return;let p=L(y);if(!p||p.version===_.version)return;let w=!0;return Se(p).then(q=>{!w||!q||(ae(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",_.version,"\u2192",p.version),K(p))}),()=>{w=!1}},[t,y,O,_==null?void 0:_.version]);let Z=V(C,p=>{var w;return y&&(w=p.apply_ticks[y])!=null?w:0});ie(()=>{if(!Z||!y)return;let p=L(y);if(!p||p.version===(_==null?void 0:_.version))return;let w=!0;return Se(p).then(q=>{!w||!q||(ae(`webview:${e}`,"c\u1EADp nh\u1EADt",_==null?void 0:_.version,"\u2192",p.version),T(!1),K(p))}),()=>{w=!1}},[Z]),ie(()=>{var q;let p=(q=F().keep_alive)==null?void 0:q.idle_close_ms;if(t||!p||p<=0)return;let w=setTimeout(()=>{xt(e)},p);return()=>clearTimeout(w)},[t,e]),ie(()=>{r>0&&(ee(!1),T(!1),B(p=>p+1),f(p=>p+1))},[r]);let Ie=fe(t);ie(()=>{var p;Ie.current!==t&&(Ie.current=t,h.current&&((p=m.current)==null||p.injectJavaScript(ho(t?"resumed":"paused"))))},[t]);let pe=`${(Je=_==null?void 0:_.version)!=null?Je:"none"}:${(Ge=_==null?void 0:_.permissions.join(","))!=null?Ge:""}:${v}`,Q=Ot(()=>JSON.stringify([A!=null?A:{},M!=null?M:{}]),[A,M]),xe=Ot(()=>{var p;return Ao(M!=null?M:{},(p=_==null?void 0:_.permissions)!=null?p:[])},[Q,_==null?void 0:_.permissions]),ye=Ot(()=>_o(A!=null?A:{},xe)+mo()+(Ri.OS==="android"?fo():"")+(F().debug?go():""),[xe]),Ee=fe(null),Le=fe(null);ie(()=>{var w,q,te;if(!_)return;if(Le.current!==pe){Le.current=pe,Ee.current=Q;return}if(Ee.current===Q)return;let p=((q=JSON.parse((w=Ee.current)!=null?w:"[]")[0])!=null?q:{}).org_id;if(Ee.current=Q,p===(A==null?void 0:A.org_id)&&h.current){T(!1),U(1500),(te=m.current)==null||te.injectJavaScript(yo(A!=null?A:{},xe));return}T(!1),B(Fe=>Fe+1)},[Q,_,pe]),ie(()=>(t||(be(e),Te(e),Ue(e)),()=>{be(e),Te(e),Ue(e)}),[t,e,pe,r]),ie(()=>{let p=Jo.addEventListener("change",w=>{w==="background"&&!Jn()&&be(e),w==="background"&&!Qn()&&Te(e)});return()=>p.remove()},[e]);let kt=gn(async p=>{var q,te,Fe,ue,It;let w=co(p.nativeEvent.data);if(!w){if(y&&(l!=null&&l.onWebEvent))try{Promise.resolve(l.onWebEvent(p.nativeEvent.data,{app_id:y,instance_id:e})).catch(N=>{console.warn("[miniapp] onWebEvent l\u1ED7i",y,N)})}catch(N){console.warn("[miniapp] onWebEvent l\u1ED7i",y,N)}return}if(w.method==="log"){let{level:N,text:$}=w;ae(`web:${e}`,N!=null?N:"log",$!=null?$:"");return}if(w.method==="pong"){I.current||T(!0);return}if(w.method==="touchAtTop"){i.emit(!!w.at_top);return}if(w.method==="contextApplied"){I.current&&clearTimeout(I.current),I.current=null,T(!0);return}if(w.method==="ready"){h.current=!0,T(!0);let N=(q=oe.getState().instances[e])==null?void 0:q.context;N&&((te=m.current)==null||te.injectJavaScript(Gt(N)));return}try{let N=await vo(w,{getHostData:()=>{var $,se;return(se=($=oe.getState().instances[e])==null?void 0:$.host_data)!=null?se:{}},getPermissions:()=>{var $,se;return y?(se=($=L(y))==null?void 0:$.permissions)!=null?se:[]:[]},getContext:()=>{var $,se;return(se=($=oe.getState().instances[e])==null?void 0:$.context)!=null?se:{}},is_dark:o,close:lt,app_id:y!=null?y:"",instance_id:e,options:l,emit:($,se)=>{var wn;(wn=m.current)==null||wn.injectJavaScript(uo($,se))},playBeep:()=>{var $;($=m.current)==null||$.injectJavaScript(So())},isActive:()=>oe.getState().active_key===e&&Jo.currentState!=="background"});w.id&&((Fe=m.current)==null||Fe.injectJavaScript(lo(w.id,N)))}catch(N){if(!w.id)return;let $=N==null?void 0:N.code,se=N instanceof g?N:new g(typeof $=="string"?$:"HOST_ERROR",String((ue=N==null?void 0:N.message)!=null?ue:N));(It=m.current)==null||It.injectJavaScript(po(w.id,se))}},[e,o,y,i,l]),gt=gn(()=>{ee(!1),B(p=>p+1),f(p=>p+1)},[]);return He(mn,{style:[yn.absoluteFill,c&&{backgroundColor:o?"#09090B":"#FFFFFF"},!n&&le.behind],pointerEvents:t?"auto":"none",children:[(S==null?void 0:S.layout)===Ae.top&&G(sn,{scanner:S}),_?G(Ti,{ref:m,source:{uri:_.entry_uri},originWhitelist:["*"],hideKeyboardAccessoryView:!0,mediaPlaybackRequiresUserAction:!1,allowingReadAccessToURL:`file://${s?Xt():_.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:ye,onMessage:kt,bounces:!1,overScrollMode:"never",onLoadStart:p=>{be(e),Te(e),Ue(e),ae(`webview:${e}`,"load start",dn(p.nativeEvent.url)),h.current=!1,T(!1)},onError:p=>{be(e),Te(e),Ue(e),ae(`webview:${e}`,"load error",dn(p.nativeEvent.url),p.nativeEvent.description),ee(!0),T(!1)},onLoadEnd:p=>{let w=p.nativeEvent.url;ae(`webview:${e}`,"load end",dn(w)),y&&(d==null||d({app_id:y,instance_id:e,url:w})),U(1500)},onContentProcessDidTerminate:()=>{be(e),Te(e),Ue(e),h.current=!1,T(!1),B(p=>p+1)},onRenderProcessGone:()=>(be(e),Te(e),Ue(e),h.current=!1,T(!1),B(p=>p+1),!0),style:le.webview},pe):null,(S==null?void 0:S.layout)===Ae.full&&G(sn,{scanner:S}),u&&G(Ii,{visible:!_||!x,interactive:Y,children:G(ki,{splash:a,app:u.app,is_dark:o,error:Y,has_bundle:!!_,retry:gt})})]})}),ki=hn.memo(({splash:e,app:t,is_dark:n,error:o,has_bundle:r,retry:i})=>{let a=e,l=ln(t.app_id),c=o?"error":!r&&(l==null?void 0:l.status)==="downloading"?"downloading":"loading";return G(a,{app:t,is_dark:n,status:c,progress:c==="downloading"?l==null?void 0:l.progress:void 0,retry:i})}),Ii=({visible:e,interactive:t,children:n})=>{let o=fe(new un.Value(e?1:0)).current,[r,i]=qe(e);return ie(()=>{if(e){i(!0),o.setValue(1);return}let a=un.timing(o,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:l})=>{l&&i(!1)}),()=>a.stop()},[e,o]),r?G(un.View,{style:[yn.absoluteFill,{opacity:o}],pointerEvents:t?"auto":"none",children:n}):null},Yo=({app:e,is_dark:t,status:n,progress:o,retry:r})=>{let i=t?"#FAFAFA":"#18181B";return He(mn,{style:[le.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[G(mn,{style:[le.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?G(Ei,{source:{uri:e.icon},style:le.splash_icon_image}):G(dt,{style:le.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),G(dt,{style:[le.splash_name,{color:i}],children:e.name}),n==="error"?He(fn,{children:[G(dt,{style:le.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),G(Pi,{activeOpacity:.7,style:[le.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:r,children:G(dt,{style:[le.retry_text,{color:i}],children:"Th\u1EED l\u1EA1i"})})]}):He(fn,{children:[G(Mi,{style:le.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&He(dt,{style:le.splash_hint,children:["\u0110ang t\u1EA3i mini app",o?` ${Math.round(o*100)}%`:"\u2026"]})]})]})},Ko=(e,t)=>{let n=fe(t),o=fe(!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.`))},Li=({container:e,splash:t=Yo,is_dark:n=!1,bridge:o,close_on_back:r=!0,opaque_background:i=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:l})=>{Ko("container",e),Ko("splash",t);let c=e,s=V(oe,S=>S.active_key),d=fe(s);s&&(d.current=s);let m=V(oe,S=>Object.keys(S.instances).join("|")),h=V(oe,S=>{var _;return S.active_key?(_=S.instances[S.active_key])==null?void 0:_.app.name:void 0}),u=Ot(()=>m?m.split("|"):[],[m]),[y,E]=qe({}),A=fe(Ci()).current;ie(()=>{if(!s||!r)return;let S=xi.addEventListener("hardwareBackPress",()=>(lt(),!0));return()=>S.remove()},[s,r]);let M=gn(()=>{let S=oe.getState().active_key;S&&E(_=>({..._,[S]:(_[S]||0)+1}))},[]);return u.length?He(fn,{children:[G(c,{visible:!!s,title:h!=null?h:"",is_dark:n,close:lt,reload:M,subscribeWebAtTop:A.subscribe,children:u.map(S=>G(Oi,{instance_key:S,is_active:s===S,is_front:(s!=null?s:d.current)===S,is_dark:n,reload_tick:y[S]||0,web_at_top:A,splash:t,bridge:o,opaque_background:i,allow_embedded_miniapps:a,onWebLoadEnd:l},S))}),G(Bo,{})]}):null},le=yn.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"}}),Fi=hn.memo(Li);export{X as CodeType,Yo as DefaultMiniAppSplash,Lt as MINIAPP_PLATFORM_URL,Fi as MiniAppHost,g as MiniAppHostError,$e as ScannerEndReason,qt as ScannerEvent,Ae as ScannerLayout,et as ScannerMethod,de as ToastType,lt as closeMiniApp,Xo as configureMiniApp,Qo as createMmkvStorage,An as createReactNativeBiometrics,Zo as createRnfsFileSystem,Ct as ensureMiniApp,L as getLocalMiniApp,vi as getMiniAppCatalog,ut as getMiniAppCatalogEntry,gi as getMiniAppStatuses,Ho as getMiniAppUpdate,Fr as installBundledMiniApp,di as onMiniAppEvent,oi as openMiniApp,wi as pauseMiniApp,bi as pauseMiniAppDownloads,ri as preloadMiniApp,be as releaseSpeechFor,yi as restoreMiniApp,_i as resumeMiniApp,Ai as resumeMiniAppDownloads,Nr as sendEventToWeb,pn as syncMiniAppCatalog,hi as uninstallMiniApp,Si as updateMiniApp,Nn as uploadToUrl,ln as useMiniAppDownload,ui as useMiniAppDownloadsPaused};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retion-miniapp/react-native",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "React Native host for Retion Mini Apps with built-in biometric authentication",
5
5
  "license": "MIT",
6
6
  "repository": {