@retion-miniapp/react-native 0.10.0 → 0.10.1
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/README.md +2 -2
- package/dist/index.d.mts +14 -31
- package/dist/index.d.ts +14 -31
- package/dist/index.js +28 -7
- package/dist/index.mjs +28 -7
- package/docs/MINIAPP_README.md +30 -50
- package/docs/NATIVE_APIS.md +29 -49
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -22,8 +22,8 @@ Cài package không sửa được binary đã cài trên thiết bị. Nếu bi
|
|
|
22
22
|
|
|
23
23
|
## Phiên bản và điều kiện tích hợp
|
|
24
24
|
|
|
25
|
-
Tài liệu hiện tại mô tả **Mini App React Native 0.10.
|
|
25
|
+
Tài liệu hiện tại mô tả **Mini App React Native 0.10.1 + Web SDK 0.10.0**. Package khai báo React ≥18, React Native ≥0.72, Expo ≥52 và WebView ≥13; đây là giới hạn khai báo, không phải cam kết mọi tổ hợp phiên bản native đã được kiểm tra. App React Native thuần cần tích hợp Expo Modules để dùng thư viện speech.
|
|
26
26
|
|
|
27
|
-
Package tự cài `react-native-biometrics@3.0.1`, `expo-speech-recognition@1.1.1`, `@react-native-community/geolocation@3.4.0
|
|
27
|
+
Package tự cài `react-native-biometrics@3.0.1`, `expo-speech-recognition@1.1.1`, `@react-native-community/geolocation@3.4.0`, `react-native-image-picker@8.2.1`, `@react-native-documents/picker@12.0.2` và `react-native-compressor@1.13.0`. Nếu app cũng dùng các thư viện này cho chức năng khác, đồng bộ phiên bản để tránh trùng module native. Với Expo 57, xem lưu ý bản vá của thư viện speech trong [hướng dẫn speech](docs/SPEECH.md).
|
|
28
28
|
|
|
29
29
|
Trong lúc bản mới chưa phát hành lên npm, có thể dùng package local để thử. Trước khi phát hành app từ CI hoặc chia sẻ dự án độc lập, chuyển dependency `file:../...` về phiên bản npm đã publish và cập nhật lockfile.
|
package/dist/index.d.mts
CHANGED
|
@@ -180,11 +180,19 @@ interface MiniAppPickedFile {
|
|
|
180
180
|
/** Nguồn đã tự nén theo `process` → bỏ qua processors. */
|
|
181
181
|
processed?: boolean;
|
|
182
182
|
}
|
|
183
|
+
/** Mini app đang gọi upload — vd lấy page_id từ context để xin URL upload theo page. */
|
|
184
|
+
interface MiniAppUploadCaller {
|
|
185
|
+
app_id: string;
|
|
186
|
+
instance_id: string;
|
|
187
|
+
/** Context lúc openMiniApp (page_id, client_id…). */
|
|
188
|
+
context: MiniAppContext;
|
|
189
|
+
}
|
|
183
190
|
interface MiniAppUploadSourceRequest {
|
|
184
191
|
/** Như <input accept>; [] = mọi file. Lõi lọc lại sau khi chọn — nguồn chỉ cần dùng làm gợi ý. */
|
|
185
192
|
accept: string[];
|
|
186
193
|
max_count: number;
|
|
187
194
|
process: MiniAppUploadProcessOptions;
|
|
195
|
+
caller: MiniAppUploadCaller;
|
|
188
196
|
}
|
|
189
197
|
/** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
|
|
190
198
|
type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
|
|
@@ -211,6 +219,7 @@ interface MiniAppUploadRequest {
|
|
|
211
219
|
onProgress: (loaded: number, total: number) => void;
|
|
212
220
|
/** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
|
|
213
221
|
signal: AbortSignal;
|
|
222
|
+
caller: MiniAppUploadCaller;
|
|
214
223
|
}
|
|
215
224
|
/** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
|
|
216
225
|
type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
|
|
@@ -218,8 +227,9 @@ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
|
|
|
218
227
|
[key: string]: unknown;
|
|
219
228
|
}>;
|
|
220
229
|
/**
|
|
221
|
-
* Cấu hình uploadFiles.
|
|
222
|
-
*
|
|
230
|
+
* Cấu hình uploadFiles — TUỲ CHỌN. Không truyền gì vẫn có: source `library`, `camera`, `document`,
|
|
231
|
+
* nén ảnh / video (react-native-compressor), target `url`. App chỉ cần khai báo `targets.host` nếu muốn
|
|
232
|
+
* mini app upload lên máy chủ của app. Ghi đè / thêm theo tên; `null` để tắt 1 nguồn có sẵn.
|
|
223
233
|
*/
|
|
224
234
|
interface MiniAppUploadOptions {
|
|
225
235
|
sources?: Record<string, MiniAppUploadSource | null>;
|
|
@@ -227,7 +237,7 @@ interface MiniAppUploadOptions {
|
|
|
227
237
|
image?: MiniAppUploadProcessor;
|
|
228
238
|
video?: MiniAppUploadProcessor;
|
|
229
239
|
};
|
|
230
|
-
/**
|
|
240
|
+
/** `host`: upload lên máy chủ của app (API + token của app). `url` là đích chuẩn, không ghi đè được. */
|
|
231
241
|
targets?: Record<string, MiniAppUploader>;
|
|
232
242
|
}
|
|
233
243
|
/** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
|
|
@@ -670,34 +680,7 @@ interface UploadCapabilities {
|
|
|
670
680
|
targets: string[];
|
|
671
681
|
max_count: number;
|
|
672
682
|
}
|
|
673
|
-
/** Phần @react-native-documents/picker adapter dùng — app truyền module, package không import. */
|
|
674
|
-
interface DocumentPickerLike {
|
|
675
|
-
pick: (options: {
|
|
676
|
-
type?: string | string[];
|
|
677
|
-
allowMultiSelection?: boolean;
|
|
678
|
-
mode?: 'import';
|
|
679
|
-
}) => Promise<{
|
|
680
|
-
uri: string;
|
|
681
|
-
name: string | null;
|
|
682
|
-
type: string | null;
|
|
683
|
-
size: number | null;
|
|
684
|
-
error?: string | null;
|
|
685
|
-
}[]>;
|
|
686
|
-
types: Record<string, string | readonly string[]>;
|
|
687
|
-
isErrorWithCode?: (error: unknown) => boolean;
|
|
688
|
-
errorCodes?: {
|
|
689
|
-
OPERATION_CANCELED: string;
|
|
690
|
-
IN_PROGRESS?: string;
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
/**
|
|
694
|
-
* Nguồn chọn mọi loại file. accept lạ (không map được) → mở toàn bộ file rồi lõi lọc lại theo accept.
|
|
695
|
-
* @example
|
|
696
|
-
* import * as DocumentPicker from '@react-native-documents/picker';
|
|
697
|
-
* <MiniAppHost bridge={{ upload: { sources: { document: createDocumentPickerSource(DocumentPicker) } } }} />
|
|
698
|
-
*/
|
|
699
|
-
declare const createDocumentPickerSource: (picker: DocumentPickerLike) => MiniAppUploadSource;
|
|
700
683
|
/** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
|
|
701
684
|
declare const uploadToUrl: MiniAppUploader;
|
|
702
685
|
|
|
703
|
-
export { DefaultMiniAppSplash, type
|
|
686
|
+
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
|
package/dist/index.d.ts
CHANGED
|
@@ -180,11 +180,19 @@ interface MiniAppPickedFile {
|
|
|
180
180
|
/** Nguồn đã tự nén theo `process` → bỏ qua processors. */
|
|
181
181
|
processed?: boolean;
|
|
182
182
|
}
|
|
183
|
+
/** Mini app đang gọi upload — vd lấy page_id từ context để xin URL upload theo page. */
|
|
184
|
+
interface MiniAppUploadCaller {
|
|
185
|
+
app_id: string;
|
|
186
|
+
instance_id: string;
|
|
187
|
+
/** Context lúc openMiniApp (page_id, client_id…). */
|
|
188
|
+
context: MiniAppContext;
|
|
189
|
+
}
|
|
183
190
|
interface MiniAppUploadSourceRequest {
|
|
184
191
|
/** Như <input accept>; [] = mọi file. Lõi lọc lại sau khi chọn — nguồn chỉ cần dùng làm gợi ý. */
|
|
185
192
|
accept: string[];
|
|
186
193
|
max_count: number;
|
|
187
194
|
process: MiniAppUploadProcessOptions;
|
|
195
|
+
caller: MiniAppUploadCaller;
|
|
188
196
|
}
|
|
189
197
|
/** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
|
|
190
198
|
type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
|
|
@@ -211,6 +219,7 @@ interface MiniAppUploadRequest {
|
|
|
211
219
|
onProgress: (loaded: number, total: number) => void;
|
|
212
220
|
/** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
|
|
213
221
|
signal: AbortSignal;
|
|
222
|
+
caller: MiniAppUploadCaller;
|
|
214
223
|
}
|
|
215
224
|
/** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
|
|
216
225
|
type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
|
|
@@ -218,8 +227,9 @@ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
|
|
|
218
227
|
[key: string]: unknown;
|
|
219
228
|
}>;
|
|
220
229
|
/**
|
|
221
|
-
* Cấu hình uploadFiles.
|
|
222
|
-
*
|
|
230
|
+
* Cấu hình uploadFiles — TUỲ CHỌN. Không truyền gì vẫn có: source `library`, `camera`, `document`,
|
|
231
|
+
* nén ảnh / video (react-native-compressor), target `url`. App chỉ cần khai báo `targets.host` nếu muốn
|
|
232
|
+
* mini app upload lên máy chủ của app. Ghi đè / thêm theo tên; `null` để tắt 1 nguồn có sẵn.
|
|
223
233
|
*/
|
|
224
234
|
interface MiniAppUploadOptions {
|
|
225
235
|
sources?: Record<string, MiniAppUploadSource | null>;
|
|
@@ -227,7 +237,7 @@ interface MiniAppUploadOptions {
|
|
|
227
237
|
image?: MiniAppUploadProcessor;
|
|
228
238
|
video?: MiniAppUploadProcessor;
|
|
229
239
|
};
|
|
230
|
-
/**
|
|
240
|
+
/** `host`: upload lên máy chủ của app (API + token của app). `url` là đích chuẩn, không ghi đè được. */
|
|
231
241
|
targets?: Record<string, MiniAppUploader>;
|
|
232
242
|
}
|
|
233
243
|
/** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
|
|
@@ -670,34 +680,7 @@ interface UploadCapabilities {
|
|
|
670
680
|
targets: string[];
|
|
671
681
|
max_count: number;
|
|
672
682
|
}
|
|
673
|
-
/** Phần @react-native-documents/picker adapter dùng — app truyền module, package không import. */
|
|
674
|
-
interface DocumentPickerLike {
|
|
675
|
-
pick: (options: {
|
|
676
|
-
type?: string | string[];
|
|
677
|
-
allowMultiSelection?: boolean;
|
|
678
|
-
mode?: 'import';
|
|
679
|
-
}) => Promise<{
|
|
680
|
-
uri: string;
|
|
681
|
-
name: string | null;
|
|
682
|
-
type: string | null;
|
|
683
|
-
size: number | null;
|
|
684
|
-
error?: string | null;
|
|
685
|
-
}[]>;
|
|
686
|
-
types: Record<string, string | readonly string[]>;
|
|
687
|
-
isErrorWithCode?: (error: unknown) => boolean;
|
|
688
|
-
errorCodes?: {
|
|
689
|
-
OPERATION_CANCELED: string;
|
|
690
|
-
IN_PROGRESS?: string;
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
/**
|
|
694
|
-
* Nguồn chọn mọi loại file. accept lạ (không map được) → mở toàn bộ file rồi lõi lọc lại theo accept.
|
|
695
|
-
* @example
|
|
696
|
-
* import * as DocumentPicker from '@react-native-documents/picker';
|
|
697
|
-
* <MiniAppHost bridge={{ upload: { sources: { document: createDocumentPickerSource(DocumentPicker) } } }} />
|
|
698
|
-
*/
|
|
699
|
-
declare const createDocumentPickerSource: (picker: DocumentPickerLike) => MiniAppUploadSource;
|
|
700
683
|
/** XHR (không phải fetch) để có tiến trình upload; RN đọc file từ uri (cả content://), không nạp vào JS. */
|
|
701
684
|
declare const uploadToUrl: MiniAppUploader;
|
|
702
685
|
|
|
703
|
-
export { DefaultMiniAppSplash, type
|
|
686
|
+
export { DefaultMiniAppSplash, type LocationOptions, type LocationResult, MINIAPP_PLATFORM_URL, type MiniAppBiometricAvailability, type MiniAppBiometricRequest, type MiniAppBiometricResult, type MiniAppBiometrics, type MiniAppBiometryType, type MiniAppBridgeOptions, type MiniAppCatalogEntry, type MiniAppCatalogItem, type MiniAppChannel, type MiniAppConfig, type MiniAppContainerProps, type MiniAppContext, type MiniAppDownloadState, type MiniAppDownloadStatus, type MiniAppDownloadTask, type MiniAppEvent, type MiniAppFileSystem, type MiniAppHandlerContext, type MiniAppHapticType, _default as MiniAppHost, type MiniAppHostData, BridgeError as MiniAppHostError, type MiniAppHostProps, type MiniAppKeepAlive, type MiniAppLaunch, type MiniAppLocalBundle, type MiniAppManifest, type MiniAppNativeHandlers, type MiniAppPaymentRequest, type MiniAppPaymentResult, type MiniAppPermission, type MiniAppPickedFile, type MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type MiniAppUploadCaller, type MiniAppUploadOptions, type MiniAppUploadProcessOptions, type MiniAppUploadProcessor, type MiniAppUploadRequest, type MiniAppUploadSource, type MiniAppUploadSourceRequest, type MiniAppUploadTarget, type MiniAppUploader, type MiniAppUrlUploadTarget, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, type UploadCapabilities, type UploadFilesResult, type UploadedFile, closeMiniApp, configureMiniApp, createMmkvStorage, createReactNativeBiometrics, createRnfsFileSystem, ensureMiniApp, getLocalMiniApp, getMiniAppCatalog, getMiniAppCatalogEntry, getMiniAppStatuses, getMiniAppUpdate, installBundledMiniApp, onMiniAppEvent, openMiniApp, pauseMiniApp, pauseMiniAppDownloads, preloadMiniApp, releaseSpeechFor, restoreMiniApp, resumeMiniApp, resumeMiniAppDownloads, sendEventToWeb, syncMiniAppCatalog, uninstallMiniApp, updateMiniApp, uploadToUrl, useMiniAppDownload, useMiniAppDownloadsPaused };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Un=Object.create;var Ce=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var Bn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var Vn=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},Mt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $n(t))!qn.call(e,o)&&o!==n&&Ce(e,o,{get:()=>t[o],enumerable:!(i=Fn(t,o))||i.enumerable});return e};var he=(e,t,n)=>(n=e!=null?Un(Bn(e)):{},Mt(t||!e||!e.__esModule?Ce(n,"default",{value:e,enumerable:!0}):n,e)),jn=e=>Mt(Ce({},"__esModule",{value:!0}),e);var vi={};Vn(vi,{DefaultMiniAppSplash:()=>mt,MINIAPP_PLATFORM_URL:()=>Ie,MiniAppHost:()=>In,MiniAppHostError:()=>d,closeMiniApp:()=>we,configureMiniApp:()=>_t,createDocumentPickerSource:()=>Dt,createMmkvStorage:()=>xt,createReactNativeBiometrics:()=>Xe,createRnfsFileSystem:()=>St,ensureMiniApp:()=>Oe,getLocalMiniApp:()=>O,getMiniAppCatalog:()=>On,getMiniAppCatalogEntry:()=>ye,getMiniAppStatuses:()=>Mn,getMiniAppUpdate:()=>gt,installBundledMiniApp:()=>cn,onMiniAppEvent:()=>yn,openMiniApp:()=>gn,pauseMiniApp:()=>Sn,pauseMiniAppDownloads:()=>En,preloadMiniApp:()=>fn,releaseSpeechFor:()=>X,restoreMiniApp:()=>bn,resumeMiniApp:()=>xn,resumeMiniAppDownloads:()=>Pn,sendEventToWeb:()=>un,syncMiniAppCatalog:()=>Ke,uninstallMiniApp:()=>_n,updateMiniApp:()=>Rn,uploadToUrl:()=>tt,useMiniAppDownload:()=>ze,useMiniAppDownloadsPaused:()=>wn});module.exports=jn(vi);var Ie="https://retion-miniapp-platform.vercel.app",ge=null,vt=new Set,_t=e=>{ge=e,vt.forEach(t=>t())},k=()=>{if(!ge)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return ge},bt=e=>{vt.add(e),ge&&e()},H=(...e)=>{ge!=null&&ge.debug&&console.log("[miniapp]",...e)};var St=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(i=>i.map(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:o})=>{let{jobId:s,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:a,contentLength:r})=>o==null?void 0:o(a,r)});return{promise:c.then(({statusCode:a})=>({status:a})),cancel:()=>e.stopDownload(s)}}}),xt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var y=he(require("react")),S=require("react-native"),Cn=he(require("react-native-webview"));var Se=require("react-native");var Xe=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Le,Ze=()=>(Le||(Le=import("react-native-biometrics").then(({default:e})=>Xe(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Le=void 0,new d("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Le);var Q=require("react-native");var Et=e=>{var n,i,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new d("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 d("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[s,c,a]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let r=t[s];if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<c||r>a))throw new d("INVALID_PARAMS",`${s} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${a} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},Pt=(e,t=()=>!0)=>new Promise((n,i)=>{let o=!1,s=(r,l)=>{o||(o=!0,clearTimeout(c),r?i(r):n(l))},c=setTimeout(()=>s(new d("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),a=()=>o?!1:t()?!0:(s(new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!a())return;let r;try{r=(await import("@react-native-community/geolocation")).default}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(a()){if(Q.Platform.OS==="android"){let l=Q.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,u=Q.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,p=await Q.PermissionsAndroid.check(l);if(!a())return;let h=p||await Q.PermissionsAndroid.check(u);if(!a())return;if(!p&&!h){let A=await Q.PermissionsAndroid.requestMultiple([l,u]);if(!a())return;if(A[l]!==Q.PermissionsAndroid.RESULTS.GRANTED&&A[u]!==Q.PermissionsAndroid.RESULTS.GRANTED)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}a()&&r.getCurrentPosition(l=>{a()&&s(void 0,l)},l=>{var p;if(!a())return;let u=(p={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[l.code])!=null?p:"LOCATION_ERROR";s(new d(u,l.message))},e)}})().catch(r=>s(r))});var kt=require("react-native");var et=20,Rt=20,Ct=/^[a-z][a-z0-9_-]{0,31}$/,Hn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Wn=["low","medium","high"],ae=e=>!!e&&typeof e=="object"&&!Array.isArray(e),N=e=>new d("INVALID_PARAMS",e),_e=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ot=(e,t)=>{if(e===void 0)return{};if(!ae(e)||Object.keys(e).length>Rt||Object.values(e).some(n=>typeof n!="string"))throw N(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Rt} key)`);return e},It=e=>{var n,i,o,s;if(e!==void 0&&!ae(e))throw N("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ct.test(t.source)))throw N("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Hn.test(c))))throw N("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!_e(t.max_count,1,et))throw N(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${et}`);if(t.max_size!==void 0&&!_e(t.max_size,1,Number.MAX_SAFE_INTEGER))throw N("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!_e(t.concurrency,1,5))throw N("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(o=t.max_count)!=null?o:1,max_size:t.max_size,process:zn(t.process),target:Jn(t.upload),concurrency:(s=t.concurrency)!=null?s:3}},zn=e=>{if(e===void 0)return{};if(!ae(e))throw N("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!ae(n))throw N("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!_e(n[i],1,1e4))throw N(`process.image.${i} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw N("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!ae(n))throw N("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!_e(n.max_duration,1,3600))throw N("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Wn.includes(n.quality))throw N("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Jn=e=>{var n,i,o,s;if(e===void 0)return{target:"host",params:{}};if(!ae(e))throw N("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ct.test(t))throw N("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!ae(e.params))throw N("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw N("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw N(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Ot(e.headers,"upload.headers"),form_data:Ot(e.form_data,"upload.form_data"),field_name:(o=e.field_name)!=null?o:"file",url_field:(s=e.url_field)!=null?s:"url"}},Lt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Kn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=Lt(e.name);return t.some(o=>o==="*/*"?!0:o.startsWith(".")?o===i:o.endsWith("/*")?n.startsWith(o.slice(0,-1)):n===o)},Yn=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},ve,Gn=()=>(ve!=null||(ve=import("react-native-image-picker").catch(e=>{throw ve=void 0,new d("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),ve),Tt=e=>async({accept:t,max_count:n,process:i})=>{var r,l,u,p,h,A,w,I,P;let o=await Gn(),s=Yn(t),c={mediaType:s==="image"?"photo":s,maxWidth:(r=i.image)==null?void 0:r.max_width,maxHeight:(l=i.image)==null?void 0:l.max_height,quality:(p=(u=i.image)==null?void 0:u.quality)!=null?p:.8,videoQuality:(A=(h=i.video)==null?void 0:h.quality)!=null?A:"medium",durationLimit:(w=i.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},a=e==="camera"?await o.launchCamera({...c,saveToPhotos:!1}):await o.launchImageLibrary({...c,selectionLimit:n});if(a.didCancel)return[];if(a.errorCode){let x=a.errorCode==="permission"?"PERMISSION_DENIED":a.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new d(x,(I=a.errorMessage)!=null?I:a.errorCode)}return((P=a.assets)!=null?P:[]).filter(x=>x.uri).map((x,m)=>{var L,J,$;return{uri:x.uri,name:(L=x.fileName)!=null?L:`file_${m+1}`,mime_type:(J=x.type)!=null?J:"application/octet-stream",size:x.fileSize,width:x.width,height:x.height,duration:x.duration,processed:!(($=x.type)!=null&&$.startsWith("video/"))||kt.Platform.OS==="ios"}})},Qn={"image/*":"images","video/*":"video","audio/*":"audio","text/plain":"plainText","text/csv":"csv","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","application/vnd.ms-powerpoint":"ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":"pptx"},Xn={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Dt=e=>async({accept:t,max_count:n})=>{var s,c,a,r;let i=t.map(l=>{var u;return(u=Qn[l])!=null?u:Xn[l]}),o=!t.length||i.some(l=>!l||!e.types[l])?e.types.allFiles:[...new Set(i)].flatMap(l=>e.types[l]);try{return(await e.pick({type:o,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,p)=>{var h,A,w;return{uri:u.uri,name:(h=u.name)!=null?h:`file_${p+1}`,mime_type:(A=u.type)!=null?A:"application/octet-stream",size:(w=u.size)!=null?w:void 0}})}catch(l){let u=l==null?void 0:l.code;if(u===((c=(s=e.errorCodes)==null?void 0:s.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw u===((r=(a=e.errorCodes)==null?void 0:a.IN_PROGRESS)!=null?r:"ASYNC_OP_IN_PROGRESS")?new d("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):l}},Zn={library:Tt("library"),camera:Tt("camera")},ei=(e,t)=>t.split(".").reduce((n,i)=>ae(n)?n[i]:void 0,e),tt=({file:e,target:t,onProgress:n,signal:i})=>new Promise((o,s)=>{if(t.target!=="url"||!("url"in t)){s(new d("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){s(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let a=new XMLHttpRequest,r=new FormData;Object.entries(c.form_data).forEach(([p,h])=>r.append(p,h)),r.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let l=()=>a.abort();i.addEventListener("abort",l);let u=p=>{i.removeEventListener("abort",l),p()};a.open("POST",c.url),Object.entries(c.headers).forEach(([p,h])=>a.setRequestHeader(p,h)),a.upload.onprogress=p=>n(p.loaded,p.total||e.size||0),a.onload=()=>u(()=>{let p=a.responseText;try{p=JSON.parse(a.responseText)}catch{}if(a.status<200||a.status>=300){s(new d("UPLOAD_FAILED",`HTTP ${a.status}`));return}let h=ei(p,c.url_field);if(typeof h!="string"||!h){s(new d("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}o({url:h,response:p})}),a.onerror=()=>u(()=>s(new d("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),a.onabort=()=>u(()=>s(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),a.send(r)}),Nt=e=>{var i,o;let t={...Zn};for(let[s,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[s]=c:delete t[s];let n={url:tt};for(let[s,c]of Object.entries((o=e==null?void 0:e.targets)!=null?o:{}))s!=="url"&&c&&(n[s]=c);return{sources:t,targets:n}},Ut=e=>{let{sources:t,targets:n}=Nt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:et}},Ne=new Map,Ft=(e,t)=>`${e}:${t}`,ti=0,$t=(e,t)=>{var n;typeof t=="string"&&((n=Ne.get(Ft(e,t)))==null||n.abort())},fe=e=>{for(let[t,n]of Ne)t.startsWith(`${e}:`)&&n.abort()},De=()=>new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),ni=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Bt=async(e,t)=>{var r;let{sources:n,targets:i}=Nt(t.config),o=n[e.source];if(!o)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let s=i[e.target.target];if(!s)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,a=Ft(t.instance_id,(r=t.task_id)!=null?r:`auto-${++ti}`);Ne.set(a,c);try{return await ii(e,t,o,s,c.signal)}finally{Ne.delete(a)}},ii=async(e,{task_id:t,config:n,emit:i,exclusivePick:o=r=>r()},s,c,a)=>{var J,$;let r=(await o(()=>s({accept:e.accept,max_count:e.max_count,process:e.process}))).slice(0,e.max_count);if(a.aborted)throw De();if(!r.length)throw new d("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],u=r.filter(R=>Kn(R,e.accept)?!0:(l.push({name:R.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${R.mime_type||Lt(R.name)}`}),!1)),p=u.map(()=>0),h=u.map(R=>{var f;return(f=R.size)!=null?f:0}),A=0,w=0,I=(R=!1)=>{if(!i||!t)return;let f=Date.now();if(!R&&f-w<200)return;w=f;let M=h.reduce((F,D)=>F+D,0),_=p.reduce((F,D)=>F+D,0);i("upload.progress",{task_id:t,loaded:_,total:M,percent:M?Math.min(100,Math.round(_/M*100)):0,done_count:A,count:u.length})},P=[],x=0,m=async()=>{var R,f;for(;x<u.length;){let M=x++,_=u[M];try{if(a.aborted)throw De();let F=_.mime_type.startsWith("image/")?"image":_.mime_type.startsWith("video/")?"video":void 0,D=F&&!_.processed?(R=n==null?void 0:n.processors)==null?void 0:R[F]:void 0;if(D&&(_=await D(_,e.process),h[M]=(f=_.size)!=null?f:h[M],a.aborted))throw De();if(e.max_size&&_.size&&_.size>e.max_size)throw new d("FILE_TOO_LARGE",`File ${_.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let j=(Te,oe)=>{p[M]=Te,oe&&(h[M]=oe),I()},re=await c({file:_,target:e.target,onProgress:j,signal:a});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new d("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Ye,...ue}=re;P[M]={url:Ye,name:_.name,mime_type:_.mime_type,size:_.size,width:_.width,height:_.height,duration:_.duration,...Object.keys(ue).length?{response:"response"in ue?ue.response:ue}:{}},p[M]=h[M]}catch(F){l.push(ni(u[M].name,F))}finally{A++,I(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,u.length)},m)),a.aborted)throw De();let L=P.filter(R=>!!R);if(!L.length){let R=l[0];throw new d((J=R==null?void 0:R.code)!=null?J:"UPLOAD_FAILED",($=R==null?void 0:R.message)!=null?$:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:L,failed:l}};var qt=require("react-native");var te,nt=e=>{var t;if(te===e&&(te=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&qt.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Vt=async(e,t,n,i=()=>!0)=>{var s,c,a,r,l;if(te)throw new d("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};te=o;try{let u;try{u=await import("expo-speech-recognition")}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let p=u.ExpoSpeechRecognitionModule;if(o.native=p,o.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let h=await p.requestPermissionsAsync();if(o.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!h.granted)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await p.getStateAsync()!=="inactive")throw new d("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(p.addListener("result",A=>{var w,I;te!==o||o.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(I=(w=A.results[0])==null?void 0:w.transcript)!=null?I:""})}),p.addListener("error",A=>{te===o&&!o.cancelled&&n("speech.error",{...A,code:A.error})}),p.addListener("end",()=>{te===o&&(nt(o),n("speech.end"))})),o.started=!0,p.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(a=t.interimResults)!=null?a:!0,addsPunctuation:(r=t.addsPunctuation)!=null?r:!0,requiresOnDeviceRecognition:(l=t.requiresOnDeviceRecognition)!=null?l:!1,iosCategory:{category:u.AVAudioSessionCategory.playAndRecord,categoryOptions:[u.AVAudioSessionCategoryOptions.defaultToSpeaker,u.AVAudioSessionCategoryOptions.allowBluetooth],mode:u.AVAudioSessionMode.measurement}})}catch(u){throw nt(o),u}},jt=e=>{let t=te;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},X=e=>{let t=te;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{nt(t)}};var Fe=1,d=class extends Error{constructor(n,i){super(i);this.code=n}},Ht=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Fe&&typeof t.method=="string"?t:null}catch{return null}},xe=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Wt=(e,t)=>xe({id:e,result:t}),zt=(e,t)=>xe({id:e,error:{code:t.code,message:t.message}}),Jt=(e,t)=>xe({event:e,data:t}),rt=e=>xe({event:"context",data:e});var Kt=()=>`(function () {
|
|
1
|
+
"use strict";var Vn=Object.create;var Fe=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Hn=Object.prototype.hasOwnProperty;var Wn=(e,t)=>{for(var n in t)Fe(e,n,{get:t[n],enumerable:!0})},xt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jn(t))!Hn.call(e,i)&&i!==n&&Fe(e,i,{get:()=>t[i],enumerable:!(r=qn(t,i))||r.enumerable});return e};var ue=(e,t,n)=>(n=e!=null?Vn(zn(e)):{},xt(t||!e||!e.__esModule?Fe(n,"default",{value:e,enumerable:!0}):n,e)),Jn=e=>xt(Fe({},"__esModule",{value:!0}),e);var kr={};Wn(kr,{DefaultMiniAppSplash:()=>vt,MINIAPP_PLATFORM_URL:()=>$e,MiniAppHost:()=>$n,MiniAppHostError:()=>u,closeMiniApp:()=>_e,configureMiniApp:()=>Pt,createMmkvStorage:()=>Tt,createReactNativeBiometrics:()=>rt,createRnfsFileSystem:()=>Ot,ensureMiniApp:()=>De,getLocalMiniApp:()=>R,getMiniAppCatalog:()=>Dn,getMiniAppCatalogEntry:()=>be,getMiniAppStatuses:()=>En,getMiniAppUpdate:()=>yt,installBundledMiniApp:()=>mn,onMiniAppEvent:()=>xn,openMiniApp:()=>yn,pauseMiniApp:()=>Tn,pauseMiniAppDownloads:()=>kn,preloadMiniApp:()=>Mn,releaseSpeechFor:()=>ee,restoreMiniApp:()=>On,resumeMiniApp:()=>Cn,resumeMiniAppDownloads:()=>In,sendEventToWeb:()=>An,syncMiniAppCatalog:()=>et,uninstallMiniApp:()=>Rn,updateMiniApp:()=>Ln,uploadToUrl:()=>at,useMiniAppDownload:()=>Xe,useMiniAppDownloadsPaused:()=>bn});module.exports=Jn(kr);var $e="https://retion-miniapp-platform.vercel.app",we=null,Et=new Set,Pt=e=>{we=e,Et.forEach(t=>t())},k=()=>{if(!we)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return we},Rt=e=>{Et.add(e),we&&e()},J=(...e)=>{we!=null&&we.debug&&console.log("[miniapp]",...e)};var Ot=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(i=>i.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:i})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>i==null?void 0:i(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),Tt=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var y=ue(require("react")),E=require("react-native"),Fn=ue(require("react-native-webview"));var Te=require("react-native");var rt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Be,it=()=>(Be||(Be=import("react-native-biometrics").then(({default:e})=>rt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Be=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Be);var Z=require("react-native");var Ct=e=>{var n,r,i;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(i=t.maximumAge)!=null?i:0}},kt=(e,t=()=>!0)=>new Promise((n,r)=>{let i=!1,o=(a,s)=>{i||(i=!0,clearTimeout(c),a?r(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>i?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(Z.Platform.OS==="android"){let s=Z.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,d=Z.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await Z.PermissionsAndroid.check(s);if(!p())return;let A=g||await Z.PermissionsAndroid.check(d);if(!p())return;if(!g&&!A){let l=await Z.PermissionsAndroid.requestMultiple([s,d]);if(!p())return;if(l[s]!==Z.PermissionsAndroid.RESULTS.GRANTED&&l[d]!==Z.PermissionsAndroid.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});var st=require("react-native");var ot=20,It=20,Nt=/^[a-z][a-z0-9_-]{0,31}$/,Kn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Yn=["low","medium","high"],de=e=>!!e&&typeof e=="object"&&!Array.isArray(e),N=e=>new u("INVALID_PARAMS",e),Re=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Lt=(e,t)=>{if(e===void 0)return{};if(!de(e)||Object.keys(e).length>It||Object.values(e).some(n=>typeof n!="string"))throw N(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${It} key)`);return e},Ut=e=>{var n,r,i,o;if(e!==void 0&&!de(e))throw N("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Nt.test(t.source)))throw N("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Kn.test(c))))throw N("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Re(t.max_count,1,ot))throw N(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${ot}`);if(t.max_size!==void 0&&!Re(t.max_size,1,Number.MAX_SAFE_INTEGER))throw N("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Re(t.concurrency,1,5))throw N("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(c=>c.toLowerCase()),max_count:(i=t.max_count)!=null?i:1,max_size:t.max_size,process:Gn(t.process),target:Qn(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Gn=e=>{if(e===void 0)return{};if(!de(e))throw N("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!de(n))throw N("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Re(n[r],1,1e4))throw N(`process.image.${r} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw N("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!de(n))throw N("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Re(n.max_duration,1,3600))throw N("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Yn.includes(n.quality))throw N("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Qn=e=>{var n,r,i,o;if(e===void 0)return{target:"host",params:{}};if(!de(e))throw N("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Nt.test(t))throw N("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!de(e.params))throw N("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw N("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw N(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Lt(e.headers,"upload.headers"),form_data:Lt(e.form_data,"upload.form_data"),field_name:(i=e.field_name)!=null?i:"file",url_field:(o=e.url_field)!=null?o:"url"}},Ft=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Xn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=Ft(e.name);return t.some(i=>i==="*/*"?!0:i.startsWith(".")?i===r:i.endsWith("/*")?n.startsWith(i.slice(0,-1)):n===i)},Zn=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},xe,er=()=>(xe!=null||(xe=import("react-native-image-picker").catch(e=>{throw xe=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),xe),Dt=e=>async({accept:t,max_count:n,process:r})=>{var a,s,d,g,A,l,h,T,_;let i=await er(),o=Zn(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=r.image)==null?void 0:a.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(A=r.video)==null?void 0:A.quality)!=null?l:"medium",durationLimit:(h=r.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await i.launchCamera({...c,saveToPhotos:!1}):await i.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let b=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(b,(T=p.errorMessage)!=null?T:p.errorCode)}return((_=p.assets)!=null?_:[]).filter(b=>b.uri).map((b,f)=>{var L,Y,$;return{uri:b.uri,name:(L=b.fileName)!=null?L:`file_${f+1}`,mime_type:(Y=b.type)!=null?Y:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!(($=b.type)!=null&&$.startsWith("video/"))||st.Platform.OS==="ios"}})},tr={"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"},nr={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},rr=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let r=t.map(s=>{var d;return(d=tr[s])!=null?d:nr[s]}),i=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:i,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var T,_,b;return{uri:l.uri,name:(T=l.name)!=null?T:`file_${h+1}`,mime_type:(_=l.type)!=null?_:"application/octet-stream",size:(b=l.size)!=null?b:void 0}});if(st.Platform.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),A=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=A.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},Ee,ir=async e=>(Ee!=null||(Ee=import("@react-native-documents/picker").then(t=>rr(t)).catch(t=>{throw Ee=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await Ee)(e)),or={library:Dt("library"),camera:Dt("camera"),document:ir},Pe,$t=()=>(Pe!=null||(Pe=import("react-native-compressor").catch(()=>(Pe=void 0,null))),Pe),Bt=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},sr=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),ar={low:640,medium:1280,high:1920},cr=async(e,{image:t})=>{var r;if(!t||!sr.has(e.mime_type.toLowerCase()))return e;let n=await $t();if(!n)return e;try{let i=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:i,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Bt(n,i,e.size),processed:!0}}catch{return e}},pr=async(e,{video:t})=>{var r;let n=await $t();if(!n)return e;try{let i=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:ar[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:i,mime_type:"video/mp4",size:await Bt(n,i,e.size),processed:!0}}catch{return e}},lr={image:cr,video:pr},ur=(e,t)=>t.split(".").reduce((n,r)=>de(n)?n[r]:void 0,e),at=({file:e,target:t,onProgress:n,signal:r})=>new Promise((i,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(r.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,A])=>a.append(g,A)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,A])=>p.setRequestHeader(g,A)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let A=ur(g,c.url_field);if(typeof A!="string"||!A){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}i({url:A,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Vt=e=>{var r,i;let t={...or};for(let[o,c]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))c?t[o]=c:delete t[o];let n={url:at};for(let[o,c]of Object.entries((i=e==null?void 0:e.targets)!=null?i:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},qt=e=>{let{sources:t,targets:n}=Vt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:ot}},qe=new Map,jt=(e,t)=>`${e}:${t}`,dr=0,zt=(e,t)=>{var n;typeof t=="string"&&((n=qe.get(jt(e,t)))==null||n.abort())},ye=e=>{for(let[t,n]of qe)t.startsWith(`${e}:`)&&n.abort()},Ve=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),gr=(e,t)=>{var n;return{name:e,code:typeof(t==null?void 0:t.code)=="string"?t.code:"UPLOAD_FAILED",message:String((n=t==null?void 0:t.message)!=null?n:t)}},Ht=async(e,t)=>{var a;let{sources:n,targets:r}=Vt(t.config),i=n[e.source];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=r[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=jt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++dr}`);qe.set(p,c);try{return await mr(e,t,i,o,c.signal)}finally{qe.delete(p)}},mr=async(e,{instance_id:t,app_id:n,getContext:r,task_id:i,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var w,S,z;let g={app_id:n!=null?n:"",instance_id:t,context:{...(w=r==null?void 0:r())!=null?w:{}}},A=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw Ve();if(!A.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=A.filter(v=>Xn(v,e.accept)?!0:(l.push({name:v.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${v.mime_type||Ft(v.name)}`}),!1)),T=h.map(()=>0),_=h.map(v=>{var D;return(D=v.size)!=null?D:0}),b=0,f=0,L=(v=!1)=>{if(!c||!i)return;let D=Date.now();if(!v&&D-f<200)return;f=D;let ne=_.reduce((C,H)=>C+H,0),B=T.reduce((C,H)=>C+H,0);c("upload.progress",{task_id:i,loaded:B,total:ne,percent:ne?Math.min(100,Math.round(B/ne*100)):0,done_count:b,count:h.length})},Y=[],$=0,ve=async()=>{var v,D,ne;for(;$<h.length;){let B=$++,C=h[B];try{if(d.aborted)throw Ve();let H=C.mime_type.startsWith("image/")?"image":C.mime_type.startsWith("video/")?"video":void 0,pe=H&&!C.processed?(D=(v=o==null?void 0:o.processors)==null?void 0:v[H])!=null?D:lr[H]:void 0;if(pe&&(C=await pe(C,e.process),_[B]=(ne=C.size)!=null?ne:_[B],d.aborted))throw Ve();if(e.max_size&&C.size&&C.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${C.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let he=(Ne,Ue)=>{T[B]=Ne,Ue&&(_[B]=Ue),L()},re=await s({file:C,target:e.target,onProgress:he,signal:d,caller:g});if(typeof(re==null?void 0:re.url)!="string"||!re.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:tt,...ie}=re;Y[B]={url:tt,name:C.name,mime_type:C.mime_type,size:C.size,width:C.width,height:C.height,duration:C.duration,...Object.keys(ie).length?{response:"response"in ie?ie.response:ie}:{}},T[B]=_[B]}catch(H){l.push(gr(h[B].name,H))}finally{b++,L(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},ve)),d.aborted)throw Ve();let ce=Y.filter(v=>!!v);if(!ce.length){let v=l[0];throw new u((S=v==null?void 0:v.code)!=null?S:"UPLOAD_FAILED",(z=v==null?void 0:v.message)!=null?z:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ce,failed:l}};var Wt=require("react-native");var oe,ct=e=>{var t;if(oe===e&&(oe=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Wt.Platform.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Jt=async(e,t,n,r=()=>!0)=>{var o,c,p,a,s;if(oe)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let i={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};oe=i;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(i.native=g,i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let A=await g.requestPermissionsAsync();if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!A.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.subscriptions.push(g.addListener("result",l=>{var h,T;oe!==i||i.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(T=(h=l.results[0])==null?void 0:h.transcript)!=null?T:""})}),g.addListener("error",l=>{oe===i&&!i.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{oe===i&&(ct(i),n("speech.end"))})),i.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw ct(i),d}},Kt=e=>{let t=oe;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ee=e=>{let t=oe;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{ct(t)}};var ze=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Yt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===ze&&typeof t.method=="string"?t:null}catch{return null}},Ce=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Gt=(e,t)=>Ce({id:e,result:t}),Qt=(e,t)=>Ce({id:e,error:{code:t.code,message:t.message}}),Xt=(e,t)=>Ce({event:e,data:t}),lt=e=>Ce({event:"context",data:e});var Zt=()=>`(function () {
|
|
2
2
|
var post = function (level, args) {
|
|
3
3
|
try {
|
|
4
4
|
var parts = [];
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
|
|
9
9
|
else { parts.push(String(a)); }
|
|
10
10
|
}
|
|
11
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
11
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${ze}, method: 'log', level: level, text: parts.join(' ') }));
|
|
12
12
|
} catch (e) {}
|
|
13
13
|
};
|
|
14
14
|
['log', 'info', 'warn', 'error'].forEach(function (level) {
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
|
|
20
20
|
// Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
|
|
21
21
|
post('info', ['[page] ' + location.pathname + location.hash]);
|
|
22
|
-
})(); true;`,
|
|
22
|
+
})(); true;`,en=()=>`(function () {
|
|
23
23
|
function atTop(el) {
|
|
24
24
|
for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
|
|
25
25
|
if (n.scrollTop > 0) { return false; }
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
function report(at_top) {
|
|
31
31
|
if (at_top === last) { return; }
|
|
32
32
|
last = at_top;
|
|
33
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
33
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${ze}, method: 'touchAtTop', at_top: at_top }));
|
|
34
34
|
}
|
|
35
35
|
document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
|
|
36
36
|
// Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
|
|
@@ -38,8 +38,29 @@
|
|
|
38
38
|
var el = e.target === document ? document.documentElement : e.target;
|
|
39
39
|
if (el && el.scrollTop > 0) { report(false); }
|
|
40
40
|
}, { capture: true, passive: true });
|
|
41
|
-
})(); true;`,
|
|
42
|
-
|
|
41
|
+
})(); true;`,tn=()=>`(function () {
|
|
42
|
+
if (window.__retionSafeAreaFrozen) { return; }
|
|
43
|
+
window.__retionSafeAreaFrozen = true;
|
|
44
|
+
var max = {};
|
|
45
|
+
var orig = window.getComputedStyle;
|
|
46
|
+
window.getComputedStyle = function (el, pseudo) {
|
|
47
|
+
var style = orig.call(this, el, pseudo);
|
|
48
|
+
var m = el && el.style && /env\\(safe-area-inset-(top|right|bottom|left)\\)/.exec(el.style.cssText || '');
|
|
49
|
+
if (!m) { return style; }
|
|
50
|
+
var prop = 'padding-' + m[1];
|
|
51
|
+
var value = parseFloat(style.getPropertyValue(prop)) || 0;
|
|
52
|
+
if (!(prop in max) || value > max[prop]) { max[prop] = value; }
|
|
53
|
+
var frozen = max[prop] + 'px';
|
|
54
|
+
return new Proxy(style, {
|
|
55
|
+
get: function (t, k) {
|
|
56
|
+
if (k === 'getPropertyValue') { return function (p) { return p === prop ? frozen : t.getPropertyValue(p); }; }
|
|
57
|
+
var v = t[k];
|
|
58
|
+
return typeof v === 'function' ? v.bind(t) : v;
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
})(); true;`,nn=e=>Ce({event:e}),rn=(e,t)=>{let n=on(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
|
|
63
|
+
${lt(e)}`},on=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),sn=(e,t={})=>{let n=on(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${ze} };
|
|
43
64
|
window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
|
|
44
65
|
${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
|
|
45
|
-
true;`},en={partner:"partner_token",chatbox:"chatbox_token"},tn=(e,t)=>{let n={...e};for(let i of Object.values(en))t.includes(i)||delete n[i];return n},it=new Set,be=async(e,t)=>{if(it.has(e))throw new d("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);it.add(e);try{return await t()}finally{it.delete(e)}},ri=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Ue=(e,t)=>{if(typeof e!="string"||!e)throw new d("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},nn=async({method:e,params:t},{getHostData:n,getPermissions:i,is_dark:o,close:s,app_id:c,instance_id:a,options:r,emit:l,isActive:u})=>{var w,I,P,x,m,L,J,$,R;let p=r==null?void 0:r.handlers,h={app_id:c,instance_id:a,close:s},A=()=>new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let f=Et(t);return be(e,()=>Pt(f,u))}case"speech.start":{if(!l)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 d("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");f.lang=t.lang}for(let M of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[M])!==void 0){if(typeof t[M]!="boolean")throw new d("INVALID_PARAMS",`${M} ph\u1EA3i l\xE0 boolean`);f[M]=t[M]}return Vt(a,f,l,u)}case"speech.stop":return jt(a);case"uploadFiles":{let{task_id:f,...M}=t!=null?t:{};if(f!==void 0&&(typeof f!="string"||!f))throw new d("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Bt(It(M),{instance_id:a,task_id:f,config:r==null?void 0:r.upload,emit:l,exclusivePick:_=>be("uploadFiles.pick",_)})}case"uploadFiles.cancel":$t(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Ut(r==null?void 0:r.upload);case"getBiometricAvailability":return((w=r==null?void 0:r.biometrics)!=null?w:await Ze()).getAvailability();case"authenticateBiometric":{let f=Ue(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new d("INVALID_PARAMS","reason must contain 1\u2013200 characters");let M=t==null?void 0:t.cancelButtonText;if(M!==void 0&&(typeof M!="string"||!M.trim()||M.length>80))throw new d("INVALID_PARAMS","Invalid cancelButtonText");return be(e,async()=>{var F;return((F=r==null?void 0:r.biometrics)!=null?F:await Ze()).authenticate({reason:f,cancelButtonText:M})})}case"requestPayment":{let f=p==null?void 0:p.requestPayment;if(!f)throw A();let M=t==null?void 0:t.amount;if(typeof M!="number"||!Number.isFinite(M)||M<=0)throw new d("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let _={...t,amount:M,currency:Ue(t==null?void 0:t.currency,"currency")};return be(e,()=>f(_,h))}case"printImage":{let f=p==null?void 0:p.printImage;if(!f)throw A();let M=Ue(t==null?void 0:t.image,"image");await be(e,()=>f({image:M},h));return}case"openScreen":if(!(p!=null&&p.openScreen))throw A();await p.openScreen({screen:Ue(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},h);return;case"closeApp":s();return;case"openWebview":{let f=String((I=t==null?void 0:t.url)!=null?I:"");if(!/^https?:\/\//i.test(f))throw new d("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(r!=null&&r.openUrl?r.openUrl(f):Se.Linking.openURL(f));return}case"openLink":{let f=String((P=t==null?void 0:t.url)!=null?P:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new d("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(r!=null&&r.openUrl?r.openUrl(f):Se.Linking.openURL(f))}catch(M){throw new d("NOT_SUPPORTED",String((m=(x=M==null?void 0:M.message)!=null?x:M)!=null?m:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(J=r==null?void 0:r.showToast)==null||J.call(r,String((L=t==null?void 0:t.message)!=null?L:""));return;case"haptic":{let f=ri.has(t==null?void 0:t.type)?t.type:"selection";($=r==null?void 0:r.haptic)==null||$.call(r,f);return}case"getSystemInfo":return{platform:Se.Platform.OS==="ios"?"ios":"android",appVersion:(R=r==null?void 0:r.app_version)!=null?R:"",theme:o?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new d("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 F=n().access_token;if(!F)throw new d("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return F}if(f!=="partner"&&f!=="chatbox")throw new d("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let M=en[f];if(!i().includes(M))throw new d("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${M} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let _=f==="partner"?n().partner_token:n().chatbox_token;if(!_)throw new d("HOST_ERROR",`Kh\xF4ng c\xF3 ${M}`);return _}case"getUserInfo":{let f=n().user;if(!f)throw new d("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 d("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new d("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var st=e=>`bundle:${e}`,at=()=>`${k().file_system.document_dir}/miniapps`,ct=at,lt=(e,t,n="index.html",i=!1,o=[])=>{let s=`${ct()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:i,permissions:o}},ot=e=>{var t;k().storage.setString(st(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},oi=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,O=e=>{let t=k().storage.getString(st(e));if(!t)return null;try{let{version:n,entry:i,context_update:o,permissions:s}=JSON.parse(t);return lt(e,n,i,!!o,Array.isArray(s)?s:[])}catch{return null}},ne=e=>k().file_system.exists(e.entry_uri.replace("file://","")),pt=async e=>{let t=O(e.app_id);return(t==null?void 0:t.version)===e.version&&await ne(t)},on=async(e,t)=>{let n=k().file_system,i=`${ct()}/${e}`,o=await n.listDir(i).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${i}/${s}`).catch(()=>{})))},sn=async e=>{var t;await((t=Pe[e])==null?void 0:t.catch(()=>{})),k().storage.setString(st(e),""),await k().file_system.remove(`${ct()}/${e}`).catch(()=>{})},Ae=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Pe={},an=(e,t)=>{var s;let i=((s=Pe[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=i.catch(()=>{});return Pe[e]=o,o.then(()=>{Pe[e]===o&&delete Pe[e]}),i},si=(e,t)=>{var o,s;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let a=((o=n[c])!=null?o:0)-((s=i[c])!=null?s:0);if(a)return a}return 0},cn=({manifest:e,zip_path:t})=>an(e.app_id,async()=>{var s;let n=k().file_system,i=O(e.app_id);if(i&&si(i.version,e.version)>=0&&await ne(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=lt(e.app_id,e.version,e.entry,!!e.context_update,(s=e.permissions)!=null?s:[]);return await n.remove(o.dir).catch(()=>{}),await n.mkdir(o.dir),await n.unzip(t,o.dir),ot(e),H("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),on(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),o}),ut=(e,{base_url:t,onProgress:n}={})=>{let i=k().file_system,o=null,s=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,a=()=>{if(s)throw new Ae},r=async()=>{var p;a();let l=O(e.app_id);if((l==null?void 0:l.version)===e.version&&await i.exists(l.dir))return ot(e),O(e.app_id);a();let u=i.download({url:t?oi(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(h,A)=>{var I;let w=A>0?A:(I=e.size)!=null?I:0;w>0&&(n==null||n(Math.min(1,h/w)))}});o=u;try{let{status:h}=await u.promise;if(a(),h!==200)throw new Error(`bundle ${h}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else H("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);a();let A=lt(e.app_id,e.version,e.entry,!!e.context_update,(p=e.permissions)!=null?p:[]);return await i.remove(A.dir).catch(()=>{}),await i.mkdir(A.dir),await i.unzip(c,A.dir),ot(e),on(e.app_id,[e.version,l==null?void 0:l.version].filter(Boolean)),A}catch(h){throw s?new Ae:h}finally{o=null,i.remove(c).catch(()=>{})}};return{promise:an(e.app_id,r),cancel:()=>{s=!0,o==null||o.cancel()}}},Ee={},ai=__DEV__?0:60*1e3,rn={},ln=(e,t)=>{var i,o;let n=O(e);return n&&Date.now()-((i=rn[t])!=null?i:0)<ai?Promise.resolve(n):((o=Ee[e])!=null||(Ee[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let c=await s.json(),a=await ut(c,{base_url:t}).promise;return rn[t]=Date.now(),a})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),O(e))).finally(()=>{Ee[e]=void 0})),Ee[e])};var $e=new Map,pn=(e,t)=>($e.set(e,t),()=>{$e.get(e)===t&&$e.delete(e)}),un=(e,t)=>{let n=$e.get(e);return n?n(t):!1};var Be=require("react"),qe=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let o=typeof i=="function"?i(t):i;t={...t,...o},n.forEach(s=>s())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},Z=(e,t,n=Object.is)=>{let i=(0,Be.useRef)(null),o=()=>{let s=e.getState(),c=i.current;if(c&&c.state===s&&c.selector===t)return c.value;let a=t(s),r=c&&n(c.value,a)?c.value:a;return i.current={state:s,selector:t,value:r},r};return(0,Be.useSyncExternalStore)(e.subscribe,o)};var W=qe({active_key:null,instances:{}}),dn=({app:e,instance_id:t,context:n={},url_params:i={},host_data:o={}},s)=>{var a;let c=(a=k().keep_alive)==null?void 0:a.max_webviews;W.setState(r=>{let l=t!=null?t:e.app_id,u={...r.instances,[l]:{key:l,app:e,context:n,url_params:i,host_data:o,last_used_at:Date.now()}},p=Object.keys(u);return c&&c>0&&p.length>c&&p.filter(h=>h!==l).sort((h,A)=>u[h].last_used_at-u[A].last_used_at).slice(0,p.length-c).forEach(h=>{delete u[h]}),s?{active_key:l,instances:u}:{instances:u}})},gn=e=>dn(e,!0),fn=e=>dn(e,!1),we=()=>W.setState({active_key:null}),Ve=e=>{W.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var mn="catalog",ci="paused_apps",li="removed_apps",pi=10*1e3,ui=2,di=3e3,gi=()=>{var e;try{return JSON.parse((e=k().storage.getString(mn))!=null?e:"{}")}catch{return{}}},E=qe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),hn=e=>{var t;return!!((t=k().manual_update)!=null&&t.includes(e))},We=new Set,An=e=>{let t=new Set,n=()=>k().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let o=JSON.parse((i=k().storage.getString(e))!=null?i:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},G=An(ci),pe=An(li);bt(()=>{G.load(),pe.load();let e=gi(),t={};Object.keys(e).filter(n=>!pe.has(n)).forEach(n=>{let i=O(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:G.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),E.setState({catalog:e,downloads:t})});var ze=e=>Z(E,t=>e?t.downloads[e]:void 0),wn=()=>Z(E,e=>e.pause_reasons.length>0),Y=(...e)=>H("queue",...e),U=[],ie={},b=null,je=new Set,me={},dt=new Set,ce=e=>{dt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},yn=e=>(dt.add(e),()=>{dt.delete(e)}),Mn=()=>E.getState().downloads,V=(e,t)=>{let n=!!O(e),i=E.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...i!=null?i:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};E.setState(c=>({downloads:{...c.downloads,[e]:s}})),(i==null?void 0:i.status)!==s.status||(i==null?void 0:i.version)!==s.version||(i==null?void 0:i.has_local)!==s.has_local?ce({type:"status_change",app_id:e,state:s}):i.progress!==s.progress&&ce({type:"progress",app_id:e,progress:s.progress,version:s.version})},He=(e,t)=>{var n;(n=me[e])==null||n.forEach(i=>i(t)),delete me[e]},fi=()=>E.getState().pause_reasons.length>0,le=e=>{var a;if(b)return;let t=e?U.indexOf(e):fi()?-1:U.findIndex(r=>!G.has(r));if(t<0||t>=U.length)return;let[n]=U.splice(t,1),i=E.getState().catalog[n];if(!i){He(n,O(n)),le();return}let o=Date.now();ie[n]=((a=ie[n])!=null?a:0)+1,V(n,{status:"downloading",progress:0,version:i.version,error:void 0});let s=0,c=ut(i,{onProgress:r=>{let l=Math.floor(r*100);l!==s&&(s=l,V(n,{progress:l/100,version:i.version}))}});b={app_id:n,handle:c,forced:!!e},Y("start",n,i.version,e?"(forced)":""),c.promise.then(r=>{Y("installed",n,i.version,`${Date.now()-o}ms`),V(n,{status:"installed",progress:1,version:i.version}),He(n,r)}).catch(r=>{var u;if(r instanceof Ae){if(je.has(n))return;Y("paused",n),ie[n]-=1,U.unshift(n),V(n,{status:G.has(n)?"paused":"queued",progress:0,version:i.version});return}let l=String((u=r==null?void 0:r.message)!=null?u:r);if(console.warn("[miniapp-queue] failed",n,l),ie[n]<ui){V(n,{status:"queued",progress:0,version:i.version,error:l}),setTimeout(()=>{var p;U.includes(n)||(b==null?void 0:b.app_id)===n||(U.push(n),le((p=me[n])!=null&&p.length?n:void 0))},di);return}V(n,{status:"failed",progress:0,version:i.version,error:l}),He(n,O(n))}).finally(()=>{b=null;let r=U.find(l=>{var u;return(u=me[l])==null?void 0:u.length});le(r)})},Je=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=U.indexOf(e);if(n>=0){if(!t)return;U.splice(n,1)}t?U.unshift(e):U.push(e)},mi=async e=>{let{host_id:t,client_token:n}=k(),i=new AbortController,o=setTimeout(()=>i.abort(),pi);try{let s=`${Ie}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(r=>({...r,channel:e}))}finally{clearTimeout(o)}},Re=null,Ke=()=>(Re!=null||(Re=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(k().channels.map(mi)),i={};[...n].reverse().flat().forEach(r=>{i[r.app_id]=r});let o=Object.keys(E.getState().catalog).filter(r=>!i[r]);k().storage.setString(mn,JSON.stringify(i)),E.setState({catalog:i}),await Promise.all(o.map(r=>vn(r,{by_user:!1}))),o.forEach(r=>pe.delete(r));let s=Object.keys(i).filter(r=>!pe.has(r)),c=[],a={};for(let r of s.map(l=>i[l])){if(await pt(r)){V(r.app_id,{status:"installed",progress:1,version:r.version});continue}let l=O(r.app_id);if(hn(r.app_id)&&!We.has(r.app_id)&&l&&await ne(l)){V(r.app_id,{status:"installed",progress:1,version:l.version}),a[r.app_id]={app_id:r.app_id,current_version:l.version,next_version:r.version};continue}c.push(r)}return E.setState({updates:a}),c.forEach(r=>{ie[r.app_id]=0,V(r.app_id,{status:G.has(r.app_id)?"paused":"queued",progress:0,version:r.version,error:void 0}),Je(r.app_id)}),Y("catalog",s.length,"apps, outdated",c.map(r=>r.app_id),"removed",o,`${Date.now()-e}ms`),ce({type:"sync_complete",app_ids:s,removed:o}),Object.values(a).forEach(r=>ce({type:"update_available",...r})),le(),{ok:!0,app_ids:s,removed:o}}catch(n){let i=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",i),ce({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{Re=null}})()),Re),vn=async(e,{by_user:t})=>{var o,s,c,a;if(t&&pe.add(e),je.has(e))return;je.add(e),G.delete(e);let n=U.indexOf(e);n>=0&&U.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let i=(a=(c=(o=E.getState().downloads[e])==null?void 0:o.version)!=null?c:(s=O(e))==null?void 0:s.version)!=null?a:"";V(e,{status:"uninstalling",progress:0,version:i}),await sn(e),Ve(e),E.setState(r=>{let l={...r.downloads};return delete l[e],{downloads:l}}),delete ie[e],je.delete(e),He(e,null),Y("uninstalled",e,t?"(user)":"(not in list)"),ce({type:"uninstalled",app_id:e})},_n=e=>vn(e,{by_user:!0}),bn=e=>{let t=ye(e);return t?(pe.delete(e),(b==null?void 0:b.app_id)===e||U.includes(e)||(ie[e]=0,V(e,{status:G.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Je(e),le(),Y("restore",e)),!0):!1},Sn=e=>{if(G.has(e))return;if(G.add(e),Y("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=E.getState().downloads[e];U.includes(e)&&t&&V(e,{status:"paused",progress:0,version:t.version})},xn=e=>{if(!G.delete(e))return;Y("resume app",e);let t=E.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!U.includes(e)&&ye(e)&&(ie[e]=0,Je(e)),U.includes(e)&&t&&V(e,{status:"queued",progress:0,version:t.version}),le()},En=e=>{let{pause_reasons:t}=E.getState();t.includes(e)||(E.setState({pause_reasons:[...t,e]}),Y("pause",e),t.length===0&&ce({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},Pn=e=>{let{pause_reasons:t}=E.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);E.setState({pause_reasons:n}),Y("resume",e),n.length===0&&ce({type:"pause_change",paused:!1,reasons:n}),le()},gt=e=>E.getState().updates[e],Rn=async e=>{var n,i;let t=gt(e);We.add(e);try{let o=await Oe(e),s=(i=t==null?void 0:t.next_version)!=null?i:(n=ye(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(E.setState(c=>{var r;let a={...c.updates};return delete a[e],{updates:a,apply_ticks:{...c.apply_ticks,[e]:((r=c.apply_ticks[e])!=null?r:0)+1}}}),Y("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{We.delete(e)}},On=()=>Object.values(E.getState().catalog).map(e=>({...e,installed:!!O(e.app_id),removed_by_user:pe.has(e.app_id)})),ye=e=>E.getState().catalog[e],Oe=async e=>{let t=ye(e);if(!t)return;if(G.delete(e),pe.delete(e),await pt(t))return O(e);let n=O(e);if(hn(e)&&!We.has(e)&&n&&await ne(n))return n;let i=new Promise(o=>{var s;((s=me[e])!=null?s:me[e]=[]).push(o)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(ie[e]=0,Je(e,{front:!0}),b&&!b.forced?b.handle.cancel():le(e)),i};var T=require("react/jsx-runtime"),ft=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Tn=0,hi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Ai=y.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:o,web_at_top:s,splash:c,bridge:a,opaque_background:r,allow_embedded_miniapps:l,onWebLoadEnd:u})=>{var At,wt;let p=(0,y.useRef)(null),h=(0,y.useRef)(!1),A=Z(W,g=>g.instances[e]),w=A==null?void 0:A.app.app_id,I=A==null?void 0:A.app.manifest_url,P=A==null?void 0:A.context,x=A==null?void 0:A.url_params,[m,L]=(0,y.useState)(()=>w?O(w):null),[J,$]=(0,y.useState)(!1),[R,f]=(0,y.useState)(0),[M,_]=(0,y.useState)(0),[F,D]=(0,y.useState)(!1),j=(0,y.useRef)(null),re=g=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,D(!0)},g)};(0,y.useEffect)(()=>()=>{j.current&&clearTimeout(j.current)},[]),(0,y.useEffect)(()=>{if(!w||!t&&m)return;let g=!0;return $(!1),(async()=>{let v=O(w),B=v?await ne(v):!1;if(!g||(L(B?K=>!K||K.version!==v.version||K.permissions.join(",")!==v.permissions.join(",")?v:K:null),__DEV__&&Date.now()-Tn>1e4&&(Tn=Date.now(),await Ke()),!g))return;let se=await Oe(w),de=se!==void 0?se:I?await ln(w,I):O(w);if(g){if(!de){$(!0);return}L(K=>K!=null?K:de)}})(),()=>{g=!1}},[t,w,I,R]),(0,y.useEffect)(()=>pn(e,g=>p.current?(p.current.postMessage(g),!0):!1),[e]);let Ye=Z(E,g=>{let v=w?g.downloads[w]:void 0;return(v==null?void 0:v.status)==="installed"?v.version:void 0});(0,y.useEffect)(()=>{if(t||!w||!m)return;let g=O(w);if(!g||g.version===m.version)return;let v=!0;return ne(g).then(B=>{!v||!B||(H(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",m.version,"\u2192",g.version),L(g))}),()=>{v=!1}},[t,w,Ye,m==null?void 0:m.version]);let ue=Z(E,g=>{var v;return w&&(v=g.apply_ticks[w])!=null?v:0});(0,y.useEffect)(()=>{if(!ue||!w)return;let g=O(w);if(!g||g.version===(m==null?void 0:m.version))return;let v=!0;return ne(g).then(B=>{!v||!B||(H(`webview:${e}`,"c\u1EADp nh\u1EADt",m==null?void 0:m.version,"\u2192",g.version),D(!1),L(g))}),()=>{v=!1}},[ue]),(0,y.useEffect)(()=>{var B;let g=(B=k().keep_alive)==null?void 0:B.idle_close_ms;if(t||!g||g<=0)return;let v=setTimeout(()=>{Ve(e)},g);return()=>clearTimeout(v)},[t,e]),(0,y.useEffect)(()=>{o>0&&($(!1),D(!1),_(g=>g+1),f(g=>g+1))},[o]);let Te=(0,y.useRef)(t);(0,y.useEffect)(()=>{var g;Te.current!==t&&(Te.current=t,h.current&&((g=p.current)==null||g.injectJavaScript(Gt(t?"resumed":"paused"))))},[t]);let oe=`${(At=m==null?void 0:m.version)!=null?At:"none"}:${(wt=m==null?void 0:m.permissions.join(","))!=null?wt:""}:${M}`,Me=(0,y.useMemo)(()=>JSON.stringify([P!=null?P:{},x!=null?x:{}]),[P,x]),Ge=(0,y.useMemo)(()=>{var g;return tn(x!=null?x:{},(g=m==null?void 0:m.permissions)!=null?g:[])},[Me,m==null?void 0:m.permissions]),Ln=(0,y.useMemo)(()=>Zt(P!=null?P:{},Ge)+Yt()+(k().debug?Kt():""),[Ge]),ke=(0,y.useRef)(null),ht=(0,y.useRef)(null);(0,y.useEffect)(()=>{var v,B,se;if(!m)return;if(ht.current!==oe){ht.current=oe,ke.current=Me;return}if(ke.current===Me)return;let g=((B=JSON.parse((v=ke.current)!=null?v:"[]")[0])!=null?B:{}).org_id;if(ke.current=Me,g===(P==null?void 0:P.org_id)&&h.current){D(!1),re(1500),(se=p.current)==null||se.injectJavaScript(Qt(P!=null?P:{},Ge));return}D(!1),_(de=>de+1)},[Me,m,oe]),(0,y.useEffect)(()=>(t||(X(e),fe(e)),()=>{X(e),fe(e)}),[t,e,oe,o]),(0,y.useEffect)(()=>{let g=S.AppState.addEventListener("change",v=>{v==="background"&&X(e)});return()=>g.remove()},[e]);let Dn=(0,y.useCallback)(async g=>{var B,se,de,K,Qe;let v=Ht(g.nativeEvent.data);if(!v){if(w&&(a!=null&&a.onWebEvent))try{Promise.resolve(a.onWebEvent(g.nativeEvent.data,{app_id:w,instance_id:e})).catch(C=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,C)})}catch(C){console.warn("[miniapp] onWebEvent l\u1ED7i",w,C)}return}if(v.method==="log"){let{level:C,text:q}=v;H(`web:${e}`,C!=null?C:"log",q!=null?q:"");return}if(v.method==="pong"){j.current||D(!0);return}if(v.method==="touchAtTop"){s.emit(!!v.at_top);return}if(v.method==="contextApplied"){j.current&&clearTimeout(j.current),j.current=null,D(!0);return}if(v.method==="ready"){h.current=!0,D(!0);let C=(B=W.getState().instances[e])==null?void 0:B.context;C&&((se=p.current)==null||se.injectJavaScript(rt(C)));return}try{let C=await nn(v,{getHostData:()=>{var q,ee;return(ee=(q=W.getState().instances[e])==null?void 0:q.host_data)!=null?ee:{}},getPermissions:()=>{var q,ee;return w?(ee=(q=O(w))==null?void 0:q.permissions)!=null?ee:[]:[]},is_dark:i,close:we,app_id:w!=null?w:"",instance_id:e,options:a,emit:(q,ee)=>{var yt;(yt=p.current)==null||yt.injectJavaScript(Jt(q,ee))},isActive:()=>W.getState().active_key===e&&S.AppState.currentState!=="background"});v.id&&((de=p.current)==null||de.injectJavaScript(Wt(v.id,C)))}catch(C){if(!v.id)return;let q=C==null?void 0:C.code,ee=C instanceof d?C:new d(typeof q=="string"?q:"HOST_ERROR",String((K=C==null?void 0:C.message)!=null?K:C));(Qe=p.current)==null||Qe.injectJavaScript(zt(v.id,ee))}},[e,i,w,s,a]),Nn=(0,y.useCallback)(()=>{$(!1),_(g=>g+1),f(g=>g+1)},[]);return(0,T.jsxs)(S.View,{style:[S.StyleSheet.absoluteFill,r&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&z.behind],pointerEvents:t?"auto":"none",children:[m?(0,T.jsx)(Cn.default,{ref:p,source:{uri:m.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${l?at():m.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Ln,onMessage:Dn,bounces:!1,overScrollMode:"never",onLoadStart:g=>{X(e),fe(e),H(`webview:${e}`,"load start",ft(g.nativeEvent.url)),h.current=!1,D(!1)},onError:g=>{X(e),fe(e),H(`webview:${e}`,"load error",ft(g.nativeEvent.url),g.nativeEvent.description),$(!0),D(!1)},onLoadEnd:g=>{let v=g.nativeEvent.url;H(`webview:${e}`,"load end",ft(v)),w&&(u==null||u({app_id:w,instance_id:e,url:v})),re(1500)},onContentProcessDidTerminate:()=>{X(e),fe(e),h.current=!1,D(!1),_(g=>g+1)},onRenderProcessGone:()=>(X(e),fe(e),h.current=!1,D(!1),_(g=>g+1),!0),style:z.webview},oe):null,A&&(0,T.jsx)(yi,{visible:!m||!F,interactive:J,children:(0,T.jsx)(wi,{splash:c,app:A.app,is_dark:i,error:J,has_bundle:!!m,retry:Nn})})]})}),wi=y.default.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:o,retry:s})=>{let c=e,a=ze(t.app_id),r=i?"error":!o&&(a==null?void 0:a.status)==="downloading"?"downloading":"loading";return(0,T.jsx)(c,{app:t,is_dark:n,status:r,progress:r==="downloading"?a==null?void 0:a.progress:void 0,retry:s})}),yi=({visible:e,interactive:t,children:n})=>{let i=(0,y.useRef)(new S.Animated.Value(e?1:0)).current,[o,s]=(0,y.useState)(e);return(0,y.useEffect)(()=>{if(e){s(!0),i.setValue(1);return}let c=S.Animated.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:a})=>{a&&s(!1)}),()=>c.stop()},[e,i]),o?(0,T.jsx)(S.Animated.View,{style:[S.StyleSheet.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},mt=({app:e,is_dark:t,status:n,progress:i,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,T.jsxs)(S.View,{style:[z.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,T.jsx)(S.View,{style:[z.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,T.jsx)(S.Image,{source:{uri:e.icon},style:z.splash_icon_image}):(0,T.jsx)(S.Text,{style:z.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,T.jsx)(S.Text,{style:[z.splash_name,{color:s}],children:e.name}),n==="error"?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(S.Text,{style:z.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,T.jsx)(S.TouchableOpacity,{activeOpacity:.7,style:[z.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,T.jsx)(S.Text,{style:[z.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(S.ActivityIndicator,{style:z.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,T.jsxs)(S.Text,{style:z.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},kn=(e,t)=>{let n=(0,y.useRef)(t),i=(0,y.useRef)(!1);__DEV__&&!i.current&&n.current!==t&&(i.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Mi=({container:e,splash:t=mt,is_dark:n=!1,bridge:i,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:a})=>{kn("container",e),kn("splash",t);let r=e,l=Z(W,m=>m.active_key),u=(0,y.useRef)(l);l&&(u.current=l);let p=Z(W,m=>Object.keys(m.instances).join("|")),h=Z(W,m=>{var L;return m.active_key?(L=m.instances[m.active_key])==null?void 0:L.app.name:void 0}),A=(0,y.useMemo)(()=>p?p.split("|"):[],[p]),[w,I]=(0,y.useState)({}),P=(0,y.useRef)(hi()).current;(0,y.useEffect)(()=>{if(!l||!o)return;let m=S.BackHandler.addEventListener("hardwareBackPress",()=>(we(),!0));return()=>m.remove()},[l,o]);let x=(0,y.useCallback)(()=>{let m=W.getState().active_key;m&&I(L=>({...L,[m]:(L[m]||0)+1}))},[]);return A.length?(0,T.jsx)(r,{visible:!!l,title:h!=null?h:"",is_dark:n,close:we,reload:x,subscribeWebAtTop:P.subscribe,children:A.map(m=>(0,T.jsx)(Ai,{instance_key:m,is_active:l===m,is_front:(l!=null?l:u.current)===m,is_dark:n,reload_tick:w[m]||0,web_at_top:P,splash:t,bridge:i,opaque_background:s,allow_embedded_miniapps:c,onWebLoadEnd:a},m))}):null},z=S.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),In=y.default.memo(Mi);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createDocumentPickerSource,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
|
|
66
|
+
true;`},an={partner:"partner_token",chatbox:"chatbox_token"},cn=(e,t)=>{let n={...e};for(let r of Object.values(an))t.includes(r)||delete n[r];return n},pt=new Set,Oe=async(e,t)=>{if(pt.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);pt.add(e);try{return await t()}finally{pt.delete(e)}},fr=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),je=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},pn=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:i,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var T,_,b,f,L,Y,$,ve,ce;let A=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let w=Ct(t);return Oe(e,()=>kt(w,g))}case"speech.start":{if(!d)throw h();let w={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");w.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new u("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);w[S]=t[S]}return Jt(a,w,d,g)}case"speech.stop":return Kt(a);case"uploadFiles":{let{task_id:w,...S}=t!=null?t:{};if(w!==void 0&&(typeof w!="string"||!w))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ht(Ut(S),{instance_id:a,app_id:p,getContext:i,task_id:w,config:s==null?void 0:s.upload,emit:d,exclusivePick:z=>Oe("uploadFiles.pick",z)})}case"uploadFiles.cancel":zt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return qt(s==null?void 0:s.upload);case"getBiometricAvailability":return((T=s==null?void 0:s.biometrics)!=null?T:await it()).getAvailability();case"authenticateBiometric":{let w=je(t==null?void 0:t.reason,"reason").trim();if(!w||w.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Oe(e,async()=>{var v;return((v=s==null?void 0:s.biometrics)!=null?v:await it()).authenticate({reason:w,cancelButtonText:S})})}case"requestPayment":{let w=A==null?void 0:A.requestPayment;if(!w)throw h();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let z={...t,amount:S,currency:je(t==null?void 0:t.currency,"currency")};return Oe(e,()=>w(z,l))}case"printImage":{let w=A==null?void 0:A.printImage;if(!w)throw h();let S=je(t==null?void 0:t.image,"image");await Oe(e,()=>w({image:S},l));return}case"openScreen":if(!(A!=null&&A.openScreen))throw h();await A.openScreen({screen:je(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let w=String((_=t==null?void 0:t.url)!=null?_:"");if(!/^https?:\/\//i.test(w))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(w):Te.Linking.openURL(w));return}case"openLink":{let w=String((b=t==null?void 0:t.url)!=null?b:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(w)||/^(javascript|file|data|about|blob):/i.test(w))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(w):Te.Linking.openURL(w))}catch(S){throw new u("NOT_SUPPORTED",String((L=(f=S==null?void 0:S.message)!=null?f:S)!=null?L:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":($=s==null?void 0:s.showToast)==null||$.call(s,String((Y=t==null?void 0:t.message)!=null?Y:""));return;case"haptic":{let w=fr.has(t==null?void 0:t.type)?t.type:"selection";(ve=s==null?void 0:s.haptic)==null||ve.call(s,w);return}case"getSystemInfo":return{platform:Te.Platform.OS==="ios"?"ios":"android",appVersion:(ce=s==null?void 0:s.app_version)!=null?ce:"",theme:o?"dark":"light"};case"getAccessToken":{let w=n().access_token;if(!w)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}case"getToken":{let w=t==null?void 0:t.type;if(w==="access"){let v=n().access_token;if(!v)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return v}if(w!=="partner"&&w!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(w)}`);let S=an[w];if(!r().includes(S))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let z=w==="partner"?n().partner_token:n().chatbox_token;if(!z)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return z}case"getUserInfo":{let w=n().user;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return w}case"getPageInfo":{let w=n().page;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return w}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var dt=e=>`bundle:${e}`,gt=()=>`${k().file_system.document_dir}/miniapps`,mt=gt,ft=(e,t,n="index.html",r=!1,i=[])=>{let o=`${mt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:i}},ut=e=>{var t;k().storage.setString(dt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},hr=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,R=e=>{let t=k().storage.getString(dt(e));if(!t)return null;try{let{version:n,entry:r,context_update:i,permissions:o}=JSON.parse(t);return ft(e,n,r,!!i,Array.isArray(o)?o:[])}catch{return null}},se=e=>k().file_system.exists(e.entry_uri.replace("file://","")),ht=async e=>{let t=R(e.app_id);return(t==null?void 0:t.version)===e.version&&await se(t)},un=async(e,t)=>{let n=k().file_system,r=`${mt()}/${e}`,i=await n.listDir(r).catch(()=>[]);await Promise.all(i.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},dn=async e=>{var t;await((t=Ie[e])==null?void 0:t.catch(()=>{})),k().storage.setString(dt(e),""),await k().file_system.remove(`${mt()}/${e}`).catch(()=>{})},Se=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Ie={},gn=(e,t)=>{var o;let r=((o=Ie[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return Ie[e]=i,i.then(()=>{Ie[e]===i&&delete Ie[e]}),r},Ar=(e,t)=>{var i,o;let n=e.split(".").map(c=>parseInt(c,10)||0),r=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,r.length);c++){let p=((i=n[c])!=null?i:0)-((o=r[c])!=null?o:0);if(p)return p}return 0},mn=({manifest:e,zip_path:t})=>gn(e.app_id,async()=>{var o;let n=k().file_system,r=R(e.app_id);if(r&&Ar(r.version,e.version)>=0&&await se(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let i=ft(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(i.dir).catch(()=>{}),await n.mkdir(i.dir),await n.unzip(t,i.dir),ut(e),J("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),un(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),i}),At=(e,{base_url:t,onProgress:n}={})=>{let r=k().file_system,i=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new Se},a=async()=>{var g;p();let s=R(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return ut(e),R(e.app_id);p();let d=r.download({url:t?hr(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(A,l)=>{var T;let h=l>0?l:(T=e.size)!=null?T:0;h>0&&(n==null||n(Math.min(1,A/h)))}});i=d;try{let{status:A}=await d.promise;if(p(),A!==200)throw new Error(`bundle ${A}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else J("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=ft(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(l.dir).catch(()=>{}),await r.mkdir(l.dir),await r.unzip(c,l.dir),ut(e),un(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(A){throw o?new Se:A}finally{i=null,r.remove(c).catch(()=>{})}};return{promise:gn(e.app_id,a),cancel:()=>{o=!0,i==null||i.cancel()}}},ke={},wr=__DEV__?0:60*1e3,ln={},fn=(e,t)=>{var r,i;let n=R(e);return n&&Date.now()-((r=ln[t])!=null?r:0)<wr?Promise.resolve(n):((i=ke[e])!=null||(ke[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await At(c,{base_url:t}).promise;return ln[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),R(e))).finally(()=>{ke[e]=void 0})),ke[e])};var He=new Map,hn=(e,t)=>(He.set(e,t),()=>{He.get(e)===t&&He.delete(e)}),An=(e,t)=>{let n=He.get(e);return n?n(t):!1};var We=require("react"),Je=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let i=typeof r=="function"?r(t):r;t={...t,...i},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},te=(e,t,n=Object.is)=>{let r=(0,We.useRef)(null),i=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return r.current={state:o,selector:t,value:a},a};return(0,We.useSyncExternalStore)(e.subscribe,i)};var q=Je({active_key:null,instances:{}}),wn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:i={}},o)=>{var p;let c=(p=k().keep_alive)==null?void 0:p.max_webviews;q.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:i,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(A=>A!==s).sort((A,l)=>d[A].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(A=>{delete d[A]}),o?{active_key:s,instances:d}:{instances:d}})},yn=e=>wn(e,!0),Mn=e=>wn(e,!1),_e=()=>q.setState({active_key:null}),Ke=e=>{q.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var vn="catalog",yr="paused_apps",Mr="removed_apps",vr=10*1e3,Sr=2,_r=3e3,br=()=>{var e;try{return JSON.parse((e=k().storage.getString(vn))!=null?e:"{}")}catch{return{}}},P=Je({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Sn=e=>{var t;return!!((t=k().manual_update)!=null&&t.includes(e))},Qe=new Set,_n=e=>{let t=new Set,n=()=>k().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let i=JSON.parse((r=k().storage.getString(e))!=null?r:"[]");Array.isArray(i)&&i.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},X=_n(yr),fe=_n(Mr);Rt(()=>{X.load(),fe.load();let e=br(),t={};Object.keys(e).filter(n=>!fe.has(n)).forEach(n=>{let r=R(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:X.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),P.setState({catalog:e,downloads:t})});var Xe=e=>te(P,t=>e?t.downloads[e]:void 0),bn=()=>te(P,e=>e.pause_reasons.length>0),Q=(...e)=>J("queue",...e),U=[],ae={},x=null,Ye=new Set,Me={},wt=new Set,ge=e=>{wt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},xn=e=>(wt.add(e),()=>{wt.delete(e)}),En=()=>P.getState().downloads,j=(e,t)=>{let n=!!R(e),r=P.getState().downloads[e],i=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...i?{status:i}:{},has_local:n};P.setState(c=>({downloads:{...c.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?ge({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&ge({type:"progress",app_id:e,progress:o.progress,version:o.version})},Ge=(e,t)=>{var n;(n=Me[e])==null||n.forEach(r=>r(t)),delete Me[e]},xr=()=>P.getState().pause_reasons.length>0,me=e=>{var p;if(x)return;let t=e?U.indexOf(e):xr()?-1:U.findIndex(a=>!X.has(a));if(t<0||t>=U.length)return;let[n]=U.splice(t,1),r=P.getState().catalog[n];if(!r){Ge(n,R(n)),me();return}let i=Date.now();ae[n]=((p=ae[n])!=null?p:0)+1,j(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=At(r,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,j(n,{progress:s/100,version:r.version}))}});x={app_id:n,handle:c,forced:!!e},Q("start",n,r.version,e?"(forced)":""),c.promise.then(a=>{Q("installed",n,r.version,`${Date.now()-i}ms`),j(n,{status:"installed",progress:1,version:r.version}),Ge(n,a)}).catch(a=>{var d;if(a instanceof Se){if(Ye.has(n))return;Q("paused",n),ae[n]-=1,U.unshift(n),j(n,{status:X.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),ae[n]<Sr){j(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;U.includes(n)||(x==null?void 0:x.app_id)===n||(U.push(n),me((g=Me[n])!=null&&g.length?n:void 0))},_r);return}j(n,{status:"failed",progress:0,version:r.version,error:s}),Ge(n,R(n))}).finally(()=>{x=null;let a=U.find(s=>{var d;return(d=Me[s])==null?void 0:d.length});me(a)})},Ze=(e,{front:t=!1}={})=>{if((x==null?void 0:x.app_id)===e)return;let n=U.indexOf(e);if(n>=0){if(!t)return;U.splice(n,1)}t?U.unshift(e):U.push(e)},Er=async e=>{let{host_id:t,client_token:n}=k(),r=new AbortController,i=setTimeout(()=>r.abort(),vr);try{let o=`${$e}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(i)}},Le=null,et=()=>(Le!=null||(Le=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(k().channels.map(Er)),r={};[...n].reverse().flat().forEach(a=>{r[a.app_id]=a});let i=Object.keys(P.getState().catalog).filter(a=>!r[a]);k().storage.setString(vn,JSON.stringify(r)),P.setState({catalog:r}),await Promise.all(i.map(a=>Pn(a,{by_user:!1}))),i.forEach(a=>fe.delete(a));let o=Object.keys(r).filter(a=>!fe.has(a)),c=[],p={};for(let a of o.map(s=>r[s])){if(await ht(a)){j(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=R(a.app_id);if(Sn(a.app_id)&&!Qe.has(a.app_id)&&s&&await se(s)){j(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return P.setState({updates:p}),c.forEach(a=>{ae[a.app_id]=0,j(a.app_id,{status:X.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),Ze(a.app_id)}),Q("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",i,`${Date.now()-e}ms`),ge({type:"sync_complete",app_ids:o,removed:i}),Object.values(p).forEach(a=>ge({type:"update_available",...a})),me(),{ok:!0,app_ids:o,removed:i}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ge({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{Le=null}})()),Le),Pn=async(e,{by_user:t})=>{var i,o,c,p;if(t&&fe.add(e),Ye.has(e))return;Ye.add(e),X.delete(e);let n=U.indexOf(e);n>=0&&U.splice(n,1),(x==null?void 0:x.app_id)===e&&x.handle.cancel();let r=(p=(c=(i=P.getState().downloads[e])==null?void 0:i.version)!=null?c:(o=R(e))==null?void 0:o.version)!=null?p:"";j(e,{status:"uninstalling",progress:0,version:r}),await dn(e),Ke(e),P.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete ae[e],Ye.delete(e),Ge(e,null),Q("uninstalled",e,t?"(user)":"(not in list)"),ge({type:"uninstalled",app_id:e})},Rn=e=>Pn(e,{by_user:!0}),On=e=>{let t=be(e);return t?(fe.delete(e),(x==null?void 0:x.app_id)===e||U.includes(e)||(ae[e]=0,j(e,{status:X.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ze(e),me(),Q("restore",e)),!0):!1},Tn=e=>{if(X.has(e))return;if(X.add(e),Q("pause app",e),(x==null?void 0:x.app_id)===e&&!x.forced){x.handle.cancel();return}let t=P.getState().downloads[e];U.includes(e)&&t&&j(e,{status:"paused",progress:0,version:t.version})},Cn=e=>{if(!X.delete(e))return;Q("resume app",e);let t=P.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!U.includes(e)&&be(e)&&(ae[e]=0,Ze(e)),U.includes(e)&&t&&j(e,{status:"queued",progress:0,version:t.version}),me()},kn=e=>{let{pause_reasons:t}=P.getState();t.includes(e)||(P.setState({pause_reasons:[...t,e]}),Q("pause",e),t.length===0&&ge({type:"pause_change",paused:!0,reasons:[e]}),x&&!x.forced&&x.handle.cancel())},In=e=>{let{pause_reasons:t}=P.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);P.setState({pause_reasons:n}),Q("resume",e),n.length===0&&ge({type:"pause_change",paused:!1,reasons:n}),me()},yt=e=>P.getState().updates[e],Ln=async e=>{var n,r;let t=yt(e);Qe.add(e);try{let i=await De(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=be(e))==null?void 0:n.version;return!i||!o||i.version!==o?!1:(P.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),Q("updated",e,t==null?void 0:t.current_version,"\u2192",i.version),!0)}finally{Qe.delete(e)}},Dn=()=>Object.values(P.getState().catalog).map(e=>({...e,installed:!!R(e.app_id),removed_by_user:fe.has(e.app_id)})),be=e=>P.getState().catalog[e],De=async e=>{let t=be(e);if(!t)return;if(X.delete(e),fe.delete(e),await ht(t))return R(e);let n=R(e);if(Sn(e)&&!Qe.has(e)&&n&&await se(n))return n;let r=new Promise(i=>{var o;((o=Me[e])!=null?o:Me[e]=[]).push(i)});return(x==null?void 0:x.app_id)===e?x.forced=!0:(ae[e]=0,Ze(e,{front:!0}),x&&!x.forced?x.handle.cancel():me(e)),r};var O=require("react/jsx-runtime"),Mt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Nn=0,Pr=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Rr=y.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:i,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var St,_t;let g=(0,y.useRef)(null),A=(0,y.useRef)(!1),l=te(q,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,T=l==null?void 0:l.app.manifest_url,_=l==null?void 0:l.context,b=l==null?void 0:l.url_params,[f,L]=(0,y.useState)(()=>h?R(h):null),[Y,$]=(0,y.useState)(!1),[ve,ce]=(0,y.useState)(0),[w,S]=(0,y.useState)(0),[z,v]=(0,y.useState)(!1),D=(0,y.useRef)(null),ne=m=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,v(!0)},m)};(0,y.useEffect)(()=>()=>{D.current&&clearTimeout(D.current)},[]),(0,y.useEffect)(()=>{if(!h||!t&&f)return;let m=!0;return $(!1),(async()=>{let M=R(h),V=M?await se(M):!1;if(!m||(L(V?G=>!G||G.version!==M.version||G.permissions.join(",")!==M.permissions.join(",")?M:G:null),__DEV__&&Date.now()-Nn>1e4&&(Nn=Date.now(),await et()),!m))return;let le=await De(h),Ae=le!==void 0?le:T?await fn(h,T):R(h);if(m){if(!Ae){$(!0);return}L(G=>G!=null?G:Ae)}})(),()=>{m=!1}},[t,h,T,ve]),(0,y.useEffect)(()=>hn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let B=te(P,m=>{let M=h?m.downloads[h]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});(0,y.useEffect)(()=>{if(t||!h||!f)return;let m=R(h);if(!m||m.version===f.version)return;let M=!0;return se(m).then(V=>{!M||!V||(J(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),L(m))}),()=>{M=!1}},[t,h,B,f==null?void 0:f.version]);let C=te(P,m=>{var M;return h&&(M=m.apply_ticks[h])!=null?M:0});(0,y.useEffect)(()=>{if(!C||!h)return;let m=R(h);if(!m||m.version===(f==null?void 0:f.version))return;let M=!0;return se(m).then(V=>{!M||!V||(J(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),v(!1),L(m))}),()=>{M=!1}},[C]),(0,y.useEffect)(()=>{var V;let m=(V=k().keep_alive)==null?void 0:V.idle_close_ms;if(t||!m||m<=0)return;let M=setTimeout(()=>{Ke(e)},m);return()=>clearTimeout(M)},[t,e]),(0,y.useEffect)(()=>{i>0&&($(!1),v(!1),S(m=>m+1),ce(m=>m+1))},[i]);let H=(0,y.useRef)(t);(0,y.useEffect)(()=>{var m;H.current!==t&&(H.current=t,A.current&&((m=g.current)==null||m.injectJavaScript(nn(t?"resumed":"paused"))))},[t]);let pe=`${(St=f==null?void 0:f.version)!=null?St:"none"}:${(_t=f==null?void 0:f.permissions.join(","))!=null?_t:""}:${w}`,he=(0,y.useMemo)(()=>JSON.stringify([_!=null?_:{},b!=null?b:{}]),[_,b]),re=(0,y.useMemo)(()=>{var m;return cn(b!=null?b:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[he,f==null?void 0:f.permissions]),tt=(0,y.useMemo)(()=>sn(_!=null?_:{},re)+en()+(E.Platform.OS==="android"?tn():"")+(k().debug?Zt():""),[re]),ie=(0,y.useRef)(null),Ne=(0,y.useRef)(null);(0,y.useEffect)(()=>{var M,V,le;if(!f)return;if(Ne.current!==pe){Ne.current=pe,ie.current=he;return}if(ie.current===he)return;let m=((V=JSON.parse((M=ie.current)!=null?M:"[]")[0])!=null?V:{}).org_id;if(ie.current=he,m===(_==null?void 0:_.org_id)&&A.current){v(!1),ne(1500),(le=g.current)==null||le.injectJavaScript(rn(_!=null?_:{},re));return}v(!1),S(Ae=>Ae+1)},[he,f,pe]),(0,y.useEffect)(()=>(t||(ee(e),ye(e)),()=>{ee(e),ye(e)}),[t,e,pe,i]),(0,y.useEffect)(()=>{let m=E.AppState.addEventListener("change",M=>{M==="background"&&ee(e)});return()=>m.remove()},[e]);let Ue=(0,y.useCallback)(async m=>{var V,le,Ae,G,nt;let M=Yt(m.nativeEvent.data);if(!M){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(I=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,I)})}catch(I){console.warn("[miniapp] onWebEvent l\u1ED7i",h,I)}return}if(M.method==="log"){let{level:I,text:F}=M;J(`web:${e}`,I!=null?I:"log",F!=null?F:"");return}if(M.method==="pong"){D.current||v(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){D.current&&clearTimeout(D.current),D.current=null,v(!0);return}if(M.method==="ready"){A.current=!0,v(!0);let I=(V=q.getState().instances[e])==null?void 0:V.context;I&&((le=g.current)==null||le.injectJavaScript(lt(I)));return}try{let I=await pn(M,{getHostData:()=>{var F,W;return(W=(F=q.getState().instances[e])==null?void 0:F.host_data)!=null?W:{}},getPermissions:()=>{var F,W;return h?(W=(F=R(h))==null?void 0:F.permissions)!=null?W:[]:[]},getContext:()=>{var F,W;return(W=(F=q.getState().instances[e])==null?void 0:F.context)!=null?W:{}},is_dark:r,close:_e,app_id:h!=null?h:"",instance_id:e,options:p,emit:(F,W)=>{var bt;(bt=g.current)==null||bt.injectJavaScript(Xt(F,W))},isActive:()=>q.getState().active_key===e&&E.AppState.currentState!=="background"});M.id&&((Ae=g.current)==null||Ae.injectJavaScript(Gt(M.id,I)))}catch(I){if(!M.id)return;let F=I==null?void 0:I.code,W=I instanceof u?I:new u(typeof F=="string"?F:"HOST_ERROR",String((G=I==null?void 0:I.message)!=null?G:I));(nt=g.current)==null||nt.injectJavaScript(Qt(M.id,W))}},[e,r,h,o,p]),Bn=(0,y.useCallback)(()=>{$(!1),S(m=>m+1),ce(m=>m+1)},[]);return(0,O.jsxs)(E.View,{style:[E.StyleSheet.absoluteFill,a&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&K.behind],pointerEvents:t?"auto":"none",children:[f?(0,O.jsx)(Fn.default,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?gt():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:tt,onMessage:Ue,bounces:!1,overScrollMode:"never",onLoadStart:m=>{ee(e),ye(e),J(`webview:${e}`,"load start",Mt(m.nativeEvent.url)),A.current=!1,v(!1)},onError:m=>{ee(e),ye(e),J(`webview:${e}`,"load error",Mt(m.nativeEvent.url),m.nativeEvent.description),$(!0),v(!1)},onLoadEnd:m=>{let M=m.nativeEvent.url;J(`webview:${e}`,"load end",Mt(M)),h&&(d==null||d({app_id:h,instance_id:e,url:M})),ne(1500)},onContentProcessDidTerminate:()=>{ee(e),ye(e),A.current=!1,v(!1),S(m=>m+1)},onRenderProcessGone:()=>(ee(e),ye(e),A.current=!1,v(!1),S(m=>m+1),!0),style:K.webview},pe):null,l&&(0,O.jsx)(Tr,{visible:!f||!z,interactive:Y,children:(0,O.jsx)(Or,{splash:c,app:l.app,is_dark:r,error:Y,has_bundle:!!f,retry:Bn})})]})}),Or=y.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:i,retry:o})=>{let c=e,p=Xe(t.app_id),a=r?"error":!i&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return(0,O.jsx)(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Tr=({visible:e,interactive:t,children:n})=>{let r=(0,y.useRef)(new E.Animated.Value(e?1:0)).current,[i,o]=(0,y.useState)(e);return(0,y.useEffect)(()=>{if(e){o(!0),r.setValue(1);return}let c=E.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,r]),i?(0,O.jsx)(E.Animated.View,{style:[E.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},vt=({app:e,is_dark:t,status:n,progress:r,retry:i})=>{let o=t?"#FAFAFA":"#18181B";return(0,O.jsxs)(E.View,{style:[K.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,O.jsx)(E.View,{style:[K.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,O.jsx)(E.Image,{source:{uri:e.icon},style:K.splash_icon_image}):(0,O.jsx)(E.Text,{style:K.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,O.jsx)(E.Text,{style:[K.splash_name,{color:o}],children:e.name}),n==="error"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.Text,{style:K.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,O.jsx)(E.TouchableOpacity,{activeOpacity:.7,style:[K.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:i,children:(0,O.jsx)(E.Text,{style:[K.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(E.ActivityIndicator,{style:K.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,O.jsxs)(E.Text,{style:K.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},Un=(e,t)=>{let n=(0,y.useRef)(t),r=(0,y.useRef)(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Cr=({container:e,splash:t=vt,is_dark:n=!1,bridge:r,close_on_back:i=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{Un("container",e),Un("splash",t);let a=e,s=te(q,f=>f.active_key),d=(0,y.useRef)(s);s&&(d.current=s);let g=te(q,f=>Object.keys(f.instances).join("|")),A=te(q,f=>{var L;return f.active_key?(L=f.instances[f.active_key])==null?void 0:L.app.name:void 0}),l=(0,y.useMemo)(()=>g?g.split("|"):[],[g]),[h,T]=(0,y.useState)({}),_=(0,y.useRef)(Pr()).current;(0,y.useEffect)(()=>{if(!s||!i)return;let f=E.BackHandler.addEventListener("hardwareBackPress",()=>(_e(),!0));return()=>f.remove()},[s,i]);let b=(0,y.useCallback)(()=>{let f=q.getState().active_key;f&&T(L=>({...L,[f]:(L[f]||0)+1}))},[]);return l.length?(0,O.jsx)(a,{visible:!!s,title:A!=null?A:"",is_dark:n,close:_e,reload:b,subscribeWebAtTop:_.subscribe,children:l.map(f=>(0,O.jsx)(Rr,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:_,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},K=E.StyleSheet.create({webview:{flex:1,backgroundColor:"transparent"},behind:{zIndex:-1},splash:{flex:1,alignItems:"center",justifyContent:"center",gap:12},splash_icon:{width:72,height:72,borderRadius:20,alignItems:"center",justifyContent:"center",overflow:"hidden"},splash_icon_image:{width:72,height:72},splash_letter:{fontSize:28,fontWeight:"700",color:"#1D4ED8"},splash_name:{fontSize:16,fontWeight:"600"},splash_hint:{color:"#71717A"},splash_spinner:{marginTop:8},retry_button:{marginTop:4,paddingHorizontal:20,paddingVertical:10,borderRadius:999},retry_text:{fontWeight:"600"}}),$n=y.default.memo(Cr);0&&(module.exports={DefaultMiniAppSplash,MINIAPP_PLATFORM_URL,MiniAppHost,MiniAppHostError,closeMiniApp,configureMiniApp,createMmkvStorage,createReactNativeBiometrics,createRnfsFileSystem,ensureMiniApp,getLocalMiniApp,getMiniAppCatalog,getMiniAppCatalogEntry,getMiniAppStatuses,getMiniAppUpdate,installBundledMiniApp,onMiniAppEvent,openMiniApp,pauseMiniApp,pauseMiniAppDownloads,preloadMiniApp,releaseSpeechFor,restoreMiniApp,resumeMiniApp,resumeMiniAppDownloads,sendEventToWeb,syncMiniAppCatalog,uninstallMiniApp,updateMiniApp,uploadToUrl,useMiniAppDownload,useMiniAppDownloadsPaused});
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de=e,vt.forEach(t=>t())},R=()=>{if(!de)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return de},_t=e=>{vt.add(e),de&&e()},j=(...e)=>{de!=null&&de.debug&&console.log("[miniapp]",...e)};var _n=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(i=>i.map(s=>s.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,i)=>{await t(n,i)},download:({url:n,to_file:i,onProgress:s})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:i,progressInterval:250,begin:()=>{},progress:({bytesWritten:a,contentLength:r})=>s==null?void 0:s(a,r)});return{promise:c.then(({statusCode:a})=>({status:a})),cancel:()=>e.stopDownload(o)}}}),bn=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import mt,{useCallback as gt,useEffect as q,useMemo as We,useRef as G,useState as he}from"react";import{AppState as gn,ActivityIndicator as wi,Animated as ut,BackHandler as yi,Image as Mi,StyleSheet as ht,Text as Re,TouchableOpacity as vi,View as ft}from"react-native";import _i from"react-native-webview";import{Linking as Bt,Platform as Vn}from"react-native";var bt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Ce,Ge=()=>(Ce||(Ce=import("react-native-biometrics").then(({default:e})=>bt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Ce=void 0,new d("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Ce);import{PermissionsAndroid as ge,Platform as Sn}from"react-native";var St=e=>{var n,i,s;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new d("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 d("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,a]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let r=t[o];if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)||r<c||r>a))throw new d("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${a} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(i=t.timeout)!=null?i:15e3,maximumAge:(s=t.maximumAge)!=null?s:0}},xt=(e,t=()=>!0)=>new Promise((n,i)=>{let s=!1,o=(r,l)=>{s||(s=!0,clearTimeout(c),r?i(r):n(l))},c=setTimeout(()=>o(new d("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),a=()=>s?!1:t()?!0:(o(new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!a())return;let r;try{r=(await import("@react-native-community/geolocation")).default}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(a()){if(Sn.OS==="android"){let l=ge.PERMISSIONS.ACCESS_FINE_LOCATION,u=ge.PERMISSIONS.ACCESS_COARSE_LOCATION,p=await ge.check(l);if(!a())return;let h=p||await ge.check(u);if(!a())return;if(!p&&!h){let A=await ge.requestMultiple([l,u]);if(!a())return;if(A[l]!==ge.RESULTS.GRANTED&&A[u]!==ge.RESULTS.GRANTED)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}a()&&r.getCurrentPosition(l=>{a()&&o(void 0,l)},l=>{var p;if(!a())return;let u=(p={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[l.code])!=null?p:"LOCATION_ERROR";o(new d(u,l.message))},e)}})().catch(r=>o(r))});import{Platform as xn}from"react-native";var Qe=20,Et=20,Ot=/^[a-z][a-z0-9_-]{0,31}$/,En=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,Pn=["low","medium","high"],se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),I=e=>new d("INVALID_PARAMS",e),Me=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Pt=(e,t)=>{if(e===void 0)return{};if(!se(e)||Object.keys(e).length>Et||Object.values(e).some(n=>typeof n!="string"))throw I(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Et} key)`);return e},Tt=e=>{var n,i,s,o;if(e!==void 0&&!se(e))throw I("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Ot.test(t.source)))throw I("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!En.test(c))))throw I("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Me(t.max_count,1,Qe))throw I(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${Qe}`);if(t.max_size!==void 0&&!Me(t.max_size,1,Number.MAX_SAFE_INTEGER))throw I("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Me(t.concurrency,1,5))throw I("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((i=t.accept)!=null?i:[]).map(c=>c.toLowerCase()),max_count:(s=t.max_count)!=null?s:1,max_size:t.max_size,process:Rn(t.process),target:On(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},Rn=e=>{if(e===void 0)return{};if(!se(e))throw I("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!se(n))throw I("process.image ph\u1EA3i l\xE0 object");for(let i of["max_width","max_height"])if(n[i]!==void 0&&!Me(n[i],1,1e4))throw I(`process.image.${i} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw I("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!se(n))throw I("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Me(n.max_duration,1,3600))throw I("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!Pn.includes(n.quality))throw I("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},On=e=>{var n,i,s,o;if(e===void 0)return{target:"host",params:{}};if(!se(e))throw I("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Ot.test(t))throw I("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!se(e.params))throw I("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(i=e.params)!=null?i:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw I("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw I(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Pt(e.headers,"upload.headers"),form_data:Pt(e.form_data,"upload.form_data"),field_name:(s=e.field_name)!=null?s:"file",url_field:(o=e.url_field)!=null?o:"url"}},kt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Tn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),i=kt(e.name);return t.some(s=>s==="*/*"?!0:s.startsWith(".")?s===i:s.endsWith("/*")?n.startsWith(s.slice(0,-1)):n===s)},kn=e=>{let t=e.length>0&&e.every(i=>i.startsWith("image/")),n=e.length>0&&e.every(i=>i.startsWith("video/"));return t?"image":n?"video":"mixed"},ye,Cn=()=>(ye!=null||(ye=import("react-native-image-picker").catch(e=>{throw ye=void 0,new d("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),ye),Rt=e=>async({accept:t,max_count:n,process:i})=>{var r,l,u,p,h,A,w,T,x;let s=await Cn(),o=kn(t),c={mediaType:o==="image"?"photo":o,maxWidth:(r=i.image)==null?void 0:r.max_width,maxHeight:(l=i.image)==null?void 0:l.max_height,quality:(p=(u=i.image)==null?void 0:u.quality)!=null?p:.8,videoQuality:(A=(h=i.video)==null?void 0:h.quality)!=null?A:"medium",durationLimit:(w=i.video)==null?void 0:w.max_duration,assetRepresentationMode:"compatible"},a=e==="camera"?await s.launchCamera({...c,saveToPhotos:!1}):await s.launchImageLibrary({...c,selectionLimit:n});if(a.didCancel)return[];if(a.errorCode){let b=a.errorCode==="permission"?"PERMISSION_DENIED":a.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new d(b,(T=a.errorMessage)!=null?T:a.errorCode)}return((x=a.assets)!=null?x:[]).filter(b=>b.uri).map((b,m)=>{var k,z,U;return{uri:b.uri,name:(k=b.fileName)!=null?k:`file_${m+1}`,mime_type:(z=b.type)!=null?z:"application/octet-stream",size:b.fileSize,width:b.width,height:b.height,duration:b.duration,processed:!((U=b.type)!=null&&U.startsWith("video/"))||xn.OS==="ios"}})},In={"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"},Ln={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Dn=e=>async({accept:t,max_count:n})=>{var o,c,a,r;let i=t.map(l=>{var u;return(u=In[l])!=null?u:Ln[l]}),s=!t.length||i.some(l=>!l||!e.types[l])?e.types.allFiles:[...new Set(i)].flatMap(l=>e.types[l]);try{return(await e.pick({type:s,allowMultiSelection:n>1,mode:"import"})).filter(u=>u.uri&&!u.error).map((u,p)=>{var h,A,w;return{uri:u.uri,name:(h=u.name)!=null?h:`file_${p+1}`,mime_type:(A=u.type)!=null?A:"application/octet-stream",size:(w=u.size)!=null?w:void 0}})}catch(l){let u=l==null?void 0:l.code;if(u===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw u===((r=(a=e.errorCodes)==null?void 0:a.IN_PROGRESS)!=null?r:"ASYNC_OP_IN_PROGRESS")?new d("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):l}},Nn={library:Rt("library"),camera:Rt("camera")},Un=(e,t)=>t.split(".").reduce((n,i)=>se(n)?n[i]:void 0,e),Ct=({file:e,target:t,onProgress:n,signal:i})=>new Promise((s,o)=>{if(t.target!=="url"||!("url"in t)){o(new d("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(i.aborted){o(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let a=new XMLHttpRequest,r=new FormData;Object.entries(c.form_data).forEach(([p,h])=>r.append(p,h)),r.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let l=()=>a.abort();i.addEventListener("abort",l);let u=p=>{i.removeEventListener("abort",l),p()};a.open("POST",c.url),Object.entries(c.headers).forEach(([p,h])=>a.setRequestHeader(p,h)),a.upload.onprogress=p=>n(p.loaded,p.total||e.size||0),a.onload=()=>u(()=>{let p=a.responseText;try{p=JSON.parse(a.responseText)}catch{}if(a.status<200||a.status>=300){o(new d("UPLOAD_FAILED",`HTTP ${a.status}`));return}let h=Un(p,c.url_field);if(typeof h!="string"||!h){o(new d("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}s({url:h,response:p})}),a.onerror=()=>u(()=>o(new d("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),a.onabort=()=>u(()=>o(new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),a.send(r)}),It=e=>{var i,s;let t={...Nn};for(let[o,c]of Object.entries((i=e==null?void 0:e.sources)!=null?i:{}))c?t[o]=c:delete t[o];let n={url:Ct};for(let[o,c]of Object.entries((s=e==null?void 0:e.targets)!=null?s:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Lt=e=>{let{sources:t,targets:n}=It(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:Qe}},Le=new Map,Dt=(e,t)=>`${e}:${t}`,Fn=0,Nt=(e,t)=>{var n;typeof t=="string"&&((n=Le.get(Dt(e,t)))==null||n.abort())},fe=e=>{for(let[t,n]of Le)t.startsWith(`${e}:`)&&n.abort()},Ie=()=>new d("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),$n=(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)}},Ut=async(e,t)=>{var r;let{sources:n,targets:i}=It(t.config),s=n[e.source];if(!s)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=i[e.target.target];if(!o)throw new d("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,a=Dt(t.instance_id,(r=t.task_id)!=null?r:`auto-${++Fn}`);Le.set(a,c);try{return await Bn(e,t,s,o,c.signal)}finally{Le.delete(a)}},Bn=async(e,{task_id:t,config:n,emit:i,exclusivePick:s=r=>r()},o,c,a)=>{var z,U;let r=(await s(()=>o({accept:e.accept,max_count:e.max_count,process:e.process}))).slice(0,e.max_count);if(a.aborted)throw Ie();if(!r.length)throw new d("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],u=r.filter(E=>Tn(E,e.accept)?!0:(l.push({name:E.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${E.mime_type||kt(E.name)}`}),!1)),p=u.map(()=>0),h=u.map(E=>{var f;return(f=E.size)!=null?f:0}),A=0,w=0,T=(E=!1)=>{if(!i||!t)return;let f=Date.now();if(!E&&f-w<200)return;w=f;let y=h.reduce((D,C)=>D+C,0),v=p.reduce((D,C)=>D+C,0);i("upload.progress",{task_id:t,loaded:v,total:y,percent:y?Math.min(100,Math.round(v/y*100)):0,done_count:A,count:u.length})},x=[],b=0,m=async()=>{var E,f;for(;b<u.length;){let y=b++,v=u[y];try{if(a.aborted)throw Ie();let D=v.mime_type.startsWith("image/")?"image":v.mime_type.startsWith("video/")?"video":void 0,C=D&&!v.processed?(E=n==null?void 0:n.processors)==null?void 0:E[D]:void 0;if(C&&(v=await C(v,e.process),h[y]=(f=v.size)!=null?f:h[y],a.aborted))throw Ie();if(e.max_size&&v.size&&v.size>e.max_size)throw new d("FILE_TOO_LARGE",`File ${v.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let V=(Te,re)=>{p[y]=Te,re&&(h[y]=re),T()},ie=await c({file:v,target:e.target,onProgress:V,signal:a});if(typeof(ie==null?void 0:ie.url)!="string"||!ie.url)throw new d("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:ze,...pe}=ie;x[y]={url:ze,name:v.name,mime_type:v.mime_type,size:v.size,width:v.width,height:v.height,duration:v.duration,...Object.keys(pe).length?{response:"response"in pe?pe.response:pe}:{}},p[y]=h[y]}catch(D){l.push($n(u[y].name,D))}finally{A++,T(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,u.length)},m)),a.aborted)throw Ie();let k=x.filter(E=>!!E);if(!k.length){let E=l[0];throw new d((z=E==null?void 0:E.code)!=null?z:"UPLOAD_FAILED",(U=E==null?void 0:E.message)!=null?U:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:k,failed:l}};import{Platform as qn}from"react-native";var Z,Xe=e=>{var t;if(Z===e&&(Z=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&qn.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Ft=async(e,t,n,i=()=>!0)=>{var o,c,a,r,l;if(Z)throw new d("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!i())throw new d("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let s={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};Z=s;try{let u;try{u=await import("expo-speech-recognition")}catch{throw new d("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let p=u.ExpoSpeechRecognitionModule;if(s.native=p,s.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let h=await p.requestPermissionsAsync();if(s.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!h.granted)throw new d("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await p.getStateAsync()!=="inactive")throw new d("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(s.cancelled||!i())throw new d("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");s.subscriptions.push(p.addListener("result",A=>{var w,T;Z!==s||s.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(T=(w=A.results[0])==null?void 0:w.transcript)!=null?T:""})}),p.addListener("error",A=>{Z===s&&!s.cancelled&&n("speech.error",{...A,code:A.error})}),p.addListener("end",()=>{Z===s&&(Xe(s),n("speech.end"))})),s.started=!0,p.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(a=t.interimResults)!=null?a:!0,addsPunctuation:(r=t.addsPunctuation)!=null?r:!0,requiresOnDeviceRecognition:(l=t.requiresOnDeviceRecognition)!=null?l:!1,iosCategory:{category:u.AVAudioSessionCategory.playAndRecord,categoryOptions:[u.AVAudioSessionCategoryOptions.defaultToSpeaker,u.AVAudioSessionCategoryOptions.allowBluetooth],mode:u.AVAudioSessionMode.measurement}})}catch(u){throw Xe(s),u}},$t=e=>{let t=Z;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ee=e=>{let t=Z;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{Xe(t)}};var Ne=1,d=class extends Error{constructor(n,i){super(i);this.code=n}},qt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Ne&&typeof t.method=="string"?t:null}catch{return null}},_e=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Vt=(e,t)=>_e({id:e,result:t}),jt=(e,t)=>_e({id:e,error:{code:t.code,message:t.message}}),Ht=(e,t)=>_e({event:e,data:t}),et=e=>_e({event:"context",data:e});var Wt=()=>`(function () {
|
|
1
|
+
var et="https://retion-miniapp-platform.vercel.app",he=null,xt=new Set,Pn=e=>{he=e,xt.forEach(t=>t())},O=()=>{if(!he)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return he},Et=e=>{xt.add(e),he&&e()},W=(...e)=>{he!=null&&he.debug&&console.log("[miniapp]",...e)};var Rn=(e,t)=>({document_dir:e.DocumentDirectoryPath,cache_dir:e.CachesDirectoryPath,exists:n=>e.exists(n),mkdir:n=>e.mkdir(n),remove:n=>e.unlink(n).catch(()=>{}),listDir:n=>e.readDir(n).then(r=>r.map(i=>i.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:i})=>{let{jobId:o,promise:c}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:p,contentLength:a})=>i==null?void 0:i(p,a)});return{promise:c.then(({statusCode:p})=>({status:p})),cancel:()=>e.stopDownload(o)}}}),On=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});import Mt,{useCallback as wt,useEffect as q,useMemo as Qe,useRef as X,useState as Me}from"react";import{AppState as vn,ActivityIndicator as Or,Animated as ht,BackHandler as Tr,Image as Cr,Platform as kr,StyleSheet as vt,Text as Le,TouchableOpacity as Ir,View as yt}from"react-native";import Lr from"react-native-webview";import{Linking as Jt,Platform as Zn}from"react-native";var Pt=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),Fe,tt=()=>(Fe||(Fe=import("react-native-biometrics").then(({default:e})=>Pt(new e({allowDeviceCredentials:!1}))).catch(e=>{throw Fe=void 0,new u("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),Fe);import{PermissionsAndroid as Ae,Platform as Tn}from"react-native";var Rt=e=>{var n,r,i;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new u("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new u("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[o,c,p]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let a=t[o];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<c||a>p))throw new u("INVALID_PARAMS",`${o} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${c}\u2013${p} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(i=t.maximumAge)!=null?i:0}},Ot=(e,t=()=>!0)=>new Promise((n,r)=>{let i=!1,o=(a,s)=>{i||(i=!0,clearTimeout(c),a?r(a):n(s))},c=setTimeout(()=>o(new u("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),p=()=>i?!1:t()?!0:(o(new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!p())return;let a;try{a=(await import("@react-native-community/geolocation")).default}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(p()){if(Tn.OS==="android"){let s=Ae.PERMISSIONS.ACCESS_FINE_LOCATION,d=Ae.PERMISSIONS.ACCESS_COARSE_LOCATION,g=await Ae.check(s);if(!p())return;let A=g||await Ae.check(d);if(!p())return;if(!g&&!A){let l=await Ae.requestMultiple([s,d]);if(!p())return;if(l[s]!==Ae.RESULTS.GRANTED&&l[d]!==Ae.RESULTS.GRANTED)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}p()&&a.getCurrentPosition(s=>{p()&&o(void 0,s)},s=>{var g;if(!p())return;let d=(g={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[s.code])!=null?g:"LOCATION_ERROR";o(new u(d,s.message))},e)}})().catch(a=>o(a))});import{Platform as It}from"react-native";var nt=20,Tt=20,Lt=/^[a-z][a-z0-9_-]{0,31}$/,Cn=/^(\.[\w-]{1,16}|[\w.+-]+\/(\*|[\w.+-]+))$/,kn=["low","medium","high"],le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),I=e=>new u("INVALID_PARAMS",e),Ee=(e,t,n)=>typeof e=="number"&&Number.isInteger(e)&&e>=t&&e<=n,Ct=(e,t)=>{if(e===void 0)return{};if(!le(e)||Object.keys(e).length>Tt||Object.values(e).some(n=>typeof n!="string"))throw I(`${t} ph\u1EA3i l\xE0 object chu\u1ED7i (t\u1ED1i \u0111a ${Tt} key)`);return e},Dt=e=>{var n,r,i,o;if(e!==void 0&&!le(e))throw I("Tu\u1EF3 ch\u1ECDn upload ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.source!==void 0&&(typeof t.source!="string"||!Lt.test(t.source)))throw I("source ph\u1EA3i l\xE0 t\xEAn ngu\u1ED3n, vd library | camera | document");if(t.accept!==void 0&&(!Array.isArray(t.accept)||t.accept.length>50||t.accept.some(c=>typeof c!="string"||!Cn.test(c))))throw I("accept ph\u1EA3i l\xE0 m\u1EA3ng mime (image/*, application/pdf) ho\u1EB7c \u0111u\xF4i (.docx)");if(t.max_count!==void 0&&!Ee(t.max_count,1,nt))throw I(`max_count ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u2013${nt}`);if(t.max_size!==void 0&&!Ee(t.max_size,1,Number.MAX_SAFE_INTEGER))throw I("max_size ph\u1EA3i l\xE0 s\u1ED1 byte > 0");if(t.concurrency!==void 0&&!Ee(t.concurrency,1,5))throw I("concurrency ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u20135");return{source:(n=t.source)!=null?n:"library",accept:((r=t.accept)!=null?r:[]).map(c=>c.toLowerCase()),max_count:(i=t.max_count)!=null?i:1,max_size:t.max_size,process:In(t.process),target:Ln(t.upload),concurrency:(o=t.concurrency)!=null?o:3}},In=e=>{if(e===void 0)return{};if(!le(e))throw I("process ph\u1EA3i l\xE0 object");let t={};if(e.image!==void 0){let n=e.image;if(!le(n))throw I("process.image ph\u1EA3i l\xE0 object");for(let r of["max_width","max_height"])if(n[r]!==void 0&&!Ee(n[r],1,1e4))throw I(`process.image.${r} ph\u1EA3i l\xE0 s\u1ED1 nguy\xEAn 1\u201310000`);if(n.quality!==void 0&&(typeof n.quality!="number"||n.quality<=0||n.quality>1))throw I("process.image.quality ph\u1EA3i trong kho\u1EA3ng (0, 1]");t.image={max_width:n.max_width,max_height:n.max_height,quality:n.quality}}if(e.video!==void 0){let n=e.video;if(!le(n))throw I("process.video ph\u1EA3i l\xE0 object");if(n.max_duration!==void 0&&!Ee(n.max_duration,1,3600))throw I("process.video.max_duration ph\u1EA3i l\xE0 s\u1ED1 gi\xE2y 1\u20133600");if(n.quality!==void 0&&!kn.includes(n.quality))throw I("process.video.quality ph\u1EA3i l\xE0 low | medium | high");t.video={max_duration:n.max_duration,quality:n.quality}}return t},Ln=e=>{var n,r,i,o;if(e===void 0)return{target:"host",params:{}};if(!le(e))throw I("upload ph\u1EA3i l\xE0 object");let t=(n=e.target)!=null?n:"host";if(typeof t!="string"||!Lt.test(t))throw I("upload.target ph\u1EA3i l\xE0 t\xEAn \u0111\xEDch, vd host | url");if(t!=="url"){if(e.params!==void 0&&!le(e.params))throw I("upload.params ph\u1EA3i l\xE0 object");return{target:t,params:(r=e.params)!=null?r:{}}}if(typeof e.url!="string"||!/^https:\/\//i.test(e.url))throw I("upload.url ph\u1EA3i l\xE0 https");for(let c of["field_name","url_field"])if(e[c]!==void 0&&(typeof e[c]!="string"||!e[c]))throw I(`upload.${c} ph\u1EA3i l\xE0 chu\u1ED7i`);return{target:"url",url:e.url,headers:Ct(e.headers,"upload.headers"),form_data:Ct(e.form_data,"upload.form_data"),field_name:(i=e.field_name)!=null?i:"file",url_field:(o=e.url_field)!=null?o:"url"}},Nt=e=>{let t=e.lastIndexOf(".");return t>0?e.slice(t).toLowerCase():""},Dn=(e,t)=>{if(!t.length)return!0;let n=e.mime_type.toLowerCase(),r=Nt(e.name);return t.some(i=>i==="*/*"?!0:i.startsWith(".")?i===r:i.endsWith("/*")?n.startsWith(i.slice(0,-1)):n===i)},Nn=e=>{let t=e.length>0&&e.every(r=>r.startsWith("image/")),n=e.length>0&&e.every(r=>r.startsWith("video/"));return t?"image":n?"video":"mixed"},_e,Un=()=>(_e!=null||(_e=import("react-native-image-picker").catch(e=>{throw _e=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn \u1EA3nh trong b\u1EA3n native: ${e instanceof Error?e.message:String(e)}`)})),_e),kt=e=>async({accept:t,max_count:n,process:r})=>{var a,s,d,g,A,l,h,E,S;let i=await Un(),o=Nn(t),c={mediaType:o==="image"?"photo":o,maxWidth:(a=r.image)==null?void 0:a.max_width,maxHeight:(s=r.image)==null?void 0:s.max_height,quality:(g=(d=r.image)==null?void 0:d.quality)!=null?g:.8,videoQuality:(l=(A=r.video)==null?void 0:A.quality)!=null?l:"medium",durationLimit:(h=r.video)==null?void 0:h.max_duration,assetRepresentationMode:"compatible"},p=e==="camera"?await i.launchCamera({...c,saveToPhotos:!1}):await i.launchImageLibrary({...c,selectionLimit:n});if(p.didCancel)return[];if(p.errorCode){let _=p.errorCode==="permission"?"PERMISSION_DENIED":p.errorCode==="camera_unavailable"?"NOT_SUPPORTED":"HOST_ERROR";throw new u(_,(E=p.errorMessage)!=null?E:p.errorCode)}return((S=p.assets)!=null?S:[]).filter(_=>_.uri).map((_,f)=>{var C,K,U;return{uri:_.uri,name:(C=_.fileName)!=null?C:`file_${f+1}`,mime_type:(K=_.type)!=null?K:"application/octet-stream",size:_.fileSize,width:_.width,height:_.height,duration:_.duration,processed:!((U=_.type)!=null&&U.startsWith("video/"))||It.OS==="ios"}})},Fn={"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"},$n={".pdf":"pdf",".txt":"plainText",".csv":"csv",".json":"json",".zip":"zip",".doc":"doc",".docx":"docx",".xls":"xls",".xlsx":"xlsx",".ppt":"ppt",".pptx":"pptx"},Bn=e=>async({accept:t,max_count:n})=>{var o,c,p,a;let r=t.map(s=>{var d;return(d=Fn[s])!=null?d:$n[s]}),i=!t.length||r.some(s=>!s||!e.types[s])?e.types.allFiles:[...new Set(r)].flatMap(s=>e.types[s]);try{let d=(await e.pick({type:i,allowMultiSelection:n>1,mode:"import"})).filter(l=>l.uri&&!l.error).map((l,h)=>{var E,S,_;return{uri:l.uri,name:(E=l.name)!=null?E:`file_${h+1}`,mime_type:(S=l.type)!=null?S:"application/octet-stream",size:(_=l.size)!=null?_:void 0}});if(It.OS!=="android"||!e.keepLocalCopy||!d.some(l=>l.uri.startsWith("content://")))return d;let g=await e.keepLocalCopy({files:d.map(l=>({uri:l.uri,fileName:l.name})),destination:"cachesDirectory"}),A=new Map(g.map(l=>[l.sourceUri,l.status==="success"?l.localUri:void 0]));return d.map(l=>{var h;return{...l,uri:(h=A.get(l.uri))!=null?h:l.uri}})}catch(s){let d=s==null?void 0:s.code;if(d===((c=(o=e.errorCodes)==null?void 0:o.OPERATION_CANCELED)!=null?c:"OPERATION_CANCELED"))return[];throw d===((a=(p=e.errorCodes)==null?void 0:p.IN_PROGRESS)!=null?a:"ASYNC_OP_IN_PROGRESS")?new u("BUSY","\u0110ang m\u1EDF tr\xECnh ch\u1ECDn file kh\xE1c"):s}},be,Vn=async e=>(be!=null||(be=import("@react-native-documents/picker").then(t=>Bn(t)).catch(t=>{throw be=void 0,new u("NOT_SUPPORTED",`Ch\u01B0a c\xF3 module ch\u1ECDn file trong b\u1EA3n native: ${t instanceof Error?t.message:String(t)}`)})),(await be)(e)),qn={library:kt("library"),camera:kt("camera"),document:Vn},xe,Ut=()=>(xe!=null||(xe=import("react-native-compressor").catch(()=>(xe=void 0,null))),xe),Ft=async(e,t,n)=>{try{return Number(await e.getFileSize(t))||n}catch{return n}},jn=new Set(["image/jpeg","image/jpg","image/heic","image/heif","image/webp"]),zn={low:640,medium:1280,high:1920},Hn=async(e,{image:t})=>{var r;if(!t||!jn.has(e.mime_type.toLowerCase()))return e;let n=await Ut();if(!n)return e;try{let i=await n.Image.compress(e.uri,{compressionMethod:"manual",maxWidth:t.max_width,maxHeight:t.max_height,quality:(r=t.quality)!=null?r:.8,output:"jpg"});return{...e,uri:i,mime_type:"image/jpeg",name:e.name.replace(/\.[^.]+$/,"")+".jpg",size:await Ft(n,i,e.size),processed:!0}}catch{return e}},Wn=async(e,{video:t})=>{var r;let n=await Ut();if(!n)return e;try{let i=await n.Video.compress(e.uri,{compressionMethod:"auto",maxSize:zn[(r=t==null?void 0:t.quality)!=null?r:"medium"],minimumFileSizeForCompress:2});return{...e,uri:i,mime_type:"video/mp4",size:await Ft(n,i,e.size),processed:!0}}catch{return e}},Jn={image:Hn,video:Wn},Kn=(e,t)=>t.split(".").reduce((n,r)=>le(n)?n[r]:void 0,e),$t=({file:e,target:t,onProgress:n,signal:r})=>new Promise((i,o)=>{if(t.target!=="url"||!("url"in t)){o(new u("INVALID_PARAMS","Thi\u1EBFu upload.url"));return}let c=t;if(r.aborted){o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"));return}let p=new XMLHttpRequest,a=new FormData;Object.entries(c.form_data).forEach(([g,A])=>a.append(g,A)),a.append(c.field_name,{uri:e.uri,name:e.name,type:e.mime_type});let s=()=>p.abort();r.addEventListener("abort",s);let d=g=>{r.removeEventListener("abort",s),g()};p.open("POST",c.url),Object.entries(c.headers).forEach(([g,A])=>p.setRequestHeader(g,A)),p.upload.onprogress=g=>n(g.loaded,g.total||e.size||0),p.onload=()=>d(()=>{let g=p.responseText;try{g=JSON.parse(p.responseText)}catch{}if(p.status<200||p.status>=300){o(new u("UPLOAD_FAILED",`HTTP ${p.status}`));return}let A=Kn(g,c.url_field);if(typeof A!="string"||!A){o(new u("UPLOAD_FAILED",`Response kh\xF4ng c\xF3 "${c.url_field}"`));return}i({url:A,response:g})}),p.onerror=()=>d(()=>o(new u("UPLOAD_FAILED","L\u1ED7i m\u1EA1ng khi upload"))),p.onabort=()=>d(()=>o(new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"))),p.send(a)}),Bt=e=>{var r,i;let t={...qn};for(let[o,c]of Object.entries((r=e==null?void 0:e.sources)!=null?r:{}))c?t[o]=c:delete t[o];let n={url:$t};for(let[o,c]of Object.entries((i=e==null?void 0:e.targets)!=null?i:{}))o!=="url"&&c&&(n[o]=c);return{sources:t,targets:n}},Vt=e=>{let{sources:t,targets:n}=Bt(e);return{sources:Object.keys(t),targets:Object.keys(n),max_count:nt}},Be=new Map,qt=(e,t)=>`${e}:${t}`,Yn=0,jt=(e,t)=>{var n;typeof t=="string"&&((n=Be.get(qt(e,t)))==null||n.abort())},we=e=>{for(let[t,n]of Be)t.startsWith(`${e}:`)&&n.abort()},$e=()=>new u("CANCELLED","\u0110\xE3 hu\u1EF7 upload"),Gn=(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)}},zt=async(e,t)=>{var a;let{sources:n,targets:r}=Bt(t.config),i=n[e.source];if(!i)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 ngu\u1ED3n "${e.source}"`);let o=r[e.target.target];if(!o)throw new u("NOT_SUPPORTED",`\u1EE8ng d\u1EE5ng ch\u01B0a h\u1ED7 tr\u1EE3 \u0111\xEDch upload "${e.target.target}"`);let c=new AbortController,p=qt(t.instance_id,(a=t.task_id)!=null?a:`auto-${++Yn}`);Be.set(p,c);try{return await Qn(e,t,i,o,c.signal)}finally{Be.delete(p)}},Qn=async(e,{instance_id:t,app_id:n,getContext:r,task_id:i,config:o,emit:c,exclusivePick:p=g=>g()},a,s,d)=>{var w,v,j;let g={app_id:n!=null?n:"",instance_id:t,context:{...(w=r==null?void 0:r())!=null?w:{}}},A=(await p(()=>a({accept:e.accept,max_count:e.max_count,process:e.process,caller:g}))).slice(0,e.max_count);if(d.aborted)throw $e();if(!A.length)throw new u("CANCELLED","Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ch\u1ECDn file");let l=[],h=A.filter(M=>Dn(M,e.accept)?!0:(l.push({name:M.name,code:"INVALID_FILE",message:`Kh\xF4ng cho ph\xE9p \u0111\u1ECBnh d\u1EA1ng ${M.mime_type||Nt(M.name)}`}),!1)),E=h.map(()=>0),S=h.map(M=>{var k;return(k=M.size)!=null?k:0}),_=0,f=0,C=(M=!1)=>{if(!c||!i)return;let k=Date.now();if(!M&&k-f<200)return;f=k;let ee=S.reduce((R,z)=>R+z,0),F=E.reduce((R,z)=>R+z,0);c("upload.progress",{task_id:i,loaded:F,total:ee,percent:ee?Math.min(100,Math.round(F/ee*100)):0,done_count:_,count:h.length})},K=[],U=0,ve=async()=>{var M,k,ee;for(;U<h.length;){let F=U++,R=h[F];try{if(d.aborted)throw $e();let z=R.mime_type.startsWith("image/")?"image":R.mime_type.startsWith("video/")?"video":void 0,ce=z&&!R.processed?(k=(M=o==null?void 0:o.processors)==null?void 0:M[z])!=null?k:Jn[z]:void 0;if(ce&&(R=await ce(R,e.process),S[F]=(ee=R.size)!=null?ee:S[F],d.aborted))throw $e();if(e.max_size&&R.size&&R.size>e.max_size)throw new u("FILE_TOO_LARGE",`File ${R.size} byte v\u01B0\u1EE3t gi\u1EDBi h\u1EA1n ${e.max_size}`);let me=(Ne,Ue)=>{E[F]=Ne,Ue&&(S[F]=Ue),C()},te=await s({file:R,target:e.target,onProgress:me,signal:d,caller:g});if(typeof(te==null?void 0:te.url)!="string"||!te.url)throw new u("UPLOAD_FAILED","Upload kh\xF4ng tr\u1EA3 url");let{url:Xe,...ne}=te;K[F]={url:Xe,name:R.name,mime_type:R.mime_type,size:R.size,width:R.width,height:R.height,duration:R.duration,...Object.keys(ne).length?{response:"response"in ne?ne.response:ne}:{}},E[F]=S[F]}catch(z){l.push(Gn(h[F].name,z))}finally{_++,C(!0)}}};if(await Promise.all(Array.from({length:Math.min(e.concurrency,h.length)},ve)),d.aborted)throw $e();let ae=K.filter(M=>!!M);if(!ae.length){let M=l[0];throw new u((v=M==null?void 0:M.code)!=null?v:"UPLOAD_FAILED",(j=M==null?void 0:M.message)!=null?j:"Kh\xF4ng upload \u0111\u01B0\u1EE3c file n\xE0o")}return{files:ae,failed:l}};import{Platform as Xn}from"react-native";var re,rt=e=>{var t;if(re===e&&(re=void 0,e.subscriptions.forEach(n=>n.remove()),e.started&&Xn.OS==="ios"))try{(t=e.native)==null||t.setAudioSessionActiveIOS(!1,{notifyOthersOnDeactivation:!0})}catch{}},Ht=async(e,t,n,r=()=>!0)=>{var o,c,p,a,s;if(re)throw new u("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new u("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let i={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};re=i;try{let d;try{d=await import("expo-speech-recognition")}catch{throw new u("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let g=d.ExpoSpeechRecognitionModule;if(i.native=g,i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let A=await g.requestPermissionsAsync();if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!A.granted)throw new u("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await g.getStateAsync()!=="inactive")throw new u("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(i.cancelled||!r())throw new u("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");i.subscriptions.push(g.addListener("result",l=>{var h,E;re!==i||i.cancelled||n(l.isFinal?"speech.final":"speech.partial",{...l,text:(E=(h=l.results[0])==null?void 0:h.transcript)!=null?E:""})}),g.addListener("error",l=>{re===i&&!i.cancelled&&n("speech.error",{...l,code:l.error})}),g.addListener("end",()=>{re===i&&(rt(i),n("speech.end"))})),i.started=!0,g.start({lang:(o=t.lang)!=null?o:"vi-VN",continuous:(c=t.continuous)!=null?c:!0,interimResults:(p=t.interimResults)!=null?p:!0,addsPunctuation:(a=t.addsPunctuation)!=null?a:!0,requiresOnDeviceRecognition:(s=t.requiresOnDeviceRecognition)!=null?s:!1,iosCategory:{category:d.AVAudioSessionCategory.playAndRecord,categoryOptions:[d.AVAudioSessionCategoryOptions.defaultToSpeaker,d.AVAudioSessionCategoryOptions.allowBluetooth],mode:d.AVAudioSessionMode.measurement}})}catch(d){throw rt(i),d}},Wt=e=>{let t=re;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},ie=e=>{let t=re;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{rt(t)}};var qe=1,u=class extends Error{constructor(n,r){super(r);this.code=n}},Kt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===qe&&typeof t.method=="string"?t:null}catch{return null}},Re=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,Yt=(e,t)=>Re({id:e,result:t}),Gt=(e,t)=>Re({id:e,error:{code:t.code,message:t.message}}),Qt=(e,t)=>Re({event:e,data:t}),ot=e=>Re({event:"context",data:e});var Xt=()=>`(function () {
|
|
2
2
|
var post = function (level, args) {
|
|
3
3
|
try {
|
|
4
4
|
var parts = [];
|
|
@@ -8,7 +8,7 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
|
|
|
8
8
|
else if (typeof a === 'object') { try { parts.push(JSON.stringify(a).slice(0, 800)); } catch (e) { parts.push(String(a)); } }
|
|
9
9
|
else { parts.push(String(a)); }
|
|
10
10
|
}
|
|
11
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
11
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${qe}, method: 'log', level: level, text: parts.join(' ') }));
|
|
12
12
|
} catch (e) {}
|
|
13
13
|
};
|
|
14
14
|
['log', 'info', 'warn', 'error'].forEach(function (level) {
|
|
@@ -19,7 +19,7 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
|
|
|
19
19
|
window.addEventListener('unhandledrejection', function (e) { post('error', ['[unhandledrejection]', e.reason]); });
|
|
20
20
|
// Kh\xF4ng log query (c\xF3 th\u1EC3 ch\u1EE9a token) \u2014 ch\u1EC9 \u0111\u01B0\u1EDDng d\u1EABn + route.
|
|
21
21
|
post('info', ['[page] ' + location.pathname + location.hash]);
|
|
22
|
-
})(); true;`,
|
|
22
|
+
})(); true;`,Zt=()=>`(function () {
|
|
23
23
|
function atTop(el) {
|
|
24
24
|
for (var n = el; n && n !== document.documentElement; n = n.parentElement) {
|
|
25
25
|
if (n.scrollTop > 0) { return false; }
|
|
@@ -30,7 +30,7 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
|
|
|
30
30
|
function report(at_top) {
|
|
31
31
|
if (at_top === last) { return; }
|
|
32
32
|
last = at_top;
|
|
33
|
-
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${
|
|
33
|
+
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ __retion: ${qe}, method: 'touchAtTop', at_top: at_top }));
|
|
34
34
|
}
|
|
35
35
|
document.addEventListener('touchstart', function (e) { report(atTop(e.target)); }, { capture: true, passive: true });
|
|
36
36
|
// Cu\u1ED9n r\u1EDDi \u0111\u1EA7u trang \u2192 b\xE1o ngay, kh\xF4ng \u0111\u1EE3i l\u1EA7n ch\u1EA1m sau (tr\xE1nh host d\xF9ng gi\xE1 tr\u1ECB c\u0169 "\u0111ang \u1EDF \u0111\u1EA7u").
|
|
@@ -38,8 +38,29 @@ var Ye="https://retion-miniapp-platform.vercel.app",de=null,vt=new Set,vn=e=>{de
|
|
|
38
38
|
var el = e.target === document ? document.documentElement : e.target;
|
|
39
39
|
if (el && el.scrollTop > 0) { report(false); }
|
|
40
40
|
}, { capture: true, passive: true });
|
|
41
|
-
})(); true;`,
|
|
42
|
-
|
|
41
|
+
})(); true;`,en=()=>`(function () {
|
|
42
|
+
if (window.__retionSafeAreaFrozen) { return; }
|
|
43
|
+
window.__retionSafeAreaFrozen = true;
|
|
44
|
+
var max = {};
|
|
45
|
+
var orig = window.getComputedStyle;
|
|
46
|
+
window.getComputedStyle = function (el, pseudo) {
|
|
47
|
+
var style = orig.call(this, el, pseudo);
|
|
48
|
+
var m = el && el.style && /env\\(safe-area-inset-(top|right|bottom|left)\\)/.exec(el.style.cssText || '');
|
|
49
|
+
if (!m) { return style; }
|
|
50
|
+
var prop = 'padding-' + m[1];
|
|
51
|
+
var value = parseFloat(style.getPropertyValue(prop)) || 0;
|
|
52
|
+
if (!(prop in max) || value > max[prop]) { max[prop] = value; }
|
|
53
|
+
var frozen = max[prop] + 'px';
|
|
54
|
+
return new Proxy(style, {
|
|
55
|
+
get: function (t, k) {
|
|
56
|
+
if (k === 'getPropertyValue') { return function (p) { return p === prop ? frozen : t.getPropertyValue(p); }; }
|
|
57
|
+
var v = t[k];
|
|
58
|
+
return typeof v === 'function' ? v.bind(t) : v;
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
})(); true;`,tn=e=>Re({event:e}),nn=(e,t)=>{let n=rn(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
|
|
63
|
+
${ot(e)}`},rn=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),on=(e,t={})=>{let n=rn(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${qe} };
|
|
43
64
|
window.__RETION_MINIAPP_CONTEXT__ = ${JSON.stringify(e)};
|
|
44
65
|
${n?`try { history.replaceState(history.state, '', location.pathname + '?' + ${JSON.stringify(n)} + location.hash); } catch (e) {}`:""}
|
|
45
|
-
true;`},Qt={partner:"partner_token",chatbox:"chatbox_token"},Xt=(e,t)=>{let n={...e};for(let i of Object.values(Qt))t.includes(i)||delete n[i];return n},Ze=new Set,ve=async(e,t)=>{if(Ze.has(e))throw new d("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);Ze.add(e);try{return await t()}finally{Ze.delete(e)}},jn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),De=(e,t)=>{if(typeof e!="string"||!e)throw new d("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Zt=async({method:e,params:t},{getHostData:n,getPermissions:i,is_dark:s,close:o,app_id:c,instance_id:a,options:r,emit:l,isActive:u})=>{var w,T,x,b,m,k,z,U,E;let p=r==null?void 0:r.handlers,h={app_id:c,instance_id:a,close:o},A=()=>new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let f=St(t);return ve(e,()=>xt(f,u))}case"speech.start":{if(!l)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 d("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");f.lang=t.lang}for(let y of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[y])!==void 0){if(typeof t[y]!="boolean")throw new d("INVALID_PARAMS",`${y} ph\u1EA3i l\xE0 boolean`);f[y]=t[y]}return Ft(a,f,l,u)}case"speech.stop":return $t(a);case"uploadFiles":{let{task_id:f,...y}=t!=null?t:{};if(f!==void 0&&(typeof f!="string"||!f))throw new d("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return Ut(Tt(y),{instance_id:a,task_id:f,config:r==null?void 0:r.upload,emit:l,exclusivePick:v=>ve("uploadFiles.pick",v)})}case"uploadFiles.cancel":Nt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Lt(r==null?void 0:r.upload);case"getBiometricAvailability":return((w=r==null?void 0:r.biometrics)!=null?w:await Ge()).getAvailability();case"authenticateBiometric":{let f=De(t==null?void 0:t.reason,"reason").trim();if(!f||f.length>200)throw new d("INVALID_PARAMS","reason must contain 1\u2013200 characters");let y=t==null?void 0:t.cancelButtonText;if(y!==void 0&&(typeof y!="string"||!y.trim()||y.length>80))throw new d("INVALID_PARAMS","Invalid cancelButtonText");return ve(e,async()=>{var D;return((D=r==null?void 0:r.biometrics)!=null?D:await Ge()).authenticate({reason:f,cancelButtonText:y})})}case"requestPayment":{let f=p==null?void 0:p.requestPayment;if(!f)throw A();let y=t==null?void 0:t.amount;if(typeof y!="number"||!Number.isFinite(y)||y<=0)throw new d("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let v={...t,amount:y,currency:De(t==null?void 0:t.currency,"currency")};return ve(e,()=>f(v,h))}case"printImage":{let f=p==null?void 0:p.printImage;if(!f)throw A();let y=De(t==null?void 0:t.image,"image");await ve(e,()=>f({image:y},h));return}case"openScreen":if(!(p!=null&&p.openScreen))throw A();await p.openScreen({screen:De(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},h);return;case"closeApp":o();return;case"openWebview":{let f=String((T=t==null?void 0:t.url)!=null?T:"");if(!/^https?:\/\//i.test(f))throw new d("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(r!=null&&r.openUrl?r.openUrl(f):Bt.openURL(f));return}case"openLink":{let f=String((x=t==null?void 0:t.url)!=null?x:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(f)||/^(javascript|file|data|about|blob):/i.test(f))throw new d("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(r!=null&&r.openUrl?r.openUrl(f):Bt.openURL(f))}catch(y){throw new d("NOT_SUPPORTED",String((m=(b=y==null?void 0:y.message)!=null?b:y)!=null?m:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(z=r==null?void 0:r.showToast)==null||z.call(r,String((k=t==null?void 0:t.message)!=null?k:""));return;case"haptic":{let f=jn.has(t==null?void 0:t.type)?t.type:"selection";(U=r==null?void 0:r.haptic)==null||U.call(r,f);return}case"getSystemInfo":return{platform:Vn.OS==="ios"?"ios":"android",appVersion:(E=r==null?void 0:r.app_version)!=null?E:"",theme:s?"dark":"light"};case"getAccessToken":{let f=n().access_token;if(!f)throw new d("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 D=n().access_token;if(!D)throw new d("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return D}if(f!=="partner"&&f!=="chatbox")throw new d("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(f)}`);let y=Qt[f];if(!i().includes(y))throw new d("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${y} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let v=f==="partner"?n().partner_token:n().chatbox_token;if(!v)throw new d("HOST_ERROR",`Kh\xF4ng c\xF3 ${y}`);return v}case"getUserInfo":{let f=n().user;if(!f)throw new d("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 d("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return f}case"sendMessage":case"insertText":throw new d("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new d("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var nt=e=>`bundle:${e}`,it=()=>`${R().file_system.document_dir}/miniapps`,rt=it,ot=(e,t,n="index.html",i=!1,s=[])=>{let o=`${rt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:i,permissions:s}},tt=e=>{var t;R().storage.setString(nt(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},Hn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,P=e=>{let t=R().storage.getString(nt(e));if(!t)return null;try{let{version:n,entry:i,context_update:s,permissions:o}=JSON.parse(t);return ot(e,n,i,!!s,Array.isArray(o)?o:[])}catch{return null}},te=e=>R().file_system.exists(e.entry_uri.replace("file://","")),st=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await te(t)},tn=async(e,t)=>{let n=R().file_system,i=`${rt()}/${e}`,s=await n.listDir(i).catch(()=>[]);await Promise.all(s.filter(o=>!t.includes(o)).map(o=>n.remove(`${i}/${o}`).catch(()=>{})))},nn=async e=>{var t;await((t=Se[e])==null?void 0:t.catch(()=>{})),R().storage.setString(nt(e),""),await R().file_system.remove(`${rt()}/${e}`).catch(()=>{})},Ae=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Se={},rn=(e,t)=>{var o;let i=((o=Se[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),s=i.catch(()=>{});return Se[e]=s,s.then(()=>{Se[e]===s&&delete Se[e]}),i},Wn=(e,t)=>{var s,o;let n=e.split(".").map(c=>parseInt(c,10)||0),i=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,i.length);c++){let a=((s=n[c])!=null?s:0)-((o=i[c])!=null?o:0);if(a)return a}return 0},zn=({manifest:e,zip_path:t})=>rn(e.app_id,async()=>{var o;let n=R().file_system,i=P(e.app_id);if(i&&Wn(i.version,e.version)>=0&&await te(i))return i;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let s=ot(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(s.dir).catch(()=>{}),await n.mkdir(s.dir),await n.unzip(t,s.dir),tt(e),j("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),tn(e.app_id,[e.version,i==null?void 0:i.version].filter(Boolean)),s}),at=(e,{base_url:t,onProgress:n}={})=>{let i=R().file_system,s=null,o=!1,c=`${i.cache_dir}/${e.app_id}-${e.version}.zip`,a=()=>{if(o)throw new Ae},r=async()=>{var p;a();let l=P(e.app_id);if((l==null?void 0:l.version)===e.version&&await i.exists(l.dir))return tt(e),P(e.app_id);a();let u=i.download({url:t?Hn(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(h,A)=>{var T;let w=A>0?A:(T=e.size)!=null?T:0;w>0&&(n==null||n(Math.min(1,h/w)))}});s=u;try{let{status:h}=await u.promise;if(a(),h!==200)throw new Error(`bundle ${h}`);if(e.sha256)if(i.sha256){if(await i.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else j("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);a();let A=ot(e.app_id,e.version,e.entry,!!e.context_update,(p=e.permissions)!=null?p:[]);return await i.remove(A.dir).catch(()=>{}),await i.mkdir(A.dir),await i.unzip(c,A.dir),tt(e),tn(e.app_id,[e.version,l==null?void 0:l.version].filter(Boolean)),A}catch(h){throw o?new Ae:h}finally{s=null,i.remove(c).catch(()=>{})}};return{promise:rn(e.app_id,r),cancel:()=>{o=!0,s==null||s.cancel()}}},be={},Jn=__DEV__?0:60*1e3,en={},on=(e,t)=>{var i,s;let n=P(e);return n&&Date.now()-((i=en[t])!=null?i:0)<Jn?Promise.resolve(n):((s=be[e])!=null||(be[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),a=await at(c,{base_url:t}).promise;return en[t]=Date.now(),a})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{be[e]=void 0})),be[e])};var Ue=new Map,sn=(e,t)=>(Ue.set(e,t),()=>{Ue.get(e)===t&&Ue.delete(e)}),Kn=(e,t)=>{let n=Ue.get(e);return n?n(t):!1};import{useRef as Yn,useSyncExternalStore as Gn}from"react";var Fe=e=>{let t=e,n=new Set;return{getState:()=>t,setState:i=>{let s=typeof i=="function"?i(t):i;t={...t,...s},n.forEach(o=>o())},subscribe:i=>(n.add(i),()=>{n.delete(i)})}},Q=(e,t,n=Object.is)=>{let i=Yn(null),s=()=>{let o=e.getState(),c=i.current;if(c&&c.state===o&&c.selector===t)return c.value;let a=t(o),r=c&&n(c.value,a)?c.value:a;return i.current={state:o,selector:t,value:r},r};return Gn(e.subscribe,s)};var H=Fe({active_key:null,instances:{}}),an=({app:e,instance_id:t,context:n={},url_params:i={},host_data:s={}},o)=>{var a;let c=(a=R().keep_alive)==null?void 0:a.max_webviews;H.setState(r=>{let l=t!=null?t:e.app_id,u={...r.instances,[l]:{key:l,app:e,context:n,url_params:i,host_data:s,last_used_at:Date.now()}},p=Object.keys(u);return c&&c>0&&p.length>c&&p.filter(h=>h!==l).sort((h,A)=>u[h].last_used_at-u[A].last_used_at).slice(0,p.length-c).forEach(h=>{delete u[h]}),o?{active_key:l,instances:u}:{instances:u}})},Qn=e=>an(e,!0),Xn=e=>an(e,!1),xe=()=>H.setState({active_key:null}),$e=e=>{H.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var cn="catalog",Zn="paused_apps",ei="removed_apps",ti=10*1e3,ni=2,ii=3e3,ri=()=>{var e;try{return JSON.parse((e=R().storage.getString(cn))!=null?e:"{}")}catch{return{}}},S=Fe({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),ln=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},Ve=new Set,pn=e=>{let t=new Set,n=()=>R().storage.setString(e,JSON.stringify([...t]));return{has:i=>t.has(i),values:()=>[...t],add:i=>t.has(i)?!1:(t.add(i),n(),!0),delete:i=>t.delete(i)?(n(),!0):!1,load:()=>{var i;t.clear();try{let s=JSON.parse((i=R().storage.getString(e))!=null?i:"[]");Array.isArray(s)&&s.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Y=pn(Zn),le=pn(ei);_t(()=>{Y.load(),le.load();let e=ri(),t={};Object.keys(e).filter(n=>!le.has(n)).forEach(n=>{let i=P(n);i?t[n]={status:"installed",progress:1,version:i.version,has_local:!0}:Y.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),S.setState({catalog:e,downloads:t})});var lt=e=>Q(S,t=>e?t.downloads[e]:void 0),oi=()=>Q(S,e=>e.pause_reasons.length>0),K=(...e)=>j("queue",...e),L=[],ne={},_=null,Be=new Set,me={},ct=new Set,ae=e=>{ct.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},si=e=>(ct.add(e),()=>{ct.delete(e)}),ai=()=>S.getState().downloads,B=(e,t)=>{let n=!!P(e),i=S.getState().downloads[e],s=t.status==="downloading"&&n?"updating":t.status,o={...i!=null?i:{status:"queued",progress:0},...t,...s?{status:s}:{},has_local:n};S.setState(c=>({downloads:{...c.downloads,[e]:o}})),(i==null?void 0:i.status)!==o.status||(i==null?void 0:i.version)!==o.version||(i==null?void 0:i.has_local)!==o.has_local?ae({type:"status_change",app_id:e,state:o}):i.progress!==o.progress&&ae({type:"progress",app_id:e,progress:o.progress,version:o.version})},qe=(e,t)=>{var n;(n=me[e])==null||n.forEach(i=>i(t)),delete me[e]},ci=()=>S.getState().pause_reasons.length>0,ce=e=>{var a;if(_)return;let t=e?L.indexOf(e):ci()?-1:L.findIndex(r=>!Y.has(r));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),i=S.getState().catalog[n];if(!i){qe(n,P(n)),ce();return}let s=Date.now();ne[n]=((a=ne[n])!=null?a:0)+1,B(n,{status:"downloading",progress:0,version:i.version,error:void 0});let o=0,c=at(i,{onProgress:r=>{let l=Math.floor(r*100);l!==o&&(o=l,B(n,{progress:l/100,version:i.version}))}});_={app_id:n,handle:c,forced:!!e},K("start",n,i.version,e?"(forced)":""),c.promise.then(r=>{K("installed",n,i.version,`${Date.now()-s}ms`),B(n,{status:"installed",progress:1,version:i.version}),qe(n,r)}).catch(r=>{var u;if(r instanceof Ae){if(Be.has(n))return;K("paused",n),ne[n]-=1,L.unshift(n),B(n,{status:Y.has(n)?"paused":"queued",progress:0,version:i.version});return}let l=String((u=r==null?void 0:r.message)!=null?u:r);if(console.warn("[miniapp-queue] failed",n,l),ne[n]<ni){B(n,{status:"queued",progress:0,version:i.version,error:l}),setTimeout(()=>{var p;L.includes(n)||(_==null?void 0:_.app_id)===n||(L.push(n),ce((p=me[n])!=null&&p.length?n:void 0))},ii);return}B(n,{status:"failed",progress:0,version:i.version,error:l}),qe(n,P(n))}).finally(()=>{_=null;let r=L.find(l=>{var u;return(u=me[l])==null?void 0:u.length});ce(r)})},je=(e,{front:t=!1}={})=>{if((_==null?void 0:_.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},li=async e=>{let{host_id:t,client_token:n}=R(),i=new AbortController,s=setTimeout(()=>i.abort(),ti);try{let o=`${Ye}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:i.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(r=>({...r,channel:e}))}finally{clearTimeout(s)}},Ee=null,pt=()=>(Ee!=null||(Ee=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(li)),i={};[...n].reverse().flat().forEach(r=>{i[r.app_id]=r});let s=Object.keys(S.getState().catalog).filter(r=>!i[r]);R().storage.setString(cn,JSON.stringify(i)),S.setState({catalog:i}),await Promise.all(s.map(r=>un(r,{by_user:!1}))),s.forEach(r=>le.delete(r));let o=Object.keys(i).filter(r=>!le.has(r)),c=[],a={};for(let r of o.map(l=>i[l])){if(await st(r)){B(r.app_id,{status:"installed",progress:1,version:r.version});continue}let l=P(r.app_id);if(ln(r.app_id)&&!Ve.has(r.app_id)&&l&&await te(l)){B(r.app_id,{status:"installed",progress:1,version:l.version}),a[r.app_id]={app_id:r.app_id,current_version:l.version,next_version:r.version};continue}c.push(r)}return S.setState({updates:a}),c.forEach(r=>{ne[r.app_id]=0,B(r.app_id,{status:Y.has(r.app_id)?"paused":"queued",progress:0,version:r.version,error:void 0}),je(r.app_id)}),K("catalog",o.length,"apps, outdated",c.map(r=>r.app_id),"removed",s,`${Date.now()-e}ms`),ae({type:"sync_complete",app_ids:o,removed:s}),Object.values(a).forEach(r=>ae({type:"update_available",...r})),ce(),{ok:!0,app_ids:o,removed:s}}catch(n){let i=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",i),ae({type:"sync_failed",error:i}),{ok:!1,error:i}}finally{Ee=null}})()),Ee),un=async(e,{by_user:t})=>{var s,o,c,a;if(t&&le.add(e),Be.has(e))return;Be.add(e),Y.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(_==null?void 0:_.app_id)===e&&_.handle.cancel();let i=(a=(c=(s=S.getState().downloads[e])==null?void 0:s.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?a:"";B(e,{status:"uninstalling",progress:0,version:i}),await nn(e),$e(e),S.setState(r=>{let l={...r.downloads};return delete l[e],{downloads:l}}),delete ne[e],Be.delete(e),qe(e,null),K("uninstalled",e,t?"(user)":"(not in list)"),ae({type:"uninstalled",app_id:e})},pi=e=>un(e,{by_user:!0}),ui=e=>{let t=Pe(e);return t?(le.delete(e),(_==null?void 0:_.app_id)===e||L.includes(e)||(ne[e]=0,B(e,{status:Y.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),je(e),ce(),K("restore",e)),!0):!1},di=e=>{if(Y.has(e))return;if(Y.add(e),K("pause app",e),(_==null?void 0:_.app_id)===e&&!_.forced){_.handle.cancel();return}let t=S.getState().downloads[e];L.includes(e)&&t&&B(e,{status:"paused",progress:0,version:t.version})},gi=e=>{if(!Y.delete(e))return;K("resume app",e);let t=S.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&Pe(e)&&(ne[e]=0,je(e)),L.includes(e)&&t&&B(e,{status:"queued",progress:0,version:t.version}),ce()},fi=e=>{let{pause_reasons:t}=S.getState();t.includes(e)||(S.setState({pause_reasons:[...t,e]}),K("pause",e),t.length===0&&ae({type:"pause_change",paused:!0,reasons:[e]}),_&&!_.forced&&_.handle.cancel())},mi=e=>{let{pause_reasons:t}=S.getState();if(!t.includes(e))return;let n=t.filter(i=>i!==e);S.setState({pause_reasons:n}),K("resume",e),n.length===0&&ae({type:"pause_change",paused:!1,reasons:n}),ce()},dn=e=>S.getState().updates[e],hi=async e=>{var n,i;let t=dn(e);Ve.add(e);try{let s=await He(e),o=(i=t==null?void 0:t.next_version)!=null?i:(n=Pe(e))==null?void 0:n.version;return!s||!o||s.version!==o?!1:(S.setState(c=>{var r;let a={...c.updates};return delete a[e],{updates:a,apply_ticks:{...c.apply_ticks,[e]:((r=c.apply_ticks[e])!=null?r:0)+1}}}),K("updated",e,t==null?void 0:t.current_version,"\u2192",s.version),!0)}finally{Ve.delete(e)}},Ai=()=>Object.values(S.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:le.has(e.app_id)})),Pe=e=>S.getState().catalog[e],He=async e=>{let t=Pe(e);if(!t)return;if(Y.delete(e),le.delete(e),await st(t))return P(e);let n=P(e);if(ln(e)&&!Ve.has(e)&&n&&await te(n))return n;let i=new Promise(s=>{var o;((o=me[e])!=null?o:me[e]=[]).push(s)});return(_==null?void 0:_.app_id)===e?_.forced=!0:(ne[e]=0,je(e,{front:!0}),_&&!_.forced?_.handle.cancel():ce(e)),i};import{Fragment as hn,jsx as N,jsxs as Oe}from"react/jsx-runtime";var dt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),fn=0,bi=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Si=mt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:i,reload_tick:s,web_at_top:o,splash:c,bridge:a,opaque_background:r,allow_embedded_miniapps:l,onWebLoadEnd:u})=>{var wt,yt;let p=G(null),h=G(!1),A=Q(H,g=>g.instances[e]),w=A==null?void 0:A.app.app_id,T=A==null?void 0:A.app.manifest_url,x=A==null?void 0:A.context,b=A==null?void 0:A.url_params,[m,k]=he(()=>w?P(w):null),[z,U]=he(!1),[E,f]=he(0),[y,v]=he(0),[D,C]=he(!1),V=G(null),ie=g=>{V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{V.current=null,C(!0)},g)};q(()=>()=>{V.current&&clearTimeout(V.current)},[]),q(()=>{if(!w||!t&&m)return;let g=!0;return U(!1),(async()=>{let M=P(w),F=M?await te(M):!1;if(!g||(k(F?J=>!J||J.version!==M.version||J.permissions.join(",")!==M.permissions.join(",")?M:J:null),__DEV__&&Date.now()-fn>1e4&&(fn=Date.now(),await pt()),!g))return;let oe=await He(w),ue=oe!==void 0?oe:T?await on(w,T):P(w);if(g){if(!ue){U(!0);return}k(J=>J!=null?J:ue)}})(),()=>{g=!1}},[t,w,T,E]),q(()=>sn(e,g=>p.current?(p.current.postMessage(g),!0):!1),[e]);let ze=Q(S,g=>{let M=w?g.downloads[w]:void 0;return(M==null?void 0:M.status)==="installed"?M.version:void 0});q(()=>{if(t||!w||!m)return;let g=P(w);if(!g||g.version===m.version)return;let M=!0;return te(g).then(F=>{!M||!F||(j(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",m.version,"\u2192",g.version),k(g))}),()=>{M=!1}},[t,w,ze,m==null?void 0:m.version]);let pe=Q(S,g=>{var M;return w&&(M=g.apply_ticks[w])!=null?M:0});q(()=>{if(!pe||!w)return;let g=P(w);if(!g||g.version===(m==null?void 0:m.version))return;let M=!0;return te(g).then(F=>{!M||!F||(j(`webview:${e}`,"c\u1EADp nh\u1EADt",m==null?void 0:m.version,"\u2192",g.version),C(!1),k(g))}),()=>{M=!1}},[pe]),q(()=>{var F;let g=(F=R().keep_alive)==null?void 0:F.idle_close_ms;if(t||!g||g<=0)return;let M=setTimeout(()=>{$e(e)},g);return()=>clearTimeout(M)},[t,e]),q(()=>{s>0&&(U(!1),C(!1),v(g=>g+1),f(g=>g+1))},[s]);let Te=G(t);q(()=>{var g;Te.current!==t&&(Te.current=t,h.current&&((g=p.current)==null||g.injectJavaScript(Jt(t?"resumed":"paused"))))},[t]);let re=`${(wt=m==null?void 0:m.version)!=null?wt:"none"}:${(yt=m==null?void 0:m.permissions.join(","))!=null?yt:""}:${y}`,we=We(()=>JSON.stringify([x!=null?x:{},b!=null?b:{}]),[x,b]),Je=We(()=>{var g;return Xt(b!=null?b:{},(g=m==null?void 0:m.permissions)!=null?g:[])},[we,m==null?void 0:m.permissions]),wn=We(()=>Gt(x!=null?x:{},Je)+zt()+(R().debug?Wt():""),[Je]),ke=G(null),At=G(null);q(()=>{var M,F,oe;if(!m)return;if(At.current!==re){At.current=re,ke.current=we;return}if(ke.current===we)return;let g=((F=JSON.parse((M=ke.current)!=null?M:"[]")[0])!=null?F:{}).org_id;if(ke.current=we,g===(x==null?void 0:x.org_id)&&h.current){C(!1),ie(1500),(oe=p.current)==null||oe.injectJavaScript(Kt(x!=null?x:{},Je));return}C(!1),v(ue=>ue+1)},[we,m,re]),q(()=>(t||(ee(e),fe(e)),()=>{ee(e),fe(e)}),[t,e,re,s]),q(()=>{let g=gn.addEventListener("change",M=>{M==="background"&&ee(e)});return()=>g.remove()},[e]);let yn=gt(async g=>{var F,oe,ue,J,Ke;let M=qt(g.nativeEvent.data);if(!M){if(w&&(a!=null&&a.onWebEvent))try{Promise.resolve(a.onWebEvent(g.nativeEvent.data,{app_id:w,instance_id:e})).catch(O=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,O)})}catch(O){console.warn("[miniapp] onWebEvent l\u1ED7i",w,O)}return}if(M.method==="log"){let{level:O,text:$}=M;j(`web:${e}`,O!=null?O:"log",$!=null?$:"");return}if(M.method==="pong"){V.current||C(!0);return}if(M.method==="touchAtTop"){o.emit(!!M.at_top);return}if(M.method==="contextApplied"){V.current&&clearTimeout(V.current),V.current=null,C(!0);return}if(M.method==="ready"){h.current=!0,C(!0);let O=(F=H.getState().instances[e])==null?void 0:F.context;O&&((oe=p.current)==null||oe.injectJavaScript(et(O)));return}try{let O=await Zt(M,{getHostData:()=>{var $,X;return(X=($=H.getState().instances[e])==null?void 0:$.host_data)!=null?X:{}},getPermissions:()=>{var $,X;return w?(X=($=P(w))==null?void 0:$.permissions)!=null?X:[]:[]},is_dark:i,close:xe,app_id:w!=null?w:"",instance_id:e,options:a,emit:($,X)=>{var Mt;(Mt=p.current)==null||Mt.injectJavaScript(Ht($,X))},isActive:()=>H.getState().active_key===e&&gn.currentState!=="background"});M.id&&((ue=p.current)==null||ue.injectJavaScript(Vt(M.id,O)))}catch(O){if(!M.id)return;let $=O==null?void 0:O.code,X=O instanceof d?O:new d(typeof $=="string"?$:"HOST_ERROR",String((J=O==null?void 0:O.message)!=null?J:O));(Ke=p.current)==null||Ke.injectJavaScript(jt(M.id,X))}},[e,i,w,o,a]),Mn=gt(()=>{U(!1),v(g=>g+1),f(g=>g+1)},[]);return Oe(ft,{style:[ht.absoluteFill,r&&{backgroundColor:i?"#09090B":"#FFFFFF"},!n&&W.behind],pointerEvents:t?"auto":"none",children:[m?N(_i,{ref:p,source:{uri:m.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${l?it():m.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:wn,onMessage:yn,bounces:!1,overScrollMode:"never",onLoadStart:g=>{ee(e),fe(e),j(`webview:${e}`,"load start",dt(g.nativeEvent.url)),h.current=!1,C(!1)},onError:g=>{ee(e),fe(e),j(`webview:${e}`,"load error",dt(g.nativeEvent.url),g.nativeEvent.description),U(!0),C(!1)},onLoadEnd:g=>{let M=g.nativeEvent.url;j(`webview:${e}`,"load end",dt(M)),w&&(u==null||u({app_id:w,instance_id:e,url:M})),ie(1500)},onContentProcessDidTerminate:()=>{ee(e),fe(e),h.current=!1,C(!1),v(g=>g+1)},onRenderProcessGone:()=>(ee(e),fe(e),h.current=!1,C(!1),v(g=>g+1),!0),style:W.webview},re):null,A&&N(Ei,{visible:!m||!D,interactive:z,children:N(xi,{splash:c,app:A.app,is_dark:i,error:z,has_bundle:!!m,retry:Mn})})]})}),xi=mt.memo(({splash:e,app:t,is_dark:n,error:i,has_bundle:s,retry:o})=>{let c=e,a=lt(t.app_id),r=i?"error":!s&&(a==null?void 0:a.status)==="downloading"?"downloading":"loading";return N(c,{app:t,is_dark:n,status:r,progress:r==="downloading"?a==null?void 0:a.progress:void 0,retry:o})}),Ei=({visible:e,interactive:t,children:n})=>{let i=G(new ut.Value(e?1:0)).current,[s,o]=he(e);return q(()=>{if(e){o(!0),i.setValue(1);return}let c=ut.timing(i,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:a})=>{a&&o(!1)}),()=>c.stop()},[e,i]),s?N(ut.View,{style:[ht.absoluteFill,{opacity:i}],pointerEvents:t?"auto":"none",children:n}):null},An=({app:e,is_dark:t,status:n,progress:i,retry:s})=>{let o=t?"#FAFAFA":"#18181B";return Oe(ft,{style:[W.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[N(ft,{style:[W.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?N(Mi,{source:{uri:e.icon},style:W.splash_icon_image}):N(Re,{style:W.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),N(Re,{style:[W.splash_name,{color:o}],children:e.name}),n==="error"?Oe(hn,{children:[N(Re,{style:W.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),N(vi,{activeOpacity:.7,style:[W.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:s,children:N(Re,{style:[W.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):Oe(hn,{children:[N(wi,{style:W.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&Oe(Re,{style:W.splash_hint,children:["\u0110ang t\u1EA3i mini app",i?` ${Math.round(i*100)}%`:"\u2026"]})]})]})},mn=(e,t)=>{let n=G(t),i=G(!1);__DEV__&&!i.current&&n.current!==t&&(i.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},Pi=({container:e,splash:t=An,is_dark:n=!1,bridge:i,close_on_back:s=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:a})=>{mn("container",e),mn("splash",t);let r=e,l=Q(H,m=>m.active_key),u=G(l);l&&(u.current=l);let p=Q(H,m=>Object.keys(m.instances).join("|")),h=Q(H,m=>{var k;return m.active_key?(k=m.instances[m.active_key])==null?void 0:k.app.name:void 0}),A=We(()=>p?p.split("|"):[],[p]),[w,T]=he({}),x=G(bi()).current;q(()=>{if(!l||!s)return;let m=yi.addEventListener("hardwareBackPress",()=>(xe(),!0));return()=>m.remove()},[l,s]);let b=gt(()=>{let m=H.getState().active_key;m&&T(k=>({...k,[m]:(k[m]||0)+1}))},[]);return A.length?N(r,{visible:!!l,title:h!=null?h:"",is_dark:n,close:xe,reload:b,subscribeWebAtTop:x.subscribe,children:A.map(m=>N(Si,{instance_key:m,is_active:l===m,is_front:(l!=null?l:u.current)===m,is_dark:n,reload_tick:w[m]||0,web_at_top:x,splash:t,bridge:i,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:a},m))}):null},W=ht.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"}}),Ri=mt.memo(Pi);export{An as DefaultMiniAppSplash,Ye as MINIAPP_PLATFORM_URL,Ri as MiniAppHost,d as MiniAppHostError,xe as closeMiniApp,vn as configureMiniApp,Dn as createDocumentPickerSource,bn as createMmkvStorage,bt as createReactNativeBiometrics,_n as createRnfsFileSystem,He as ensureMiniApp,P as getLocalMiniApp,Ai as getMiniAppCatalog,Pe as getMiniAppCatalogEntry,ai as getMiniAppStatuses,dn as getMiniAppUpdate,zn as installBundledMiniApp,si as onMiniAppEvent,Qn as openMiniApp,di as pauseMiniApp,fi as pauseMiniAppDownloads,Xn as preloadMiniApp,ee as releaseSpeechFor,ui as restoreMiniApp,gi as resumeMiniApp,mi as resumeMiniAppDownloads,Kn as sendEventToWeb,pt as syncMiniAppCatalog,pi as uninstallMiniApp,hi as updateMiniApp,Ct as uploadToUrl,lt as useMiniAppDownload,oi as useMiniAppDownloadsPaused};
|
|
66
|
+
true;`},sn={partner:"partner_token",chatbox:"chatbox_token"},an=(e,t)=>{let n={...e};for(let r of Object.values(sn))t.includes(r)||delete n[r];return n},it=new Set,Pe=async(e,t)=>{if(it.has(e))throw new u("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);it.add(e);try{return await t()}finally{it.delete(e)}},er=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Ve=(e,t)=>{if(typeof e!="string"||!e)throw new u("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},cn=async({method:e,params:t},{getHostData:n,getPermissions:r,getContext:i,is_dark:o,close:c,app_id:p,instance_id:a,options:s,emit:d,isActive:g})=>{var E,S,_,f,C,K,U,ve,ae;let A=s==null?void 0:s.handlers,l={app_id:p,instance_id:a,close:c},h=()=>new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let w=Rt(t);return Pe(e,()=>Ot(w,g))}case"speech.start":{if(!d)throw h();let w={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new u("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");w.lang=t.lang}for(let v of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[v])!==void 0){if(typeof t[v]!="boolean")throw new u("INVALID_PARAMS",`${v} ph\u1EA3i l\xE0 boolean`);w[v]=t[v]}return Ht(a,w,d,g)}case"speech.stop":return Wt(a);case"uploadFiles":{let{task_id:w,...v}=t!=null?t:{};if(w!==void 0&&(typeof w!="string"||!w))throw new u("INVALID_PARAMS","task_id ph\u1EA3i l\xE0 chu\u1ED7i");return zt(Dt(v),{instance_id:a,app_id:p,getContext:i,task_id:w,config:s==null?void 0:s.upload,emit:d,exclusivePick:j=>Pe("uploadFiles.pick",j)})}case"uploadFiles.cancel":jt(a,t==null?void 0:t.task_id);return;case"getUploadCapabilities":return Vt(s==null?void 0:s.upload);case"getBiometricAvailability":return((E=s==null?void 0:s.biometrics)!=null?E:await tt()).getAvailability();case"authenticateBiometric":{let w=Ve(t==null?void 0:t.reason,"reason").trim();if(!w||w.length>200)throw new u("INVALID_PARAMS","reason must contain 1\u2013200 characters");let v=t==null?void 0:t.cancelButtonText;if(v!==void 0&&(typeof v!="string"||!v.trim()||v.length>80))throw new u("INVALID_PARAMS","Invalid cancelButtonText");return Pe(e,async()=>{var M;return((M=s==null?void 0:s.biometrics)!=null?M:await tt()).authenticate({reason:w,cancelButtonText:v})})}case"requestPayment":{let w=A==null?void 0:A.requestPayment;if(!w)throw h();let v=t==null?void 0:t.amount;if(typeof v!="number"||!Number.isFinite(v)||v<=0)throw new u("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let j={...t,amount:v,currency:Ve(t==null?void 0:t.currency,"currency")};return Pe(e,()=>w(j,l))}case"printImage":{let w=A==null?void 0:A.printImage;if(!w)throw h();let v=Ve(t==null?void 0:t.image,"image");await Pe(e,()=>w({image:v},l));return}case"openScreen":if(!(A!=null&&A.openScreen))throw h();await A.openScreen({screen:Ve(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},l);return;case"closeApp":c();return;case"openWebview":{let w=String((S=t==null?void 0:t.url)!=null?S:"");if(!/^https?:\/\//i.test(w))throw new u("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(s!=null&&s.openUrl?s.openUrl(w):Jt.openURL(w));return}case"openLink":{let w=String((_=t==null?void 0:t.url)!=null?_:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(w)||/^(javascript|file|data|about|blob):/i.test(w))throw new u("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(s!=null&&s.openUrl?s.openUrl(w):Jt.openURL(w))}catch(v){throw new u("NOT_SUPPORTED",String((C=(f=v==null?void 0:v.message)!=null?f:v)!=null?C:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(U=s==null?void 0:s.showToast)==null||U.call(s,String((K=t==null?void 0:t.message)!=null?K:""));return;case"haptic":{let w=er.has(t==null?void 0:t.type)?t.type:"selection";(ve=s==null?void 0:s.haptic)==null||ve.call(s,w);return}case"getSystemInfo":return{platform:Zn.OS==="ios"?"ios":"android",appVersion:(ae=s==null?void 0:s.app_version)!=null?ae:"",theme:o?"dark":"light"};case"getAccessToken":{let w=n().access_token;if(!w)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return w}case"getToken":{let w=t==null?void 0:t.type;if(w==="access"){let M=n().access_token;if(!M)throw new u("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return M}if(w!=="partner"&&w!=="chatbox")throw new u("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(w)}`);let v=sn[w];if(!r().includes(v))throw new u("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${v} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let j=w==="partner"?n().partner_token:n().chatbox_token;if(!j)throw new u("HOST_ERROR",`Kh\xF4ng c\xF3 ${v}`);return j}case"getUserInfo":{let w=n().user;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return w}case"getPageInfo":{let w=n().page;if(!w)throw new u("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return w}case"sendMessage":case"insertText":throw new u("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new u("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var at=e=>`bundle:${e}`,ct=()=>`${O().file_system.document_dir}/miniapps`,pt=ct,lt=(e,t,n="index.html",r=!1,i=[])=>{let o=`${pt()}/${e}/${t}`;return{app_id:e,version:t,dir:o,entry_uri:`file://${o}/${n}`,context_update:r,permissions:i}},st=e=>{var t;O().storage.setString(at(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}`,P=e=>{let t=O().storage.getString(at(e));if(!t)return null;try{let{version:n,entry:r,context_update:i,permissions:o}=JSON.parse(t);return lt(e,n,r,!!i,Array.isArray(o)?o:[])}catch{return null}},oe=e=>O().file_system.exists(e.entry_uri.replace("file://","")),ut=async e=>{let t=P(e.app_id);return(t==null?void 0:t.version)===e.version&&await oe(t)},ln=async(e,t)=>{let n=O().file_system,r=`${pt()}/${e}`,i=await n.listDir(r).catch(()=>[]);await Promise.all(i.filter(o=>!t.includes(o)).map(o=>n.remove(`${r}/${o}`).catch(()=>{})))},un=async e=>{var t;await((t=Te[e])==null?void 0:t.catch(()=>{})),O().storage.setString(at(e),""),await O().file_system.remove(`${pt()}/${e}`).catch(()=>{})},Se=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},Te={},dn=(e,t)=>{var o;let r=((o=Te[e])!=null?o:Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return Te[e]=i,i.then(()=>{Te[e]===i&&delete Te[e]}),r},nr=(e,t)=>{var i,o;let n=e.split(".").map(c=>parseInt(c,10)||0),r=t.split(".").map(c=>parseInt(c,10)||0);for(let c=0;c<Math.max(n.length,r.length);c++){let p=((i=n[c])!=null?i:0)-((o=r[c])!=null?o:0);if(p)return p}return 0},rr=({manifest:e,zip_path:t})=>dn(e.app_id,async()=>{var o;let n=O().file_system,r=P(e.app_id);if(r&&nr(r.version,e.version)>=0&&await oe(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let i=lt(e.app_id,e.version,e.entry,!!e.context_update,(o=e.permissions)!=null?o:[]);return await n.remove(i.dir).catch(()=>{}),await n.mkdir(i.dir),await n.unzip(t,i.dir),st(e),W("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),ln(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),i}),dt=(e,{base_url:t,onProgress:n}={})=>{let r=O().file_system,i=null,o=!1,c=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,p=()=>{if(o)throw new Se},a=async()=>{var g;p();let s=P(e.app_id);if((s==null?void 0:s.version)===e.version&&await r.exists(s.dir))return st(e),P(e.app_id);p();let d=r.download({url:t?tr(t,e.bundle_url):e.bundle_url,to_file:c,onProgress:(A,l)=>{var E;let h=l>0?l:(E=e.size)!=null?E:0;h>0&&(n==null||n(Math.min(1,A/h)))}});i=d;try{let{status:A}=await d.promise;if(p(),A!==200)throw new Error(`bundle ${A}`);if(e.sha256)if(r.sha256){if(await r.sha256(c)!==e.sha256)throw new Error("sha256 mismatch")}else W("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);p();let l=lt(e.app_id,e.version,e.entry,!!e.context_update,(g=e.permissions)!=null?g:[]);return await r.remove(l.dir).catch(()=>{}),await r.mkdir(l.dir),await r.unzip(c,l.dir),st(e),ln(e.app_id,[e.version,s==null?void 0:s.version].filter(Boolean)),l}catch(A){throw o?new Se:A}finally{i=null,r.remove(c).catch(()=>{})}};return{promise:dn(e.app_id,a),cancel:()=>{o=!0,i==null||i.cancel()}}},Oe={},ir=__DEV__?0:60*1e3,pn={},gn=(e,t)=>{var r,i;let n=P(e);return n&&Date.now()-((r=pn[t])!=null?r:0)<ir?Promise.resolve(n):((i=Oe[e])!=null||(Oe[e]=(async()=>{let o=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!o.ok)throw new Error(`manifest ${o.status}`);let c=await o.json(),p=await dt(c,{base_url:t}).promise;return pn[t]=Date.now(),p})().catch(o=>(console.warn("[miniapp] sync failed",e,o==null?void 0:o.message),P(e))).finally(()=>{Oe[e]=void 0})),Oe[e])};var je=new Map,mn=(e,t)=>(je.set(e,t),()=>{je.get(e)===t&&je.delete(e)}),or=(e,t)=>{let n=je.get(e);return n?n(t):!1};import{useRef as sr,useSyncExternalStore as ar}from"react";var ze=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let i=typeof r=="function"?r(t):r;t={...t,...i},n.forEach(o=>o())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},Z=(e,t,n=Object.is)=>{let r=sr(null),i=()=>{let o=e.getState(),c=r.current;if(c&&c.state===o&&c.selector===t)return c.value;let p=t(o),a=c&&n(c.value,p)?c.value:p;return r.current={state:o,selector:t,value:a},a};return ar(e.subscribe,i)};var B=ze({active_key:null,instances:{}}),fn=({app:e,instance_id:t,context:n={},url_params:r={},host_data:i={}},o)=>{var p;let c=(p=O().keep_alive)==null?void 0:p.max_webviews;B.setState(a=>{let s=t!=null?t:e.app_id,d={...a.instances,[s]:{key:s,app:e,context:n,url_params:r,host_data:i,last_used_at:Date.now()}},g=Object.keys(d);return c&&c>0&&g.length>c&&g.filter(A=>A!==s).sort((A,l)=>d[A].last_used_at-d[l].last_used_at).slice(0,g.length-c).forEach(A=>{delete d[A]}),o?{active_key:s,instances:d}:{instances:d}})},cr=e=>fn(e,!0),pr=e=>fn(e,!1),Ce=()=>B.setState({active_key:null}),He=e=>{B.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var hn="catalog",lr="paused_apps",ur="removed_apps",dr=10*1e3,gr=2,mr=3e3,fr=()=>{var e;try{return JSON.parse((e=O().storage.getString(hn))!=null?e:"{}")}catch{return{}}},x=ze({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),An=e=>{var t;return!!((t=O().manual_update)!=null&&t.includes(e))},Ke=new Set,wn=e=>{let t=new Set,n=()=>O().storage.setString(e,JSON.stringify([...t]));return{has:r=>t.has(r),values:()=>[...t],add:r=>t.has(r)?!1:(t.add(r),n(),!0),delete:r=>t.delete(r)?(n(),!0):!1,load:()=>{var r;t.clear();try{let i=JSON.parse((r=O().storage.getString(e))!=null?r:"[]");Array.isArray(i)&&i.forEach(o=>{typeof o=="string"&&t.add(o)})}catch{}}}},Q=wn(lr),ge=wn(ur);Et(()=>{Q.load(),ge.load();let e=fr(),t={};Object.keys(e).filter(n=>!ge.has(n)).forEach(n=>{let r=P(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:Q.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),x.setState({catalog:e,downloads:t})});var mt=e=>Z(x,t=>e?t.downloads[e]:void 0),hr=()=>Z(x,e=>e.pause_reasons.length>0),G=(...e)=>W("queue",...e),L=[],se={},b=null,We=new Set,ye={},gt=new Set,ue=e=>{gt.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Ar=e=>(gt.add(e),()=>{gt.delete(e)}),wr=()=>x.getState().downloads,V=(e,t)=>{let n=!!P(e),r=x.getState().downloads[e],i=t.status==="downloading"&&n?"updating":t.status,o={...r!=null?r:{status:"queued",progress:0},...t,...i?{status:i}:{},has_local:n};x.setState(c=>({downloads:{...c.downloads,[e]:o}})),(r==null?void 0:r.status)!==o.status||(r==null?void 0:r.version)!==o.version||(r==null?void 0:r.has_local)!==o.has_local?ue({type:"status_change",app_id:e,state:o}):r.progress!==o.progress&&ue({type:"progress",app_id:e,progress:o.progress,version:o.version})},Je=(e,t)=>{var n;(n=ye[e])==null||n.forEach(r=>r(t)),delete ye[e]},yr=()=>x.getState().pause_reasons.length>0,de=e=>{var p;if(b)return;let t=e?L.indexOf(e):yr()?-1:L.findIndex(a=>!Q.has(a));if(t<0||t>=L.length)return;let[n]=L.splice(t,1),r=x.getState().catalog[n];if(!r){Je(n,P(n)),de();return}let i=Date.now();se[n]=((p=se[n])!=null?p:0)+1,V(n,{status:"downloading",progress:0,version:r.version,error:void 0});let o=0,c=dt(r,{onProgress:a=>{let s=Math.floor(a*100);s!==o&&(o=s,V(n,{progress:s/100,version:r.version}))}});b={app_id:n,handle:c,forced:!!e},G("start",n,r.version,e?"(forced)":""),c.promise.then(a=>{G("installed",n,r.version,`${Date.now()-i}ms`),V(n,{status:"installed",progress:1,version:r.version}),Je(n,a)}).catch(a=>{var d;if(a instanceof Se){if(We.has(n))return;G("paused",n),se[n]-=1,L.unshift(n),V(n,{status:Q.has(n)?"paused":"queued",progress:0,version:r.version});return}let s=String((d=a==null?void 0:a.message)!=null?d:a);if(console.warn("[miniapp-queue] failed",n,s),se[n]<gr){V(n,{status:"queued",progress:0,version:r.version,error:s}),setTimeout(()=>{var g;L.includes(n)||(b==null?void 0:b.app_id)===n||(L.push(n),de((g=ye[n])!=null&&g.length?n:void 0))},mr);return}V(n,{status:"failed",progress:0,version:r.version,error:s}),Je(n,P(n))}).finally(()=>{b=null;let a=L.find(s=>{var d;return(d=ye[s])==null?void 0:d.length});de(a)})},Ye=(e,{front:t=!1}={})=>{if((b==null?void 0:b.app_id)===e)return;let n=L.indexOf(e);if(n>=0){if(!t)return;L.splice(n,1)}t?L.unshift(e):L.push(e)},Mr=async e=>{let{host_id:t,client_token:n}=O(),r=new AbortController,i=setTimeout(()=>r.abort(),dr);try{let o=`${et}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,c=await fetch(o,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!c.ok)throw new Error(`host list ${e} ${c.status}`);return(await c.json()).apps.map(a=>({...a,channel:e}))}finally{clearTimeout(i)}},ke=null,ft=()=>(ke!=null||(ke=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(O().channels.map(Mr)),r={};[...n].reverse().flat().forEach(a=>{r[a.app_id]=a});let i=Object.keys(x.getState().catalog).filter(a=>!r[a]);O().storage.setString(hn,JSON.stringify(r)),x.setState({catalog:r}),await Promise.all(i.map(a=>yn(a,{by_user:!1}))),i.forEach(a=>ge.delete(a));let o=Object.keys(r).filter(a=>!ge.has(a)),c=[],p={};for(let a of o.map(s=>r[s])){if(await ut(a)){V(a.app_id,{status:"installed",progress:1,version:a.version});continue}let s=P(a.app_id);if(An(a.app_id)&&!Ke.has(a.app_id)&&s&&await oe(s)){V(a.app_id,{status:"installed",progress:1,version:s.version}),p[a.app_id]={app_id:a.app_id,current_version:s.version,next_version:a.version};continue}c.push(a)}return x.setState({updates:p}),c.forEach(a=>{se[a.app_id]=0,V(a.app_id,{status:Q.has(a.app_id)?"paused":"queued",progress:0,version:a.version,error:void 0}),Ye(a.app_id)}),G("catalog",o.length,"apps, outdated",c.map(a=>a.app_id),"removed",i,`${Date.now()-e}ms`),ue({type:"sync_complete",app_ids:o,removed:i}),Object.values(p).forEach(a=>ue({type:"update_available",...a})),de(),{ok:!0,app_ids:o,removed:i}}catch(n){let r=String((n==null?void 0:n.name)==="AbortError"?"timeout":(t=n==null?void 0:n.message)!=null?t:n);return console.warn("[miniapp-queue] sync catalog failed",r),ue({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ke=null}})()),ke),yn=async(e,{by_user:t})=>{var i,o,c,p;if(t&&ge.add(e),We.has(e))return;We.add(e),Q.delete(e);let n=L.indexOf(e);n>=0&&L.splice(n,1),(b==null?void 0:b.app_id)===e&&b.handle.cancel();let r=(p=(c=(i=x.getState().downloads[e])==null?void 0:i.version)!=null?c:(o=P(e))==null?void 0:o.version)!=null?p:"";V(e,{status:"uninstalling",progress:0,version:r}),await un(e),He(e),x.setState(a=>{let s={...a.downloads};return delete s[e],{downloads:s}}),delete se[e],We.delete(e),Je(e,null),G("uninstalled",e,t?"(user)":"(not in list)"),ue({type:"uninstalled",app_id:e})},vr=e=>yn(e,{by_user:!0}),Sr=e=>{let t=Ie(e);return t?(ge.delete(e),(b==null?void 0:b.app_id)===e||L.includes(e)||(se[e]=0,V(e,{status:Q.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Ye(e),de(),G("restore",e)),!0):!1},_r=e=>{if(Q.has(e))return;if(Q.add(e),G("pause app",e),(b==null?void 0:b.app_id)===e&&!b.forced){b.handle.cancel();return}let t=x.getState().downloads[e];L.includes(e)&&t&&V(e,{status:"paused",progress:0,version:t.version})},br=e=>{if(!Q.delete(e))return;G("resume app",e);let t=x.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!L.includes(e)&&Ie(e)&&(se[e]=0,Ye(e)),L.includes(e)&&t&&V(e,{status:"queued",progress:0,version:t.version}),de()},xr=e=>{let{pause_reasons:t}=x.getState();t.includes(e)||(x.setState({pause_reasons:[...t,e]}),G("pause",e),t.length===0&&ue({type:"pause_change",paused:!0,reasons:[e]}),b&&!b.forced&&b.handle.cancel())},Er=e=>{let{pause_reasons:t}=x.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);x.setState({pause_reasons:n}),G("resume",e),n.length===0&&ue({type:"pause_change",paused:!1,reasons:n}),de()},Mn=e=>x.getState().updates[e],Pr=async e=>{var n,r;let t=Mn(e);Ke.add(e);try{let i=await Ge(e),o=(r=t==null?void 0:t.next_version)!=null?r:(n=Ie(e))==null?void 0:n.version;return!i||!o||i.version!==o?!1:(x.setState(c=>{var a;let p={...c.updates};return delete p[e],{updates:p,apply_ticks:{...c.apply_ticks,[e]:((a=c.apply_ticks[e])!=null?a:0)+1}}}),G("updated",e,t==null?void 0:t.current_version,"\u2192",i.version),!0)}finally{Ke.delete(e)}},Rr=()=>Object.values(x.getState().catalog).map(e=>({...e,installed:!!P(e.app_id),removed_by_user:ge.has(e.app_id)})),Ie=e=>x.getState().catalog[e],Ge=async e=>{let t=Ie(e);if(!t)return;if(Q.delete(e),ge.delete(e),await ut(t))return P(e);let n=P(e);if(An(e)&&!Ke.has(e)&&n&&await oe(n))return n;let r=new Promise(i=>{var o;((o=ye[e])!=null?o:ye[e]=[]).push(i)});return(b==null?void 0:b.app_id)===e?b.forced=!0:(se[e]=0,Ye(e,{front:!0}),b&&!b.forced?b.handle.cancel():de(e)),r};import{Fragment as bn,jsx as N,jsxs as De}from"react/jsx-runtime";var At=e=>(e!=null?e:"").replace(/\?[^#]*/,""),Sn=0,Dr=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Nr=Mt.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:i,web_at_top:o,splash:c,bridge:p,opaque_background:a,allow_embedded_miniapps:s,onWebLoadEnd:d})=>{var St,_t;let g=X(null),A=X(!1),l=Z(B,m=>m.instances[e]),h=l==null?void 0:l.app.app_id,E=l==null?void 0:l.app.manifest_url,S=l==null?void 0:l.context,_=l==null?void 0:l.url_params,[f,C]=Me(()=>h?P(h):null),[K,U]=Me(!1),[ve,ae]=Me(0),[w,v]=Me(0),[j,M]=Me(!1),k=X(null),ee=m=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{k.current=null,M(!0)},m)};q(()=>()=>{k.current&&clearTimeout(k.current)},[]),q(()=>{if(!h||!t&&f)return;let m=!0;return U(!1),(async()=>{let y=P(h),$=y?await oe(y):!1;if(!m||(C($?Y=>!Y||Y.version!==y.version||Y.permissions.join(",")!==y.permissions.join(",")?y:Y:null),__DEV__&&Date.now()-Sn>1e4&&(Sn=Date.now(),await ft()),!m))return;let pe=await Ge(h),fe=pe!==void 0?pe:E?await gn(h,E):P(h);if(m){if(!fe){U(!0);return}C(Y=>Y!=null?Y:fe)}})(),()=>{m=!1}},[t,h,E,ve]),q(()=>mn(e,m=>g.current?(g.current.postMessage(m),!0):!1),[e]);let F=Z(x,m=>{let y=h?m.downloads[h]:void 0;return(y==null?void 0:y.status)==="installed"?y.version:void 0});q(()=>{if(t||!h||!f)return;let m=P(h);if(!m||m.version===f.version)return;let y=!0;return oe(m).then($=>{!y||!$||(W(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",f.version,"\u2192",m.version),C(m))}),()=>{y=!1}},[t,h,F,f==null?void 0:f.version]);let R=Z(x,m=>{var y;return h&&(y=m.apply_ticks[h])!=null?y:0});q(()=>{if(!R||!h)return;let m=P(h);if(!m||m.version===(f==null?void 0:f.version))return;let y=!0;return oe(m).then($=>{!y||!$||(W(`webview:${e}`,"c\u1EADp nh\u1EADt",f==null?void 0:f.version,"\u2192",m.version),M(!1),C(m))}),()=>{y=!1}},[R]),q(()=>{var $;let m=($=O().keep_alive)==null?void 0:$.idle_close_ms;if(t||!m||m<=0)return;let y=setTimeout(()=>{He(e)},m);return()=>clearTimeout(y)},[t,e]),q(()=>{i>0&&(U(!1),M(!1),v(m=>m+1),ae(m=>m+1))},[i]);let z=X(t);q(()=>{var m;z.current!==t&&(z.current=t,A.current&&((m=g.current)==null||m.injectJavaScript(tn(t?"resumed":"paused"))))},[t]);let ce=`${(St=f==null?void 0:f.version)!=null?St:"none"}:${(_t=f==null?void 0:f.permissions.join(","))!=null?_t:""}:${w}`,me=Qe(()=>JSON.stringify([S!=null?S:{},_!=null?_:{}]),[S,_]),te=Qe(()=>{var m;return an(_!=null?_:{},(m=f==null?void 0:f.permissions)!=null?m:[])},[me,f==null?void 0:f.permissions]),Xe=Qe(()=>on(S!=null?S:{},te)+Zt()+(kr.OS==="android"?en():"")+(O().debug?Xt():""),[te]),ne=X(null),Ne=X(null);q(()=>{var y,$,pe;if(!f)return;if(Ne.current!==ce){Ne.current=ce,ne.current=me;return}if(ne.current===me)return;let m=(($=JSON.parse((y=ne.current)!=null?y:"[]")[0])!=null?$:{}).org_id;if(ne.current=me,m===(S==null?void 0:S.org_id)&&A.current){M(!1),ee(1500),(pe=g.current)==null||pe.injectJavaScript(nn(S!=null?S:{},te));return}M(!1),v(fe=>fe+1)},[me,f,ce]),q(()=>(t||(ie(e),we(e)),()=>{ie(e),we(e)}),[t,e,ce,i]),q(()=>{let m=vn.addEventListener("change",y=>{y==="background"&&ie(e)});return()=>m.remove()},[e]);let Ue=wt(async m=>{var $,pe,fe,Y,Ze;let y=Kt(m.nativeEvent.data);if(!y){if(h&&(p!=null&&p.onWebEvent))try{Promise.resolve(p.onWebEvent(m.nativeEvent.data,{app_id:h,instance_id:e})).catch(T=>{console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)})}catch(T){console.warn("[miniapp] onWebEvent l\u1ED7i",h,T)}return}if(y.method==="log"){let{level:T,text:D}=y;W(`web:${e}`,T!=null?T:"log",D!=null?D:"");return}if(y.method==="pong"){k.current||M(!0);return}if(y.method==="touchAtTop"){o.emit(!!y.at_top);return}if(y.method==="contextApplied"){k.current&&clearTimeout(k.current),k.current=null,M(!0);return}if(y.method==="ready"){A.current=!0,M(!0);let T=($=B.getState().instances[e])==null?void 0:$.context;T&&((pe=g.current)==null||pe.injectJavaScript(ot(T)));return}try{let T=await cn(y,{getHostData:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.host_data)!=null?H:{}},getPermissions:()=>{var D,H;return h?(H=(D=P(h))==null?void 0:D.permissions)!=null?H:[]:[]},getContext:()=>{var D,H;return(H=(D=B.getState().instances[e])==null?void 0:D.context)!=null?H:{}},is_dark:r,close:Ce,app_id:h!=null?h:"",instance_id:e,options:p,emit:(D,H)=>{var bt;(bt=g.current)==null||bt.injectJavaScript(Qt(D,H))},isActive:()=>B.getState().active_key===e&&vn.currentState!=="background"});y.id&&((fe=g.current)==null||fe.injectJavaScript(Yt(y.id,T)))}catch(T){if(!y.id)return;let D=T==null?void 0:T.code,H=T instanceof u?T:new u(typeof D=="string"?D:"HOST_ERROR",String((Y=T==null?void 0:T.message)!=null?Y:T));(Ze=g.current)==null||Ze.injectJavaScript(Gt(y.id,H))}},[e,r,h,o,p]),En=wt(()=>{U(!1),v(m=>m+1),ae(m=>m+1)},[]);return De(yt,{style:[vt.absoluteFill,a&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&J.behind],pointerEvents:t?"auto":"none",children:[f?N(Lr,{ref:g,source:{uri:f.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${s?ct():f.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:Xe,onMessage:Ue,bounces:!1,overScrollMode:"never",onLoadStart:m=>{ie(e),we(e),W(`webview:${e}`,"load start",At(m.nativeEvent.url)),A.current=!1,M(!1)},onError:m=>{ie(e),we(e),W(`webview:${e}`,"load error",At(m.nativeEvent.url),m.nativeEvent.description),U(!0),M(!1)},onLoadEnd:m=>{let y=m.nativeEvent.url;W(`webview:${e}`,"load end",At(y)),h&&(d==null||d({app_id:h,instance_id:e,url:y})),ee(1500)},onContentProcessDidTerminate:()=>{ie(e),we(e),A.current=!1,M(!1),v(m=>m+1)},onRenderProcessGone:()=>(ie(e),we(e),A.current=!1,M(!1),v(m=>m+1),!0),style:J.webview},ce):null,l&&N(Fr,{visible:!f||!j,interactive:K,children:N(Ur,{splash:c,app:l.app,is_dark:r,error:K,has_bundle:!!f,retry:En})})]})}),Ur=Mt.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:i,retry:o})=>{let c=e,p=mt(t.app_id),a=r?"error":!i&&(p==null?void 0:p.status)==="downloading"?"downloading":"loading";return N(c,{app:t,is_dark:n,status:a,progress:a==="downloading"?p==null?void 0:p.progress:void 0,retry:o})}),Fr=({visible:e,interactive:t,children:n})=>{let r=X(new ht.Value(e?1:0)).current,[i,o]=Me(e);return q(()=>{if(e){o(!0),r.setValue(1);return}let c=ht.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return c.start(({finished:p})=>{p&&o(!1)}),()=>c.stop()},[e,r]),i?N(ht.View,{style:[vt.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},xn=({app:e,is_dark:t,status:n,progress:r,retry:i})=>{let o=t?"#FAFAFA":"#18181B";return De(yt,{style:[J.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[N(yt,{style:[J.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?N(Cr,{source:{uri:e.icon},style:J.splash_icon_image}):N(Le,{style:J.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),N(Le,{style:[J.splash_name,{color:o}],children:e.name}),n==="error"?De(bn,{children:[N(Le,{style:J.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),N(Ir,{activeOpacity:.7,style:[J.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:i,children:N(Le,{style:[J.retry_text,{color:o}],children:"Th\u1EED l\u1EA1i"})})]}):De(bn,{children:[N(Or,{style:J.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&De(Le,{style:J.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},_n=(e,t)=>{let n=X(t),r=X(!1);__DEV__&&!r.current&&n.current!==t&&(r.current=!0,console.warn(`[miniapp] MiniAppHost prop "${e}" \u0111\u1ED5i gi\u1EEFa c\xE1c l\u1EA7n render \u2192 m\u1ECDi WebView b\u1ECB mount l\u1EA1i. Khai b\xE1o component b\xEAn ngo\xE0i render.`))},$r=({container:e,splash:t=xn,is_dark:n=!1,bridge:r,close_on_back:i=!0,opaque_background:o=!0,allow_embedded_miniapps:c=!1,onWebLoadEnd:p})=>{_n("container",e),_n("splash",t);let a=e,s=Z(B,f=>f.active_key),d=X(s);s&&(d.current=s);let g=Z(B,f=>Object.keys(f.instances).join("|")),A=Z(B,f=>{var C;return f.active_key?(C=f.instances[f.active_key])==null?void 0:C.app.name:void 0}),l=Qe(()=>g?g.split("|"):[],[g]),[h,E]=Me({}),S=X(Dr()).current;q(()=>{if(!s||!i)return;let f=Tr.addEventListener("hardwareBackPress",()=>(Ce(),!0));return()=>f.remove()},[s,i]);let _=wt(()=>{let f=B.getState().active_key;f&&E(C=>({...C,[f]:(C[f]||0)+1}))},[]);return l.length?N(a,{visible:!!s,title:A!=null?A:"",is_dark:n,close:Ce,reload:_,subscribeWebAtTop:S.subscribe,children:l.map(f=>N(Nr,{instance_key:f,is_active:s===f,is_front:(s!=null?s:d.current)===f,is_dark:n,reload_tick:h[f]||0,web_at_top:S,splash:t,bridge:r,opaque_background:o,allow_embedded_miniapps:c,onWebLoadEnd:p},f))}):null},J=vt.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"}}),Br=Mt.memo($r);export{xn as DefaultMiniAppSplash,et as MINIAPP_PLATFORM_URL,Br as MiniAppHost,u as MiniAppHostError,Ce as closeMiniApp,Pn as configureMiniApp,On as createMmkvStorage,Pt as createReactNativeBiometrics,Rn as createRnfsFileSystem,Ge as ensureMiniApp,P as getLocalMiniApp,Rr as getMiniAppCatalog,Ie as getMiniAppCatalogEntry,wr as getMiniAppStatuses,Mn as getMiniAppUpdate,rr as installBundledMiniApp,Ar as onMiniAppEvent,cr as openMiniApp,_r as pauseMiniApp,xr as pauseMiniAppDownloads,pr as preloadMiniApp,ie as releaseSpeechFor,Sr as restoreMiniApp,br as resumeMiniApp,Er as resumeMiniAppDownloads,or as sendEventToWeb,ft as syncMiniAppCatalog,vr as uninstallMiniApp,Pr as updateMiniApp,$t as uploadToUrl,mt as useMiniAppDownload,hr as useMiniAppDownloadsPaused};
|
package/docs/MINIAPP_README.md
CHANGED
|
@@ -551,7 +551,7 @@ Mount **1 lần** ở gốc app, không unmount.
|
|
|
551
551
|
| `container` | ✓ | Layout bao ngoài — nhận `MiniAppContainerProps` |
|
|
552
552
|
| `splash` | | Màn che lúc khởi động / đang tải / lỗi — nhận `MiniAppSplashProps`. Mặc định có sẵn |
|
|
553
553
|
| `is_dark` | | Theme, mặc định `false` |
|
|
554
|
-
| `bridge` | | `{ handlers, upload, showToast, haptic, openUrl, app_version, onWebEvent }` — `openUrl` dùng cho `openWebview` / `openLink`; `upload`
|
|
554
|
+
| `bridge` | | `{ handlers, upload, showToast, haptic, openUrl, app_version, onWebEvent }` — `openUrl` dùng cho `openWebview` / `openLink`; `upload` tuỳ chọn: chỉ cần khai báo đích `host` (API upload của app) cho `uploadFiles` (xem [Upload file](#upload-file-uploadfiles)) |
|
|
555
555
|
| `close_on_back` | | Nút Back (Android) đóng mini app. Mặc định `true`; `false` khi mini app là nội dung chính của màn / tab |
|
|
556
556
|
| `opaque_background` | | Tô nền đặc (trắng / `#09090B` theo `is_dark`) dưới mỗi WebView → web không tô nền không lộ mini app chạy ngầm phía sau. Mặc định `true`; `false` để nền trong suốt (container tự lo nền) |
|
|
557
557
|
| `allow_embedded_miniapps` | | Mini app được nhúng mini app khác bằng iframe nạp bản trong máy (`getLocalMiniApp(app_id).entry_uri`) — vd Sảnh mở app con offline. iOS cho WebView đọc cả thư mục `miniapps/`. Mặc định `false` |
|
|
@@ -613,7 +613,7 @@ Mount **1 lần** ở gốc app, không unmount.
|
|
|
613
613
|
|
|
614
614
|
## Tích hợp API native
|
|
615
615
|
|
|
616
|
-
Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.
|
|
616
|
+
Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.1`; web dùng `@retion-miniapp/sdk@0.8.0` trở lên (upload file cần cả hai bản 0.10.0). Package tự xử lý các tính năng này qua bridge chung, không phụ thuộc Chat SDK và không cần gắn handler riêng.
|
|
617
617
|
|
|
618
618
|
### Thiết lập app chủ
|
|
619
619
|
|
|
@@ -680,7 +680,7 @@ Android: kiểm tra manifest sau khi hợp nhất có cấu hình tương đươ
|
|
|
680
680
|
</queries>
|
|
681
681
|
```
|
|
682
682
|
|
|
683
|
-
Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation
|
|
683
|
+
Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation, image-picker, document picker và compressor vào `react-native.config.js`, giữ các cấu hình khác:
|
|
684
684
|
|
|
685
685
|
```js
|
|
686
686
|
const path = require('path');
|
|
@@ -701,11 +701,21 @@ module.exports = {
|
|
|
701
701
|
paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
|
|
702
702
|
})),
|
|
703
703
|
},
|
|
704
|
+
'@react-native-documents/picker': {
|
|
705
|
+
root: path.dirname(require.resolve('@react-native-documents/picker/package.json', {
|
|
706
|
+
paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
|
|
707
|
+
})),
|
|
708
|
+
},
|
|
709
|
+
'react-native-compressor': {
|
|
710
|
+
root: path.dirname(require.resolve('react-native-compressor/package.json', {
|
|
711
|
+
paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
|
|
712
|
+
})),
|
|
713
|
+
},
|
|
704
714
|
},
|
|
705
715
|
};
|
|
706
716
|
```
|
|
707
717
|
|
|
708
|
-
Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0
|
|
718
|
+
Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0**, image-picker **8.2.1**, document picker **12.0.2** và compressor **1.13.0**. Không cài nhiều phiên bản native khác nhau; không xoá dependency trực tiếp nếu tính năng khác của app còn dùng. Với Expo 57, giữ bản vá `expo-speech-recognition@1.1.1` đang dùng trong Retion để sửa kiểu resolver Swift trước khi build.
|
|
709
719
|
|
|
710
720
|
Cài package/plugin không sửa binary đã cài. Nếu thiếu module hoặc quyền, phải build/cài lại; OTA và reload không bổ sung native. Nếu binary đã đủ module/quyền tương thích, thay đổi JavaScript có thể chỉ cần reload.
|
|
711
721
|
|
|
@@ -901,60 +911,30 @@ const { files, failed } = await uploadFiles({
|
|
|
901
911
|
|
|
902
912
|
`target: 'url'` chỉ nhận https, gửi multipart POST và đọc link ở `url_field` (dạng `a.b.c`) trong JSON trả về.
|
|
903
913
|
|
|
904
|
-
**App ch
|
|
914
|
+
**App chủ: không cần cấu hình.** Cài package, build lại native là có ngay:
|
|
905
915
|
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
916
|
+
| Có sẵn | Thư viện (package tự cài) |
|
|
917
|
+
| --- | --- |
|
|
918
|
+
| Nguồn `library`, `camera` | `react-native-image-picker` 8.2.1 |
|
|
919
|
+
| Nguồn `document` (mọi loại file: Files, iCloud, Drive…) | `@react-native-documents/picker` 12.0.2. Android tự copy `content://` ra file cục bộ |
|
|
920
|
+
| Nén ảnh (khi web truyền `process.image`, bỏ qua PNG/GIF) và nén video (luôn, mặc định `medium`) | `react-native-compressor` 1.13.0. Nén lỗi → upload bản gốc |
|
|
921
|
+
| Đích `url` (server của mini app) | Có sẵn |
|
|
909
922
|
|
|
923
|
+
**Chỉ một thứ do app quyết định: đích `host`.** Đây là API upload của chính app (domain, token, storage riêng), package không đoán được. App không khai báo thì web gọi `target: 'host'` nhận `NOT_SUPPORTED` và dùng `target: 'url'`. Muốn bật thì truyền một hàm upload, thường tái dùng hàm upload sẵn có của app:
|
|
924
|
+
|
|
925
|
+
```tsx
|
|
910
926
|
<MiniAppHost bridge={{ upload: {
|
|
911
|
-
sources: {
|
|
912
|
-
// Có sẵn: library, camera (react-native-image-picker 8.2.1). Ghi đè theo tên, hoặc null để tắt.
|
|
913
|
-
document: createDocumentPickerSource(DocumentPicker), // mọi loại file
|
|
914
|
-
library: async ({ accept, max_count, process }) => [/* UI gallery riêng của app */],
|
|
915
|
-
},
|
|
916
|
-
processors: {
|
|
917
|
-
// Chạy cho file nguồn chưa tự nén (processed !== true), vd react-native-compressor.
|
|
918
|
-
image: async (file, { image }) => ({ ...file, uri: compressedUri, size }),
|
|
919
|
-
video: async (file, { video }) => ({ ...file, uri: compressedUri, size }),
|
|
920
|
-
},
|
|
921
927
|
targets: {
|
|
922
|
-
|
|
923
|
-
|
|
928
|
+
host: async ({ file, onProgress, signal, caller }) => {
|
|
929
|
+
// file: { uri, name, mime_type, size? } — đã nén; caller.context: context lúc openMiniApp (vd page_id)
|
|
930
|
+
const url = await myAppUpload(file, caller.context.page_id, onProgress, signal);
|
|
931
|
+
return { url }; // trường thêm → web nhận trong response
|
|
932
|
+
},
|
|
924
933
|
},
|
|
925
934
|
} }} />
|
|
926
935
|
```
|
|
927
936
|
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
`MiniAppUploadOptions`: giá trị của `bridge.upload`
|
|
931
|
-
|
|
932
|
-
| Prop | Type | Mô tả |
|
|
933
|
-
| --- | --- | --- |
|
|
934
|
-
| `sources` | `Record<string, MiniAppUploadSource \| null>` | Thêm / ghi đè nguồn theo tên. Có sẵn `library`, `camera`; `null` để tắt một nguồn có sẵn |
|
|
935
|
-
| `processors` | `{ image?: MiniAppUploadProcessor; video?: MiniAppUploadProcessor }` | Nén file mà nguồn chưa tự nén (`processed !== true`) |
|
|
936
|
-
| `targets` | `Record<string, MiniAppUploader>` | Đích upload theo tên, vd `host`. Có sẵn `url`, không ghi đè được |
|
|
937
|
-
|
|
938
|
-
| Type | Chữ ký / dạng |
|
|
939
|
-
| --- | --- |
|
|
940
|
-
| `MiniAppUploadSource` | `(request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>`. Người dùng huỷ → trả `[]` |
|
|
941
|
-
| `MiniAppUploadSourceRequest` | `{ accept: string[]; max_count: number; process: MiniAppUploadProcessOptions }` |
|
|
942
|
-
| `MiniAppUploadProcessor` | `(file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>` |
|
|
943
|
-
| `MiniAppUploadProcessOptions` | `{ image?: { max_width?, max_height?, quality? }; video?: { max_duration?, quality? } }` |
|
|
944
|
-
| `MiniAppPickedFile` | `{ uri: string; name: string; mime_type: string; size?: number; width?: number; height?: number; duration?: number; processed?: boolean }` |
|
|
945
|
-
| `MiniAppUploader` | `(request: MiniAppUploadRequest) => Promise<{ url: string; [key: string]: unknown }>`. Trường thêm → web nhận trong `response` |
|
|
946
|
-
| `MiniAppUploadRequest` | `{ file: MiniAppPickedFile; target: MiniAppUploadTarget; onProgress: (loaded, total) => void; signal: AbortSignal }` |
|
|
947
|
-
| `MiniAppUploadTarget` | `{ target: string; params: Record<string, unknown> }` hoặc `MiniAppUrlUploadTarget` |
|
|
948
|
-
| `MiniAppUrlUploadTarget` | `{ target: 'url'; url; headers; form_data; field_name; url_field }` |
|
|
949
|
-
|
|
950
|
-
| Hàm | Mô tả |
|
|
951
|
-
| --- | --- |
|
|
952
|
-
| `createDocumentPickerSource(DocumentPicker)` | Nguồn mọi loại file từ `@react-native-documents/picker` (app tự cài). Map `accept` sang loại của picker; `accept` lạ → mở toàn bộ file rồi lọc lại |
|
|
953
|
-
| `uploadToUrl` | Uploader multipart dùng cho đích `url`; dùng lại được trong uploader riêng |
|
|
954
|
-
|
|
955
|
-
- Nguồn: `(request: { accept, max_count, process }) => Promise<PickedFile[]>`, huỷ trả `[]`. Lõi tự lọc lại theo `accept` sau khi chọn, nên nguồn chỉ cần dùng `accept` làm gợi ý.
|
|
956
|
-
- `react-native-image-picker` đã nén ảnh (và video trên iOS) nên bỏ qua processor; video Android vẫn qua `processors.video` nếu có.
|
|
957
|
-
- `max_size` kiểm tra sau khi xử lý.
|
|
937
|
+
`bridge.upload` còn cho ghi đè nếu thật sự cần (không bắt buộc): `sources` (thay / thêm nguồn theo tên, `null` để tắt), `processors` (`image` / `video`, thay bộ nén có sẵn).
|
|
958
938
|
|
|
959
939
|
Plugin Expo thêm `NSPhotoLibraryUsageDescription` / `NSCameraUsageDescription` (tuỳ chỉnh qua `photoLibraryPermission`, `cameraPermission`). Upload không bị huỷ khi app xuống nền (picker hệ thống làm app vào background); chỉ huỷ khi đóng / reload mini app.
|
|
960
940
|
|
package/docs/NATIVE_APIS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
## Tích hợp API native
|
|
2
2
|
|
|
3
|
-
Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.
|
|
3
|
+
Phần này hướng dẫn **Face ID / Touch ID**, **speech-to-text**, **vị trí hiện tại**, **upload file** và các API native do app chủ cung cấp. App chủ dùng `@retion-miniapp/react-native@0.10.1`; web dùng `@retion-miniapp/sdk@0.8.0` trở lên (upload cần cả hai bản 0.10.0). Package tự xử lý các tính năng này qua bridge chung, không phụ thuộc Chat SDK và không cần gắn handler riêng.
|
|
4
4
|
|
|
5
5
|
### Thiết lập app chủ
|
|
6
6
|
|
|
@@ -61,7 +61,7 @@ Android: kiểm tra manifest sau khi hợp nhất có cấu hình tương đươ
|
|
|
61
61
|
</queries>
|
|
62
62
|
```
|
|
63
63
|
|
|
64
|
-
Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation
|
|
64
|
+
Nếu CLI chỉ dò dependency trực tiếp, bổ sung liên kết biometric, geolocation, image-picker, document picker và compressor vào `react-native.config.js`, giữ các cấu hình khác:
|
|
65
65
|
|
|
66
66
|
```js
|
|
67
67
|
const path = require('path');
|
|
@@ -82,11 +82,21 @@ module.exports = {
|
|
|
82
82
|
paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
|
|
83
83
|
})),
|
|
84
84
|
},
|
|
85
|
+
'@react-native-documents/picker': {
|
|
86
|
+
root: path.dirname(require.resolve('@react-native-documents/picker/package.json', {
|
|
87
|
+
paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
|
|
88
|
+
})),
|
|
89
|
+
},
|
|
90
|
+
'react-native-compressor': {
|
|
91
|
+
root: path.dirname(require.resolve('react-native-compressor/package.json', {
|
|
92
|
+
paths: [path.dirname(require.resolve('@retion-miniapp/react-native/package.json'))],
|
|
93
|
+
})),
|
|
94
|
+
},
|
|
85
95
|
},
|
|
86
96
|
};
|
|
87
97
|
```
|
|
88
98
|
|
|
89
|
-
Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0
|
|
99
|
+
Expo ≥52 là yêu cầu khai báo, không đảm bảo mọi tổ hợp native đã được kiểm tra. Package ghim biometric **3.0.1**, speech **1.1.1**, geolocation **3.4.0**, image-picker **8.2.1**, document picker **12.0.2** và compressor **1.13.0**. Không cài nhiều phiên bản native khác nhau; không xoá dependency trực tiếp nếu tính năng khác của app còn dùng. Với Expo 57, giữ bản vá `expo-speech-recognition@1.1.1` đang dùng trong Retion để sửa kiểu resolver Swift trước khi build.
|
|
90
100
|
|
|
91
101
|
Cài package/plugin không sửa binary đã cài. Nếu thiếu module hoặc quyền, phải build/cài lại; OTA và reload không bổ sung native. Nếu binary đã đủ module/quyền tương thích, thay đổi JavaScript có thể chỉ cần reload.
|
|
92
102
|
|
|
@@ -414,59 +424,29 @@ const { files, failed } = await uploadFiles({
|
|
|
414
424
|
|
|
415
425
|
`target: 'url'` chỉ nhận https, gửi multipart POST và đọc link ở `url_field` (dạng `a.b.c`) trong JSON trả về.
|
|
416
426
|
|
|
417
|
-
**App ch
|
|
427
|
+
**App chủ: không cần cấu hình.** Cài package, build lại native là có ngay:
|
|
418
428
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
429
|
+
| Có sẵn | Thư viện (package tự cài) |
|
|
430
|
+
| --- | --- |
|
|
431
|
+
| Nguồn `library`, `camera` | `react-native-image-picker` 8.2.1 |
|
|
432
|
+
| Nguồn `document` (mọi loại file: Files, iCloud, Drive…) | `@react-native-documents/picker` 12.0.2. Android tự copy `content://` ra file cục bộ |
|
|
433
|
+
| Nén ảnh (khi web truyền `process.image`, bỏ qua PNG/GIF) và nén video (luôn, mặc định `medium`) | `react-native-compressor` 1.13.0. Nén lỗi → upload bản gốc |
|
|
434
|
+
| Đích `url` (server của mini app) | Có sẵn |
|
|
422
435
|
|
|
436
|
+
**Chỉ một thứ do app quyết định: đích `host`.** Đây là API upload của chính app (domain, token, storage riêng), package không đoán được. App không khai báo thì web gọi `target: 'host'` nhận `NOT_SUPPORTED` và dùng `target: 'url'`. Muốn bật thì truyền một hàm upload, thường tái dùng hàm upload sẵn có của app:
|
|
437
|
+
|
|
438
|
+
```tsx
|
|
423
439
|
<MiniAppHost bridge={{ upload: {
|
|
424
|
-
sources: {
|
|
425
|
-
// Có sẵn: library, camera (react-native-image-picker 8.2.1). Ghi đè theo tên, hoặc null để tắt.
|
|
426
|
-
document: createDocumentPickerSource(DocumentPicker), // mọi loại file
|
|
427
|
-
library: async ({ accept, max_count, process }) => [/* UI gallery riêng của app */],
|
|
428
|
-
},
|
|
429
|
-
processors: {
|
|
430
|
-
// Chạy cho file nguồn chưa tự nén (processed !== true), vd react-native-compressor.
|
|
431
|
-
image: async (file, { image }) => ({ ...file, uri: compressedUri, size }),
|
|
432
|
-
video: async (file, { video }) => ({ ...file, uri: compressedUri, size }),
|
|
433
|
-
},
|
|
434
440
|
targets: {
|
|
435
|
-
|
|
436
|
-
|
|
441
|
+
host: async ({ file, onProgress, signal, caller }) => {
|
|
442
|
+
// file: { uri, name, mime_type, size? } — đã nén; caller.context: context lúc openMiniApp (vd page_id)
|
|
443
|
+
const url = await myAppUpload(file, caller.context.page_id, onProgress, signal);
|
|
444
|
+
return { url }; // trường thêm → web nhận trong response
|
|
445
|
+
},
|
|
437
446
|
},
|
|
438
447
|
} }} />
|
|
439
448
|
```
|
|
440
449
|
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
`MiniAppUploadOptions`: giá trị của `bridge.upload`
|
|
444
|
-
|
|
445
|
-
| Prop | Type | Mô tả |
|
|
446
|
-
| --- | --- | --- |
|
|
447
|
-
| `sources` | `Record<string, MiniAppUploadSource \| null>` | Thêm / ghi đè nguồn theo tên. Có sẵn `library`, `camera`; `null` để tắt một nguồn có sẵn |
|
|
448
|
-
| `processors` | `{ image?: MiniAppUploadProcessor; video?: MiniAppUploadProcessor }` | Nén file mà nguồn chưa tự nén (`processed !== true`) |
|
|
449
|
-
| `targets` | `Record<string, MiniAppUploader>` | Đích upload theo tên, vd `host`. Có sẵn `url`, không ghi đè được |
|
|
450
|
-
|
|
451
|
-
| Type | Chữ ký / dạng |
|
|
452
|
-
| --- | --- |
|
|
453
|
-
| `MiniAppUploadSource` | `(request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>`. Người dùng huỷ → trả `[]` |
|
|
454
|
-
| `MiniAppUploadSourceRequest` | `{ accept: string[]; max_count: number; process: MiniAppUploadProcessOptions }` |
|
|
455
|
-
| `MiniAppUploadProcessor` | `(file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>` |
|
|
456
|
-
| `MiniAppUploadProcessOptions` | `{ image?: { max_width?, max_height?, quality? }; video?: { max_duration?, quality? } }` |
|
|
457
|
-
| `MiniAppPickedFile` | `{ uri: string; name: string; mime_type: string; size?: number; width?: number; height?: number; duration?: number; processed?: boolean }` |
|
|
458
|
-
| `MiniAppUploader` | `(request: MiniAppUploadRequest) => Promise<{ url: string; [key: string]: unknown }>`. Trường thêm → web nhận trong `response` |
|
|
459
|
-
| `MiniAppUploadRequest` | `{ file: MiniAppPickedFile; target: MiniAppUploadTarget; onProgress: (loaded, total) => void; signal: AbortSignal }` |
|
|
460
|
-
| `MiniAppUploadTarget` | `{ target: string; params: Record<string, unknown> }` hoặc `MiniAppUrlUploadTarget` |
|
|
461
|
-
| `MiniAppUrlUploadTarget` | `{ target: 'url'; url; headers; form_data; field_name; url_field }` |
|
|
462
|
-
|
|
463
|
-
| Hàm | Mô tả |
|
|
464
|
-
| --- | --- |
|
|
465
|
-
| `createDocumentPickerSource(DocumentPicker)` | Nguồn mọi loại file từ `@react-native-documents/picker` (app tự cài). Map `accept` sang loại của picker; `accept` lạ → mở toàn bộ file rồi lọc lại |
|
|
466
|
-
| `uploadToUrl` | Uploader multipart dùng cho đích `url`; dùng lại được trong uploader riêng |
|
|
467
|
-
|
|
468
|
-
- Nguồn: `(request: { accept, max_count, process }) => Promise<PickedFile[]>`, huỷ trả `[]`. Lõi tự lọc lại theo `accept` sau khi chọn, nên nguồn chỉ cần dùng `accept` làm gợi ý.
|
|
469
|
-
- `react-native-image-picker` đã nén ảnh (và video trên iOS) nên bỏ qua processor; video Android vẫn qua `processors.video` nếu có.
|
|
470
|
-
- `max_size` kiểm tra sau khi xử lý.
|
|
450
|
+
`bridge.upload` còn cho ghi đè nếu thật sự cần (không bắt buộc): `sources` (thay / thêm nguồn theo tên, `null` để tắt), `processors` (`image` / `video`, thay bộ nén có sẵn).
|
|
471
451
|
|
|
472
452
|
Plugin Expo thêm `NSPhotoLibraryUsageDescription` / `NSCameraUsageDescription` (tuỳ chỉnh qua `photoLibraryPermission`, `cameraPermission`). Upload không bị huỷ khi app xuống nền (picker hệ thống làm app vào background); chỉ huỷ khi đóng / reload mini app.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@retion-miniapp/react-native",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.1",
|
|
4
4
|
"description": "React Native host for Retion Mini Apps with built-in biometric authentication",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -89,8 +89,10 @@
|
|
|
89
89
|
},
|
|
90
90
|
"dependencies": {
|
|
91
91
|
"@react-native-community/geolocation": "3.4.0",
|
|
92
|
+
"@react-native-documents/picker": "12.0.2",
|
|
92
93
|
"expo-speech-recognition": "1.1.1",
|
|
93
94
|
"react-native-biometrics": "3.0.1",
|
|
95
|
+
"react-native-compressor": "1.13.0",
|
|
94
96
|
"react-native-image-picker": "8.2.1"
|
|
95
97
|
}
|
|
96
98
|
}
|