@retion-miniapp/react-native 0.9.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 CHANGED
@@ -1,11 +1,11 @@
1
1
  # Retion Mini App cho React Native
2
2
 
3
- Package chạy mini app web trong app React Native: tải bundle, lưu cục bộ, quản lý WebView và cung cấp API native qua bridge chung. Từ **0.8.0**, Face ID / Touch ID và nhận dạng giọng nói được xử lý trong package; app chủ không cần gắn handler riêng cho các API này.
3
+ Package chạy mini app web trong app React Native: tải bundle, lưu cục bộ, quản lý WebView và cung cấp API native qua bridge chung. Từ **0.8.0**, Face ID / Touch ID và nhận dạng giọng nói (từ **0.9.0** thêm vị trí hiện tại, từ **0.10.0** thêm upload file) được xử lý trong package; app chủ không cần gắn handler riêng cho các API này.
4
4
 
5
5
  ## Đọc theo thứ tự
6
6
 
7
7
  1. [Cài đặt, cấu hình và mở mini app](docs/MINIAPP_README.md).
8
- 2. [Tích hợp API native: Face ID / Touch ID và speech-to-text](docs/NATIVE_APIS.md).
8
+ 2. [Tích hợp API native: Face ID / Touch ID, speech-to-text, vị trí hiện tại và upload file](docs/NATIVE_APIS.md).
9
9
  3. [Nhận dạng giọng nói: quyền, hoạt động, API và quản lý phiên](docs/SPEECH.md).
10
10
  4. [Face ID / Touch ID: quyền, API và kết quả native](docs/BIOMETRICS.md).
11
11
 
@@ -14,7 +14,7 @@ Package chạy mini app web trong app React Native: tải bundle, lưu cục b
14
14
  | Thành phần | Trách nhiệm |
15
15
  | --- | --- |
16
16
  | App chủ | Cài package, cấu hình quyền và liên kết native, build ứng dụng, cấu hình dữ liệu mini app và mount `MiniAppHost` |
17
- | Mini App React Native | Tải/chạy mini app; thực hiện xác thực sinh trắc học, xin quyền speech, quản lý micro và chuyển kết quả/event về đúng WebView |
17
+ | Mini App React Native | Tải/chạy mini app; thực hiện xác thực sinh trắc học, lấy vị trí, chọn và upload file, xin quyền speech/vị trí, quản lý micro và chuyển kết quả/event về đúng WebView |
18
18
  | Web SDK `@retion-miniapp/sdk` | Cung cấp API Promise và đăng ký event cho mini app web |
19
19
  | Mini app web | Gọi API khi người dùng thao tác, kiểm tra kết quả/lỗi và cập nhật giao diện |
20
20
 
@@ -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.8.1 + Web SDK 0.8.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.
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` và `expo-speech-recognition@1.1.1`. 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).
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/app.plugin.js CHANGED
@@ -10,6 +10,12 @@ module.exports = function withMiniApp(config, options = {}) {
10
10
  config.modResults.NSLocationWhenInUseUsageDescription = options.locationPermission
11
11
  || config.modResults.NSLocationWhenInUseUsageDescription
12
12
  || 'Allow this app to access your location while you use it.';
13
+ config.modResults.NSPhotoLibraryUsageDescription = options.photoLibraryPermission
14
+ || config.modResults.NSPhotoLibraryUsageDescription
15
+ || 'Allow this app to access your photos to upload them.';
16
+ config.modResults.NSCameraUsageDescription = options.cameraPermission
17
+ || config.modResults.NSCameraUsageDescription
18
+ || 'Allow this app to use the camera to take photos and videos to upload.';
13
19
  return config;
14
20
  });
15
21
  config = withSpeechRecognition(config, {
package/dist/index.d.mts CHANGED
@@ -155,6 +155,91 @@ interface MiniAppNativeHandlers {
155
155
  params?: Record<string, unknown>;
156
156
  }, context: MiniAppHandlerContext) => Promise<void> | void;
157
157
  }
158
+ interface MiniAppUploadProcessOptions {
159
+ image?: {
160
+ max_width?: number;
161
+ max_height?: number; /** (0, 1]. */
162
+ quality?: number;
163
+ };
164
+ video?: {
165
+ max_duration?: number;
166
+ quality?: 'low' | 'medium' | 'high';
167
+ };
168
+ }
169
+ /** File đã chọn trong máy — chỉ host thấy, không gửi xuống web. */
170
+ interface MiniAppPickedFile {
171
+ uri: string;
172
+ name: string;
173
+ mime_type: string;
174
+ /** Byte. */
175
+ size?: number;
176
+ width?: number;
177
+ height?: number;
178
+ /** Giây (video). */
179
+ duration?: number;
180
+ /** Nguồn đã tự nén theo `process` → bỏ qua processors. */
181
+ processed?: boolean;
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
+ }
190
+ interface MiniAppUploadSourceRequest {
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 ý. */
192
+ accept: string[];
193
+ max_count: number;
194
+ process: MiniAppUploadProcessOptions;
195
+ caller: MiniAppUploadCaller;
196
+ }
197
+ /** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
198
+ type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
199
+ /** Xử lý 1 file (vd nén bằng react-native-compressor), trả file mới. */
200
+ type MiniAppUploadProcessor = (file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>;
201
+ /** Server của mini app: multipart POST, lấy link ở `url_field` (dạng a.b.c) của JSON trả về. */
202
+ interface MiniAppUrlUploadTarget {
203
+ target: 'url';
204
+ url: string;
205
+ headers: Record<string, string>;
206
+ form_data: Record<string, string>;
207
+ field_name: string;
208
+ url_field: string;
209
+ }
210
+ type MiniAppUploadTarget =
211
+ /** Đích app đăng ký (vd 'host') — `params` web truyền thêm, uploader tự hiểu. */
212
+ {
213
+ target: string;
214
+ params: Record<string, unknown>;
215
+ } | MiniAppUrlUploadTarget;
216
+ interface MiniAppUploadRequest {
217
+ file: MiniAppPickedFile;
218
+ target: MiniAppUploadTarget;
219
+ onProgress: (loaded: number, total: number) => void;
220
+ /** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
221
+ signal: AbortSignal;
222
+ caller: MiniAppUploadCaller;
223
+ }
224
+ /** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
225
+ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
226
+ url: string;
227
+ [key: string]: unknown;
228
+ }>;
229
+ /**
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.
233
+ */
234
+ interface MiniAppUploadOptions {
235
+ sources?: Record<string, MiniAppUploadSource | null>;
236
+ processors?: {
237
+ image?: MiniAppUploadProcessor;
238
+ video?: MiniAppUploadProcessor;
239
+ };
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. */
241
+ targets?: Record<string, MiniAppUploader>;
242
+ }
158
243
  /** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
159
244
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
245
  /** Hành vi bridge phụ thuộc ứng dụng. */
@@ -171,6 +256,8 @@ interface MiniAppBridgeOptions {
171
256
  app_version?: string;
172
257
  /** Chức năng native web gọi qua SDK: thanh toán, in, mở màn hình. */
173
258
  handlers?: MiniAppNativeHandlers;
259
+ /** uploadFiles: nguồn chọn file, xử lý, đích upload. */
260
+ upload?: MiniAppUploadOptions;
174
261
  /**
175
262
  * Web → app: event riêng của web (không qua @retion-miniapp/sdk), web gửi bằng
176
263
  * `window.ReactNativeWebView.postMessage(...)`. `data` là chuỗi gốc web gửi. Gửi lại web bằng sendEventToWeb().
@@ -569,4 +656,31 @@ interface LocationResult {
569
656
  timestamp: number;
570
657
  }
571
658
 
572
- 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 MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, 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, useMiniAppDownload, useMiniAppDownloadsPaused };
659
+ interface UploadedFile {
660
+ url: string;
661
+ name: string;
662
+ mime_type: string;
663
+ size?: number;
664
+ width?: number;
665
+ height?: number;
666
+ duration?: number;
667
+ /** Body JSON server trả về (target url) / dữ liệu thêm uploader của app trả. */
668
+ response?: unknown;
669
+ }
670
+ interface UploadFilesResult {
671
+ files: UploadedFile[];
672
+ failed: {
673
+ name: string;
674
+ code: string;
675
+ message: string;
676
+ }[];
677
+ }
678
+ interface UploadCapabilities {
679
+ sources: string[];
680
+ targets: string[];
681
+ max_count: number;
682
+ }
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. */
684
+ declare const uploadToUrl: MiniAppUploader;
685
+
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
@@ -155,6 +155,91 @@ interface MiniAppNativeHandlers {
155
155
  params?: Record<string, unknown>;
156
156
  }, context: MiniAppHandlerContext) => Promise<void> | void;
157
157
  }
158
+ interface MiniAppUploadProcessOptions {
159
+ image?: {
160
+ max_width?: number;
161
+ max_height?: number; /** (0, 1]. */
162
+ quality?: number;
163
+ };
164
+ video?: {
165
+ max_duration?: number;
166
+ quality?: 'low' | 'medium' | 'high';
167
+ };
168
+ }
169
+ /** File đã chọn trong máy — chỉ host thấy, không gửi xuống web. */
170
+ interface MiniAppPickedFile {
171
+ uri: string;
172
+ name: string;
173
+ mime_type: string;
174
+ /** Byte. */
175
+ size?: number;
176
+ width?: number;
177
+ height?: number;
178
+ /** Giây (video). */
179
+ duration?: number;
180
+ /** Nguồn đã tự nén theo `process` → bỏ qua processors. */
181
+ processed?: boolean;
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
+ }
190
+ interface MiniAppUploadSourceRequest {
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 ý. */
192
+ accept: string[];
193
+ max_count: number;
194
+ process: MiniAppUploadProcessOptions;
195
+ caller: MiniAppUploadCaller;
196
+ }
197
+ /** Nguồn lấy file (UI chọn). Người dùng huỷ → trả []. */
198
+ type MiniAppUploadSource = (request: MiniAppUploadSourceRequest) => Promise<MiniAppPickedFile[]>;
199
+ /** Xử lý 1 file (vd nén bằng react-native-compressor), trả file mới. */
200
+ type MiniAppUploadProcessor = (file: MiniAppPickedFile, options: MiniAppUploadProcessOptions) => Promise<MiniAppPickedFile>;
201
+ /** Server của mini app: multipart POST, lấy link ở `url_field` (dạng a.b.c) của JSON trả về. */
202
+ interface MiniAppUrlUploadTarget {
203
+ target: 'url';
204
+ url: string;
205
+ headers: Record<string, string>;
206
+ form_data: Record<string, string>;
207
+ field_name: string;
208
+ url_field: string;
209
+ }
210
+ type MiniAppUploadTarget =
211
+ /** Đích app đăng ký (vd 'host') — `params` web truyền thêm, uploader tự hiểu. */
212
+ {
213
+ target: string;
214
+ params: Record<string, unknown>;
215
+ } | MiniAppUrlUploadTarget;
216
+ interface MiniAppUploadRequest {
217
+ file: MiniAppPickedFile;
218
+ target: MiniAppUploadTarget;
219
+ onProgress: (loaded: number, total: number) => void;
220
+ /** Web huỷ / đóng mini app → abort; uploader nên dừng request. */
221
+ signal: AbortSignal;
222
+ caller: MiniAppUploadCaller;
223
+ }
224
+ /** Upload 1 file, trả link (+ trường thêm → web nhận trong `response`). */
225
+ type MiniAppUploader = (request: MiniAppUploadRequest) => Promise<{
226
+ url: string;
227
+ [key: string]: unknown;
228
+ }>;
229
+ /**
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.
233
+ */
234
+ interface MiniAppUploadOptions {
235
+ sources?: Record<string, MiniAppUploadSource | null>;
236
+ processors?: {
237
+ image?: MiniAppUploadProcessor;
238
+ video?: MiniAppUploadProcessor;
239
+ };
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. */
241
+ targets?: Record<string, MiniAppUploader>;
242
+ }
158
243
  /** Kiểu rung web gửi qua haptic() — trùng tên trigger của react-native-haptic-feedback. */
159
244
  type MiniAppHapticType = 'selection' | 'impactLight' | 'impactMedium' | 'impactHeavy' | 'rigid' | 'soft' | 'notificationSuccess' | 'notificationWarning' | 'notificationError';
160
245
  /** Hành vi bridge phụ thuộc ứng dụng. */
@@ -171,6 +256,8 @@ interface MiniAppBridgeOptions {
171
256
  app_version?: string;
172
257
  /** Chức năng native web gọi qua SDK: thanh toán, in, mở màn hình. */
173
258
  handlers?: MiniAppNativeHandlers;
259
+ /** uploadFiles: nguồn chọn file, xử lý, đích upload. */
260
+ upload?: MiniAppUploadOptions;
174
261
  /**
175
262
  * Web → app: event riêng của web (không qua @retion-miniapp/sdk), web gửi bằng
176
263
  * `window.ReactNativeWebView.postMessage(...)`. `data` là chuỗi gốc web gửi. Gửi lại web bằng sendEventToWeb().
@@ -569,4 +656,31 @@ interface LocationResult {
569
656
  timestamp: number;
570
657
  }
571
658
 
572
- 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 MiniAppSplashProps, type MiniAppStorage, type MiniAppSyncResult, type MiniAppUpdate, type OpenMiniAppArgs, type ReactNativeBiometricsLike, type SpeechOptions, 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, useMiniAppDownload, useMiniAppDownloadsPaused };
659
+ interface UploadedFile {
660
+ url: string;
661
+ name: string;
662
+ mime_type: string;
663
+ size?: number;
664
+ width?: number;
665
+ height?: number;
666
+ duration?: number;
667
+ /** Body JSON server trả về (target url) / dữ liệu thêm uploader của app trả. */
668
+ response?: unknown;
669
+ }
670
+ interface UploadFilesResult {
671
+ files: UploadedFile[];
672
+ failed: {
673
+ name: string;
674
+ code: string;
675
+ message: string;
676
+ }[];
677
+ }
678
+ interface UploadCapabilities {
679
+ sources: string[];
680
+ targets: string[];
681
+ max_count: number;
682
+ }
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. */
684
+ declare const uploadToUrl: MiniAppUploader;
685
+
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 hn=Object.create;var be=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var Mn=(e,t)=>{for(var n in t)be(e,n,{get:t[n],enumerable:!0})},lt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of An(t))!yn.call(e,o)&&o!==n&&be(e,o,{get:()=>t[o],enumerable:!(r=mn(t,o))||r.enumerable});return e};var fe=(e,t,n)=>(n=e!=null?hn(wn(e)):{},lt(t||!e||!e.__esModule?be(n,"default",{value:e,enumerable:!0}):n,e)),vn=e=>lt(be({},"__esModule",{value:!0}),e);var Vn={};Mn(Vn,{DefaultMiniAppSplash:()=>nt,MINIAPP_PLATFORM_URL:()=>_e,MiniAppHost:()=>ln,MiniAppHostError:()=>g,closeMiniApp:()=>pe,configureMiniApp:()=>dt,createMmkvStorage:()=>ht,createReactNativeBiometrics:()=>Ue,createRnfsFileSystem:()=>ft,ensureMiniApp:()=>Me,getLocalMiniApp:()=>x,getMiniAppCatalog:()=>sn,getMiniAppCatalogEntry:()=>le,getMiniAppStatuses:()=>Gt,getMiniAppUpdate:()=>et,installBundledMiniApp:()=>$t,onMiniAppEvent:()=>Yt,openMiniApp:()=>qt,pauseMiniApp:()=>en,pauseMiniAppDownloads:()=>nn,preloadMiniApp:()=>Ht,releaseSpeechFor:()=>z,restoreMiniApp:()=>Zt,resumeMiniApp:()=>tn,resumeMiniAppDownloads:()=>rn,sendEventToWeb:()=>Ut,syncMiniAppCatalog:()=>$e,uninstallMiniApp:()=>Xt,updateMiniApp:()=>on,useMiniAppDownload:()=>Ne,useMiniAppDownloadsPaused:()=>Kt});module.exports=vn(Vn);var _e="https://retion-miniapp-platform.vercel.app",se=null,ut=new Set,dt=e=>{se=e,ut.forEach(t=>t())},R=()=>{if(!se)throw new Error("[miniapp] Ch\u01B0a g\u1ECDi configureMiniApp()");return se},gt=e=>{ut.add(e),se&&e()},$=(...e)=>{se!=null&&se.debug&&console.log("[miniapp]",...e)};var ft=(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(o=>o.name)).catch(()=>[]),sha256:n=>e.hash(n,"sha256"),unzip:async(n,r)=>{await t(n,r)},download:({url:n,to_file:r,onProgress:o})=>{let{jobId:s,promise:a}=e.downloadFile({fromUrl:n,toFile:r,progressInterval:250,begin:()=>{},progress:({bytesWritten:c,contentLength:i})=>o==null?void 0:o(c,i)});return{promise:a.then(({statusCode:c})=>({status:c})),cancel:()=>e.stopDownload(s)}}}),ht=e=>({getString:t=>e.getString(t),setString:(t,n)=>e.set(t,n)});var f=fe(require("react")),b=require("react-native"),pn=fe(require("react-native-webview"));var he=require("react-native");var Ue=e=>({getAvailability:()=>e.isSensorAvailable(),authenticate:({reason:t,cancelButtonText:n})=>e.simplePrompt({promptMessage:t,cancelButtonText:n,fallbackPromptMessage:""})}),xe,Je=()=>(xe||(xe=import("react-native-biometrics").then(({default:e})=>Ue(new e({allowDeviceCredentials:!1}))).catch(e=>{throw xe=void 0,new g("NOT_SUPPORTED",`Biometric native module unavailable: ${e instanceof Error?e.message:String(e)}`)})),xe);var W=require("react-native");var mt=e=>{var n,r,o;if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e)))throw new g("INVALID_PARAMS","Tu\u1EF3 ch\u1ECDn v\u1ECB tr\xED ph\u1EA3i l\xE0 object");let t=e!=null?e:{};if(t.enableHighAccuracy!==void 0&&typeof t.enableHighAccuracy!="boolean")throw new g("INVALID_PARAMS","enableHighAccuracy ph\u1EA3i l\xE0 boolean");for(let[s,a,c]of[["timeout",1,6e4],["maximumAge",0,864e5]]){let i=t[s];if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||i<a||i>c))throw new g("INVALID_PARAMS",`${s} ph\u1EA3i n\u1EB1m trong kho\u1EA3ng ${a}\u2013${c} ms`)}return{enableHighAccuracy:(n=t.enableHighAccuracy)!=null?n:!1,timeout:(r=t.timeout)!=null?r:15e3,maximumAge:(o=t.maximumAge)!=null?o:0}},At=(e,t=()=>!0)=>new Promise((n,r)=>{let o=!1,s=(i,p)=>{o||(o=!0,clearTimeout(a),i?r(i):n(p))},a=setTimeout(()=>s(new g("TIMEOUT","H\u1EBFt th\u1EDDi gian ch\u1EDD c\u1EA5p quy\u1EC1n/l\u1EA5y v\u1ECB tr\xED")),12e4+e.timeout),c=()=>o?!1:t()?!0:(s(new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng")),!1);(async()=>{if(!c())return;let i;try{i=(await import("@react-native-community/geolocation")).default}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module v\u1ECB tr\xED trong b\u1EA3n native")}if(c()){if(W.Platform.OS==="android"){let p=W.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,y=W.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,d=await W.PermissionsAndroid.check(p);if(!c())return;let M=d||await W.PermissionsAndroid.check(y);if(!c())return;if(!d&&!M){let A=await W.PermissionsAndroid.requestMultiple([p,y]);if(!c())return;if(A[p]!==W.PermissionsAndroid.RESULTS.GRANTED&&A[y]!==W.PermissionsAndroid.RESULTS.GRANTED)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n truy c\u1EADp v\u1ECB tr\xED")}}c()&&i.getCurrentPosition(p=>{c()&&s(void 0,p)},p=>{var d;if(!c())return;let y=(d={1:"PERMISSION_DENIED",2:"POSITION_UNAVAILABLE",3:"TIMEOUT"}[p.code])!=null?d:"LOCATION_ERROR";s(new g(y,p.message))},e)}})().catch(i=>s(i))});var wt=require("react-native");var G,qe=e=>{var t;if(G===e&&(G=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{}},yt=async(e,t,n,r=()=>!0)=>{var s,a,c,i,p;if(G)throw new g("BUSY","Micro \u0111ang \u0111\u01B0\u1EE3c mini app kh\xE1c s\u1EED d\u1EE5ng");if(!r())throw new g("CANCELLED","Mini app kh\xF4ng c\xF2n ho\u1EA1t \u0111\u1ED9ng");let o={owner:e,emit:n,cancelled:!1,started:!1,subscriptions:[]};G=o;try{let y;try{y=await import("expo-speech-recognition")}catch{throw new g("NOT_SUPPORTED","Ch\u01B0a c\xF3 module nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i trong b\u1EA3n native")}let d=y.ExpoSpeechRecognitionModule;if(o.native=d,o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");let M=await d.requestPermissionsAsync();if(o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");if(!M.granted)throw new g("PERMISSION_DENIED","Ch\u01B0a c\u1EA5p quy\u1EC1n micro / nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i");if(await d.getStateAsync()!=="inactive")throw new g("BUSY","Nh\u1EADn d\u1EA1ng gi\u1ECDng n\xF3i \u0111ang \u0111\u01B0\u1EE3c t\xEDnh n\u0103ng kh\xE1c s\u1EED d\u1EE5ng");if(o.cancelled||!r())throw new g("CANCELLED","Mini app \u0111\xE3 \u0111\xF3ng");o.subscriptions.push(d.addListener("result",A=>{var w,C;G!==o||o.cancelled||n(A.isFinal?"speech.final":"speech.partial",{...A,text:(C=(w=A.results[0])==null?void 0:w.transcript)!=null?C:""})}),d.addListener("error",A=>{G===o&&!o.cancelled&&n("speech.error",{...A,code:A.error})}),d.addListener("end",()=>{G===o&&(qe(o),n("speech.end"))})),o.started=!0,d.start({lang:(s=t.lang)!=null?s:"vi-VN",continuous:(a=t.continuous)!=null?a:!0,interimResults:(c=t.interimResults)!=null?c:!0,addsPunctuation:(i=t.addsPunctuation)!=null?i:!0,requiresOnDeviceRecognition:(p=t.requiresOnDeviceRecognition)!=null?p:!1,iosCategory:{category:y.AVAudioSessionCategory.playAndRecord,categoryOptions:[y.AVAudioSessionCategoryOptions.defaultToSpeaker,y.AVAudioSessionCategoryOptions.allowBluetooth],mode:y.AVAudioSessionMode.measurement}})}catch(y){throw qe(o),y}},Mt=e=>{let t=G;if(!(!t||t.owner!==e)){if(!t.started){t.cancelled=!0;return}t.native.stop()}},z=e=>{let t=G;if(!(!t||t.owner!==e||t.cancelled)&&(t.cancelled=!0,t.started))try{t.native.abort()}catch{qe(t)}};var Pe=1,g=class extends Error{constructor(n,r){super(r);this.code=n}},vt=e=>{try{let t=JSON.parse(e);return(t==null?void 0:t.__retion)===Pe&&typeof t.method=="string"?t:null}catch{return null}},me=e=>`window.__RETION_MINIAPP__ && window.__RETION_MINIAPP__.receive(${JSON.stringify(e)}); true;`,St=(e,t)=>me({id:e,result:t}),bt=(e,t)=>me({id:e,error:{code:t.code,message:t.message}}),_t=(e,t)=>me({event:e,data:t}),je=e=>me({event:"context",data:e});var xt=()=>`(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: ${Pe}, method: 'log', level: level, text: parts.join(' ') }));
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;`,Et=()=>`(function () {
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: ${Pe}, method: 'touchAtTop', at_top: at_top }));
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;`,Rt=e=>me({event:e}),Pt=(e,t)=>{let n=Tt(t);return`try { history.replaceState(history.state, '', location.pathname + ${JSON.stringify(n?`?${n}`:"")} + location.hash); } catch (e) {}
42
- ${je(e)}`},Tt=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`).join("&"),Ot=(e,t={})=>{let n=Tt(t);return`window.__RETION_MINIAPP_HOST__ = { protocol: ${Pe} };
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;`},Ct={partner:"partner_token",chatbox:"chatbox_token"},It=(e,t)=>{let n={...e};for(let r of Object.values(Ct))t.includes(r)||delete n[r];return n},He=new Set,Ee=async(e,t)=>{if(He.has(e))throw new g("BUSY",`${e} \u0111ang ch\u1EA1y \u2014 ch\u1EDD l\u01B0\u1EE3t tr\u01B0\u1EDBc xong`);He.add(e);try{return await t()}finally{He.delete(e)}},Sn=new Set(["selection","impactLight","impactMedium","impactHeavy","rigid","soft","notificationSuccess","notificationWarning","notificationError"]),Re=(e,t)=>{if(typeof e!="string"||!e)throw new g("INVALID_PARAMS",`Thi\u1EBFu ${t}`);return e},Lt=async({method:e,params:t},{getHostData:n,getPermissions:r,is_dark:o,close:s,app_id:a,instance_id:c,options:i,emit:p,isActive:y})=>{var w,C,T,N,u,I,ue,Z,ve;let d=i==null?void 0:i.handlers,M={app_id:a,instance_id:c,close:s},A=()=>new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF \u1EE9ng d\u1EE5ng n\xE0y`);switch(e){case"getCurrentLocation":{let h=mt(t);return Ee(e,()=>At(h,y))}case"speech.start":{if(!p)throw A();let h={};if((t==null?void 0:t.lang)!==void 0){if(typeof t.lang!="string"||!/^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$/.test(t.lang))throw new g("INVALID_PARAMS","lang ph\u1EA3i l\xE0 m\xE3 ng\xF4n ng\u1EEF nh\u01B0 vi-VN");h.lang=t.lang}for(let S of["continuous","interimResults","addsPunctuation","requiresOnDeviceRecognition"])if((t==null?void 0:t[S])!==void 0){if(typeof t[S]!="boolean")throw new g("INVALID_PARAMS",`${S} ph\u1EA3i l\xE0 boolean`);h[S]=t[S]}return yt(c,h,p,y)}case"speech.stop":return Mt(c);case"getBiometricAvailability":return((w=i==null?void 0:i.biometrics)!=null?w:await Je()).getAvailability();case"authenticateBiometric":{let h=Re(t==null?void 0:t.reason,"reason").trim();if(!h||h.length>200)throw new g("INVALID_PARAMS","reason must contain 1\u2013200 characters");let S=t==null?void 0:t.cancelButtonText;if(S!==void 0&&(typeof S!="string"||!S.trim()||S.length>80))throw new g("INVALID_PARAMS","Invalid cancelButtonText");return Ee(e,async()=>{var ie;return((ie=i==null?void 0:i.biometrics)!=null?ie:await Je()).authenticate({reason:h,cancelButtonText:S})})}case"requestPayment":{let h=d==null?void 0:d.requestPayment;if(!h)throw A();let S=t==null?void 0:t.amount;if(typeof S!="number"||!Number.isFinite(S)||S<=0)throw new g("INVALID_PARAMS","amount ph\u1EA3i l\xE0 s\u1ED1 > 0");let U={...t,amount:S,currency:Re(t==null?void 0:t.currency,"currency")};return Ee(e,()=>h(U,M))}case"printImage":{let h=d==null?void 0:d.printImage;if(!h)throw A();let S=Re(t==null?void 0:t.image,"image");await Ee(e,()=>h({image:S},M));return}case"openScreen":if(!(d!=null&&d.openScreen))throw A();await d.openScreen({screen:Re(t==null?void 0:t.screen,"screen"),params:t==null?void 0:t.params},M);return;case"closeApp":s();return;case"openWebview":{let h=String((C=t==null?void 0:t.url)!=null?C:"");if(!/^https?:\/\//i.test(h))throw new g("INVALID_PARAMS","url ph\u1EA3i l\xE0 http(s)");await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h));return}case"openLink":{let h=String((T=t==null?void 0:t.url)!=null?T:"").trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(h)||/^(javascript|file|data|about|blob):/i.test(h))throw new g("INVALID_PARAMS","url kh\xF4ng h\u1EE3p l\u1EC7");try{await(i!=null&&i.openUrl?i.openUrl(h):he.Linking.openURL(h))}catch(S){throw new g("NOT_SUPPORTED",String((u=(N=S==null?void 0:S.message)!=null?N:S)!=null?u:"Kh\xF4ng m\u1EDF \u0111\u01B0\u1EE3c link"))}return}case"showToast":(ue=i==null?void 0:i.showToast)==null||ue.call(i,String((I=t==null?void 0:t.message)!=null?I:""));return;case"haptic":{let h=Sn.has(t==null?void 0:t.type)?t.type:"selection";(Z=i==null?void 0:i.haptic)==null||Z.call(i,h);return}case"getSystemInfo":return{platform:he.Platform.OS==="ios"?"ios":"android",appVersion:(ve=i==null?void 0:i.app_version)!=null?ve:"",theme:o?"dark":"light"};case"getAccessToken":{let h=n().access_token;if(!h)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return h}case"getToken":{let h=t==null?void 0:t.type;if(h==="access"){let ie=n().access_token;if(!ie)throw new g("HOST_ERROR","Mini app ch\u01B0a c\xF3 token cho page n\xE0y");return ie}if(h!=="partner"&&h!=="chatbox")throw new g("HOST_ERROR",`Lo\u1EA1i token kh\xF4ng h\u1EE3p l\u1EC7: ${String(h)}`);let S=Ct[h];if(!r().includes(S))throw new g("PERMISSION_DENIED",`Mini app ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5p quy\u1EC1n ${S} (Console \u2192 Quy\u1EC1n l\u1EA5y token)`);let U=h==="partner"?n().partner_token:n().chatbox_token;if(!U)throw new g("HOST_ERROR",`Kh\xF4ng c\xF3 ${S}`);return U}case"getUserInfo":{let h=n().user;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin nh\xE2n vi\xEAn");return h}case"getPageInfo":{let h=n().page;if(!h)throw new g("HOST_ERROR","Kh\xF4ng l\u1EA5y \u0111\u01B0\u1EE3c th\xF4ng tin page");return h}case"sendMessage":case"insertText":throw new g("NOT_SUPPORTED",`${e} ch\u01B0a h\u1ED7 tr\u1EE3 \u1EDF phi\xEAn b\u1EA3n app n\xE0y`);default:throw new g("NOT_SUPPORTED",`API kh\xF4ng t\u1ED3n t\u1EA1i: ${e}`)}};var ze=e=>`bundle:${e}`,Ke=()=>`${R().file_system.document_dir}/miniapps`,Ye=Ke,Ge=(e,t,n="index.html",r=!1,o=[])=>{let s=`${Ye()}/${e}/${t}`;return{app_id:e,version:t,dir:s,entry_uri:`file://${s}/${n}`,context_update:r,permissions:o}},We=e=>{var t;R().storage.setString(ze(e.app_id),JSON.stringify({version:e.version,entry:e.entry,context_update:!!e.context_update,permissions:(t=e.permissions)!=null?t:[]}))},bn=(e,t)=>/^https?:\/\//.test(t)?t:`${e.replace(/[^/]*$/,"")}${t}`,x=e=>{let t=R().storage.getString(ze(e));if(!t)return null;try{let{version:n,entry:r,context_update:o,permissions:s}=JSON.parse(t);return Ge(e,n,r,!!o,Array.isArray(s)?s:[])}catch{return null}},Q=e=>R().file_system.exists(e.entry_uri.replace("file://","")),Qe=async e=>{let t=x(e.app_id);return(t==null?void 0:t.version)===e.version&&await Q(t)},Dt=async(e,t)=>{let n=R().file_system,r=`${Ye()}/${e}`,o=await n.listDir(r).catch(()=>[]);await Promise.all(o.filter(s=>!t.includes(s)).map(s=>n.remove(`${r}/${s}`).catch(()=>{})))},Nt=async e=>{var t;await((t=we[e])==null?void 0:t.catch(()=>{})),R().storage.setString(ze(e),""),await R().file_system.remove(`${Ye()}/${e}`).catch(()=>{})},ce=class extends Error{constructor(){super("cancelled"),this.name="MiniAppInstallCancelled"}},we={},Bt=(e,t)=>{var s;let r=((s=we[e])!=null?s:Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return we[e]=o,o.then(()=>{we[e]===o&&delete we[e]}),r},_n=(e,t)=>{var o,s;let n=e.split(".").map(a=>parseInt(a,10)||0),r=t.split(".").map(a=>parseInt(a,10)||0);for(let a=0;a<Math.max(n.length,r.length);a++){let c=((o=n[a])!=null?o:0)-((s=r[a])!=null?s:0);if(c)return c}return 0},$t=({manifest:e,zip_path:t})=>Bt(e.app_id,async()=>{var s;let n=R().file_system,r=x(e.app_id);if(r&&_n(r.version,e.version)>=0&&await Q(r))return r;if(e.sha256&&n.sha256&&await n.sha256(t)!==e.sha256)throw new Error("sha256 mismatch");let o=Ge(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),We(e),$("\u0111\xE3 c\xE0i b\u1EA3n \u0111\xF3ng s\u1EB5n",e.app_id,e.version),Dt(e.app_id,[e.version,r==null?void 0:r.version].filter(Boolean)),o}),Xe=(e,{base_url:t,onProgress:n}={})=>{let r=R().file_system,o=null,s=!1,a=`${r.cache_dir}/${e.app_id}-${e.version}.zip`,c=()=>{if(s)throw new ce},i=async()=>{var d;c();let p=x(e.app_id);if((p==null?void 0:p.version)===e.version&&await r.exists(p.dir))return We(e),x(e.app_id);c();let y=r.download({url:t?bn(t,e.bundle_url):e.bundle_url,to_file:a,onProgress:(M,A)=>{var C;let w=A>0?A:(C=e.size)!=null?C:0;w>0&&(n==null||n(Math.min(1,M/w)))}});o=y;try{let{status:M}=await y.promise;if(c(),M!==200)throw new Error(`bundle ${M}`);if(e.sha256)if(r.sha256){if(await r.sha256(a)!==e.sha256)throw new Error("sha256 mismatch")}else $("b\u1ECF qua ki\u1EC3m tra sha256 (file_system kh\xF4ng c\xF3 sha256)",e.app_id);c();let A=Ge(e.app_id,e.version,e.entry,!!e.context_update,(d=e.permissions)!=null?d:[]);return await r.remove(A.dir).catch(()=>{}),await r.mkdir(A.dir),await r.unzip(a,A.dir),We(e),Dt(e.app_id,[e.version,p==null?void 0:p.version].filter(Boolean)),A}catch(M){throw s?new ce:M}finally{o=null,r.remove(a).catch(()=>{})}};return{promise:Bt(e.app_id,i),cancel:()=>{s=!0,o==null||o.cancel()}}},Ae={},xn=__DEV__?0:60*1e3,kt={},Vt=(e,t)=>{var r,o;let n=x(e);return n&&Date.now()-((r=kt[t])!=null?r:0)<xn?Promise.resolve(n):((o=Ae[e])!=null||(Ae[e]=(async()=>{let s=await fetch(t,{headers:{"Cache-Control":"no-cache"}});if(!s.ok)throw new Error(`manifest ${s.status}`);let a=await s.json(),c=await Xe(a,{base_url:t}).promise;return kt[t]=Date.now(),c})().catch(s=>(console.warn("[miniapp] sync failed",e,s==null?void 0:s.message),x(e))).finally(()=>{Ae[e]=void 0})),Ae[e])};var Te=new Map,Ft=(e,t)=>(Te.set(e,t),()=>{Te.get(e)===t&&Te.delete(e)}),Ut=(e,t)=>{let n=Te.get(e);return n?n(t):!1};var Oe=require("react"),Ce=e=>{let t=e,n=new Set;return{getState:()=>t,setState:r=>{let o=typeof r=="function"?r(t):r;t={...t,...o},n.forEach(s=>s())},subscribe:r=>(n.add(r),()=>{n.delete(r)})}},K=(e,t,n=Object.is)=>{let r=(0,Oe.useRef)(null),o=()=>{let s=e.getState(),a=r.current;if(a&&a.state===s&&a.selector===t)return a.value;let c=t(s),i=a&&n(a.value,c)?a.value:c;return r.current={state:s,selector:t,value:i},i};return(0,Oe.useSyncExternalStore)(e.subscribe,o)};var V=Ce({active_key:null,instances:{}}),Jt=({app:e,instance_id:t,context:n={},url_params:r={},host_data:o={}},s)=>{var c;let a=(c=R().keep_alive)==null?void 0:c.max_webviews;V.setState(i=>{let p=t!=null?t:e.app_id,y={...i.instances,[p]:{key:p,app:e,context:n,url_params:r,host_data:o,last_used_at:Date.now()}},d=Object.keys(y);return a&&a>0&&d.length>a&&d.filter(M=>M!==p).sort((M,A)=>y[M].last_used_at-y[A].last_used_at).slice(0,d.length-a).forEach(M=>{delete y[M]}),s?{active_key:p,instances:y}:{instances:y}})},qt=e=>Jt(e,!0),Ht=e=>Jt(e,!1),pe=()=>V.setState({active_key:null}),Ie=e=>{V.setState(t=>{if(t.active_key===e||!t.instances[e])return{};let n={...t.instances};return delete n[e],{instances:n}})};var jt="catalog",En="paused_apps",Rn="removed_apps",Pn=10*1e3,Tn=2,On=3e3,Cn=()=>{var e;try{return JSON.parse((e=R().storage.getString(jt))!=null?e:"{}")}catch{return{}}},_=Ce({catalog:{},downloads:{},pause_reasons:[],updates:{},apply_ticks:{}}),Wt=e=>{var t;return!!((t=R().manual_update)!=null&&t.includes(e))},De=new Set,zt=e=>{let t=new Set,n=()=>R().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 o=JSON.parse((r=R().storage.getString(e))!=null?r:"[]");Array.isArray(o)&&o.forEach(s=>{typeof s=="string"&&t.add(s)})}catch{}}}},H=zt(En),re=zt(Rn);gt(()=>{H.load(),re.load();let e=Cn(),t={};Object.keys(e).filter(n=>!re.has(n)).forEach(n=>{let r=x(n);r?t[n]={status:"installed",progress:1,version:r.version,has_local:!0}:H.has(n)&&(t[n]={status:"paused",progress:0,version:e[n].version,has_local:!1})}),_.setState({catalog:e,downloads:t})});var Ne=e=>K(_,t=>e?t.downloads[e]:void 0),Kt=()=>K(_,e=>e.pause_reasons.length>0),q=(...e)=>$("queue",...e),O=[],X={},v=null,Le=new Set,ae={},Ze=new Set,te=e=>{Ze.forEach(t=>{try{t(e)}catch(n){console.warn("[miniapp-queue] event listener error",n==null?void 0:n.message)}})},Yt=e=>(Ze.add(e),()=>{Ze.delete(e)}),Gt=()=>_.getState().downloads,D=(e,t)=>{let n=!!x(e),r=_.getState().downloads[e],o=t.status==="downloading"&&n?"updating":t.status,s={...r!=null?r:{status:"queued",progress:0},...t,...o?{status:o}:{},has_local:n};_.setState(a=>({downloads:{...a.downloads,[e]:s}})),(r==null?void 0:r.status)!==s.status||(r==null?void 0:r.version)!==s.version||(r==null?void 0:r.has_local)!==s.has_local?te({type:"status_change",app_id:e,state:s}):r.progress!==s.progress&&te({type:"progress",app_id:e,progress:s.progress,version:s.version})},ke=(e,t)=>{var n;(n=ae[e])==null||n.forEach(r=>r(t)),delete ae[e]},In=()=>_.getState().pause_reasons.length>0,ne=e=>{var c;if(v)return;let t=e?O.indexOf(e):In()?-1:O.findIndex(i=>!H.has(i));if(t<0||t>=O.length)return;let[n]=O.splice(t,1),r=_.getState().catalog[n];if(!r){ke(n,x(n)),ne();return}let o=Date.now();X[n]=((c=X[n])!=null?c:0)+1,D(n,{status:"downloading",progress:0,version:r.version,error:void 0});let s=0,a=Xe(r,{onProgress:i=>{let p=Math.floor(i*100);p!==s&&(s=p,D(n,{progress:p/100,version:r.version}))}});v={app_id:n,handle:a,forced:!!e},q("start",n,r.version,e?"(forced)":""),a.promise.then(i=>{q("installed",n,r.version,`${Date.now()-o}ms`),D(n,{status:"installed",progress:1,version:r.version}),ke(n,i)}).catch(i=>{var y;if(i instanceof ce){if(Le.has(n))return;q("paused",n),X[n]-=1,O.unshift(n),D(n,{status:H.has(n)?"paused":"queued",progress:0,version:r.version});return}let p=String((y=i==null?void 0:i.message)!=null?y:i);if(console.warn("[miniapp-queue] failed",n,p),X[n]<Tn){D(n,{status:"queued",progress:0,version:r.version,error:p}),setTimeout(()=>{var d;O.includes(n)||(v==null?void 0:v.app_id)===n||(O.push(n),ne((d=ae[n])!=null&&d.length?n:void 0))},On);return}D(n,{status:"failed",progress:0,version:r.version,error:p}),ke(n,x(n))}).finally(()=>{v=null;let i=O.find(p=>{var y;return(y=ae[p])==null?void 0:y.length});ne(i)})},Be=(e,{front:t=!1}={})=>{if((v==null?void 0:v.app_id)===e)return;let n=O.indexOf(e);if(n>=0){if(!t)return;O.splice(n,1)}t?O.unshift(e):O.push(e)},Ln=async e=>{let{host_id:t,client_token:n}=R(),r=new AbortController,o=setTimeout(()=>r.abort(),Pn);try{let s=`${_e}/api/hosts/${encodeURIComponent(t)}/miniapps?channel=${e}`,a=await fetch(s,{headers:{Authorization:`Bearer ${n}`,"Cache-Control":"no-cache"},signal:r.signal});if(!a.ok)throw new Error(`host list ${e} ${a.status}`);return(await a.json()).apps.map(i=>({...i,channel:e}))}finally{clearTimeout(o)}},ye=null,$e=()=>(ye!=null||(ye=(async()=>{var t;let e=Date.now();try{let n=await Promise.all(R().channels.map(Ln)),r={};[...n].reverse().flat().forEach(i=>{r[i.app_id]=i});let o=Object.keys(_.getState().catalog).filter(i=>!r[i]);R().storage.setString(jt,JSON.stringify(r)),_.setState({catalog:r}),await Promise.all(o.map(i=>Qt(i,{by_user:!1}))),o.forEach(i=>re.delete(i));let s=Object.keys(r).filter(i=>!re.has(i)),a=[],c={};for(let i of s.map(p=>r[p])){if(await Qe(i)){D(i.app_id,{status:"installed",progress:1,version:i.version});continue}let p=x(i.app_id);if(Wt(i.app_id)&&!De.has(i.app_id)&&p&&await Q(p)){D(i.app_id,{status:"installed",progress:1,version:p.version}),c[i.app_id]={app_id:i.app_id,current_version:p.version,next_version:i.version};continue}a.push(i)}return _.setState({updates:c}),a.forEach(i=>{X[i.app_id]=0,D(i.app_id,{status:H.has(i.app_id)?"paused":"queued",progress:0,version:i.version,error:void 0}),Be(i.app_id)}),q("catalog",s.length,"apps, outdated",a.map(i=>i.app_id),"removed",o,`${Date.now()-e}ms`),te({type:"sync_complete",app_ids:s,removed:o}),Object.values(c).forEach(i=>te({type:"update_available",...i})),ne(),{ok:!0,app_ids:s,removed:o}}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),te({type:"sync_failed",error:r}),{ok:!1,error:r}}finally{ye=null}})()),ye),Qt=async(e,{by_user:t})=>{var o,s,a,c;if(t&&re.add(e),Le.has(e))return;Le.add(e),H.delete(e);let n=O.indexOf(e);n>=0&&O.splice(n,1),(v==null?void 0:v.app_id)===e&&v.handle.cancel();let r=(c=(a=(o=_.getState().downloads[e])==null?void 0:o.version)!=null?a:(s=x(e))==null?void 0:s.version)!=null?c:"";D(e,{status:"uninstalling",progress:0,version:r}),await Nt(e),Ie(e),_.setState(i=>{let p={...i.downloads};return delete p[e],{downloads:p}}),delete X[e],Le.delete(e),ke(e,null),q("uninstalled",e,t?"(user)":"(not in list)"),te({type:"uninstalled",app_id:e})},Xt=e=>Qt(e,{by_user:!0}),Zt=e=>{let t=le(e);return t?(re.delete(e),(v==null?void 0:v.app_id)===e||O.includes(e)||(X[e]=0,D(e,{status:H.has(e)?"paused":"queued",progress:0,version:t.version,error:void 0}),Be(e),ne(),q("restore",e)),!0):!1},en=e=>{if(H.has(e))return;if(H.add(e),q("pause app",e),(v==null?void 0:v.app_id)===e&&!v.forced){v.handle.cancel();return}let t=_.getState().downloads[e];O.includes(e)&&t&&D(e,{status:"paused",progress:0,version:t.version})},tn=e=>{if(!H.delete(e))return;q("resume app",e);let t=_.getState().downloads[e];(t==null?void 0:t.status)==="paused"&&!O.includes(e)&&le(e)&&(X[e]=0,Be(e)),O.includes(e)&&t&&D(e,{status:"queued",progress:0,version:t.version}),ne()},nn=e=>{let{pause_reasons:t}=_.getState();t.includes(e)||(_.setState({pause_reasons:[...t,e]}),q("pause",e),t.length===0&&te({type:"pause_change",paused:!0,reasons:[e]}),v&&!v.forced&&v.handle.cancel())},rn=e=>{let{pause_reasons:t}=_.getState();if(!t.includes(e))return;let n=t.filter(r=>r!==e);_.setState({pause_reasons:n}),q("resume",e),n.length===0&&te({type:"pause_change",paused:!1,reasons:n}),ne()},et=e=>_.getState().updates[e],on=async e=>{var n,r;let t=et(e);De.add(e);try{let o=await Me(e),s=(r=t==null?void 0:t.next_version)!=null?r:(n=le(e))==null?void 0:n.version;return!o||!s||o.version!==s?!1:(_.setState(a=>{var i;let c={...a.updates};return delete c[e],{updates:c,apply_ticks:{...a.apply_ticks,[e]:((i=a.apply_ticks[e])!=null?i:0)+1}}}),q("updated",e,t==null?void 0:t.current_version,"\u2192",o.version),!0)}finally{De.delete(e)}},sn=()=>Object.values(_.getState().catalog).map(e=>({...e,installed:!!x(e.app_id),removed_by_user:re.has(e.app_id)})),le=e=>_.getState().catalog[e],Me=async e=>{let t=le(e);if(!t)return;if(H.delete(e),re.delete(e),await Qe(t))return x(e);let n=x(e);if(Wt(e)&&!De.has(e)&&n&&await Q(n))return n;let r=new Promise(o=>{var s;((s=ae[e])!=null?s:ae[e]=[]).push(o)});return(v==null?void 0:v.app_id)===e?v.forced=!0:(X[e]=0,Be(e,{front:!0}),v&&!v.forced?v.handle.cancel():ne(e)),r};var E=require("react/jsx-runtime"),tt=e=>(e!=null?e:"").replace(/\?[^#]*/,""),an=0,kn=()=>{let e=new Set;return{emit:t=>e.forEach(n=>n(t)),subscribe:t=>(e.add(t),()=>{e.delete(t)})}},Dn=f.default.memo(({instance_key:e,is_active:t,is_front:n,is_dark:r,reload_tick:o,web_at_top:s,splash:a,bridge:c,opaque_background:i,allow_embedded_miniapps:p,onWebLoadEnd:y})=>{var at,ct;let d=(0,f.useRef)(null),M=(0,f.useRef)(!1),A=K(V,l=>l.instances[e]),w=A==null?void 0:A.app.app_id,C=A==null?void 0:A.app.manifest_url,T=A==null?void 0:A.context,N=A==null?void 0:A.url_params,[u,I]=(0,f.useState)(()=>w?x(w):null),[ue,Z]=(0,f.useState)(!1),[ve,h]=(0,f.useState)(0),[S,U]=(0,f.useState)(0),[ie,B]=(0,f.useState)(!1),j=(0,f.useRef)(null),rt=l=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,B(!0)},l)};(0,f.useEffect)(()=>()=>{j.current&&clearTimeout(j.current)},[]),(0,f.useEffect)(()=>{if(!w||!t&&u)return;let l=!0;return Z(!1),(async()=>{let m=x(w),L=m?await Q(m):!1;if(!l||(I(L?J=>!J||J.version!==m.version||J.permissions.join(",")!==m.permissions.join(",")?m:J:null),__DEV__&&Date.now()-an>1e4&&(an=Date.now(),await $e()),!l))return;let ee=await Me(w),oe=ee!==void 0?ee:C?await Vt(w,C):x(w);if(l){if(!oe){Z(!0);return}I(J=>J!=null?J:oe)}})(),()=>{l=!1}},[t,w,C,ve]),(0,f.useEffect)(()=>Ft(e,l=>d.current?(d.current.postMessage(l),!0):!1),[e]);let un=K(_,l=>{let m=w?l.downloads[w]:void 0;return(m==null?void 0:m.status)==="installed"?m.version:void 0});(0,f.useEffect)(()=>{if(t||!w||!u)return;let l=x(w);if(!l||l.version===u.version)return;let m=!0;return Q(l).then(L=>{!m||!L||($(`webview:${e}`,"\u0111\u1ED5i bundle (\u1EA9n)",u.version,"\u2192",l.version),I(l))}),()=>{m=!1}},[t,w,un,u==null?void 0:u.version]);let it=K(_,l=>{var m;return w&&(m=l.apply_ticks[w])!=null?m:0});(0,f.useEffect)(()=>{if(!it||!w)return;let l=x(w);if(!l||l.version===(u==null?void 0:u.version))return;let m=!0;return Q(l).then(L=>{!m||!L||($(`webview:${e}`,"c\u1EADp nh\u1EADt",u==null?void 0:u.version,"\u2192",l.version),B(!1),I(l))}),()=>{m=!1}},[it]),(0,f.useEffect)(()=>{var L;let l=(L=R().keep_alive)==null?void 0:L.idle_close_ms;if(t||!l||l<=0)return;let m=setTimeout(()=>{Ie(e)},l);return()=>clearTimeout(m)},[t,e]),(0,f.useEffect)(()=>{o>0&&(Z(!1),B(!1),U(l=>l+1),h(l=>l+1))},[o]);let ot=(0,f.useRef)(t);(0,f.useEffect)(()=>{var l;ot.current!==t&&(ot.current=t,M.current&&((l=d.current)==null||l.injectJavaScript(Rt(t?"resumed":"paused"))))},[t]);let de=`${(at=u==null?void 0:u.version)!=null?at:"none"}:${(ct=u==null?void 0:u.permissions.join(","))!=null?ct:""}:${S}`,ge=(0,f.useMemo)(()=>JSON.stringify([T!=null?T:{},N!=null?N:{}]),[T,N]),Ve=(0,f.useMemo)(()=>{var l;return It(N!=null?N:{},(l=u==null?void 0:u.permissions)!=null?l:[])},[ge,u==null?void 0:u.permissions]),dn=(0,f.useMemo)(()=>Ot(T!=null?T:{},Ve)+Et()+(R().debug?xt():""),[Ve]),Se=(0,f.useRef)(null),st=(0,f.useRef)(null);(0,f.useEffect)(()=>{var m,L,ee;if(!u)return;if(st.current!==de){st.current=de,Se.current=ge;return}if(Se.current===ge)return;let l=((L=JSON.parse((m=Se.current)!=null?m:"[]")[0])!=null?L:{}).org_id;if(Se.current=ge,l===(T==null?void 0:T.org_id)&&M.current){B(!1),rt(1500),(ee=d.current)==null||ee.injectJavaScript(Pt(T!=null?T:{},Ve));return}B(!1),U(oe=>oe+1)},[ge,u,de]),(0,f.useEffect)(()=>(t||z(e),()=>z(e)),[t,e,de,o]),(0,f.useEffect)(()=>{let l=b.AppState.addEventListener("change",m=>{m==="background"&&z(e)});return()=>l.remove()},[e]);let gn=(0,f.useCallback)(async l=>{var L,ee,oe,J,Fe;let m=vt(l.nativeEvent.data);if(!m){if(w&&(c!=null&&c.onWebEvent))try{Promise.resolve(c.onWebEvent(l.nativeEvent.data,{app_id:w,instance_id:e})).catch(P=>{console.warn("[miniapp] onWebEvent l\u1ED7i",w,P)})}catch(P){console.warn("[miniapp] onWebEvent l\u1ED7i",w,P)}return}if(m.method==="log"){let{level:P,text:k}=m;$(`web:${e}`,P!=null?P:"log",k!=null?k:"");return}if(m.method==="pong"){j.current||B(!0);return}if(m.method==="touchAtTop"){s.emit(!!m.at_top);return}if(m.method==="contextApplied"){j.current&&clearTimeout(j.current),j.current=null,B(!0);return}if(m.method==="ready"){M.current=!0,B(!0);let P=(L=V.getState().instances[e])==null?void 0:L.context;P&&((ee=d.current)==null||ee.injectJavaScript(je(P)));return}try{let P=await Lt(m,{getHostData:()=>{var k,Y;return(Y=(k=V.getState().instances[e])==null?void 0:k.host_data)!=null?Y:{}},getPermissions:()=>{var k,Y;return w?(Y=(k=x(w))==null?void 0:k.permissions)!=null?Y:[]:[]},is_dark:r,close:pe,app_id:w!=null?w:"",instance_id:e,options:c,emit:(k,Y)=>{var pt;(pt=d.current)==null||pt.injectJavaScript(_t(k,Y))},isActive:()=>V.getState().active_key===e&&b.AppState.currentState!=="background"});m.id&&((oe=d.current)==null||oe.injectJavaScript(St(m.id,P)))}catch(P){if(!m.id)return;let k=P==null?void 0:P.code,Y=P instanceof g?P:new g(typeof k=="string"?k:"HOST_ERROR",String((J=P==null?void 0:P.message)!=null?J:P));(Fe=d.current)==null||Fe.injectJavaScript(bt(m.id,Y))}},[e,r,w,s,c]),fn=(0,f.useCallback)(()=>{Z(!1),U(l=>l+1),h(l=>l+1)},[]);return(0,E.jsxs)(b.View,{style:[b.StyleSheet.absoluteFill,i&&{backgroundColor:r?"#09090B":"#FFFFFF"},!n&&F.behind],pointerEvents:t?"auto":"none",children:[u?(0,E.jsx)(pn.default,{ref:d,source:{uri:u.entry_uri},originWhitelist:["*"],allowingReadAccessToURL:`file://${p?Ke():u.dir}`,allowFileAccess:!0,allowFileAccessFromFileURLs:!0,allowUniversalAccessFromFileURLs:!0,injectedJavaScriptBeforeContentLoaded:dn,onMessage:gn,bounces:!1,overScrollMode:"never",onLoadStart:l=>{z(e),$(`webview:${e}`,"load start",tt(l.nativeEvent.url)),M.current=!1,B(!1)},onError:l=>{z(e),$(`webview:${e}`,"load error",tt(l.nativeEvent.url),l.nativeEvent.description),Z(!0),B(!1)},onLoadEnd:l=>{let m=l.nativeEvent.url;$(`webview:${e}`,"load end",tt(m)),w&&(y==null||y({app_id:w,instance_id:e,url:m})),rt(1500)},onContentProcessDidTerminate:()=>{z(e),M.current=!1,B(!1),U(l=>l+1)},onRenderProcessGone:()=>(z(e),M.current=!1,B(!1),U(l=>l+1),!0),style:F.webview},de):null,A&&(0,E.jsx)(Bn,{visible:!u||!ie,interactive:ue,children:(0,E.jsx)(Nn,{splash:a,app:A.app,is_dark:r,error:ue,has_bundle:!!u,retry:fn})})]})}),Nn=f.default.memo(({splash:e,app:t,is_dark:n,error:r,has_bundle:o,retry:s})=>{let a=e,c=Ne(t.app_id),i=r?"error":!o&&(c==null?void 0:c.status)==="downloading"?"downloading":"loading";return(0,E.jsx)(a,{app:t,is_dark:n,status:i,progress:i==="downloading"?c==null?void 0:c.progress:void 0,retry:s})}),Bn=({visible:e,interactive:t,children:n})=>{let r=(0,f.useRef)(new b.Animated.Value(e?1:0)).current,[o,s]=(0,f.useState)(e);return(0,f.useEffect)(()=>{if(e){s(!0),r.setValue(1);return}let a=b.Animated.timing(r,{toValue:0,duration:180,useNativeDriver:!0});return a.start(({finished:c})=>{c&&s(!1)}),()=>a.stop()},[e,r]),o?(0,E.jsx)(b.Animated.View,{style:[b.StyleSheet.absoluteFill,{opacity:r}],pointerEvents:t?"auto":"none",children:n}):null},nt=({app:e,is_dark:t,status:n,progress:r,retry:o})=>{let s=t?"#FAFAFA":"#18181B";return(0,E.jsxs)(b.View,{style:[F.splash,{backgroundColor:t?"#09090B":"#FFFFFF"}],children:[(0,E.jsx)(b.View,{style:[F.splash_icon,{backgroundColor:t?"#18181B":"#F4F4F5"}],children:e.icon?(0,E.jsx)(b.Image,{source:{uri:e.icon},style:F.splash_icon_image}):(0,E.jsx)(b.Text,{style:F.splash_letter,children:(e.name||"?").slice(0,1).toUpperCase()})}),(0,E.jsx)(b.Text,{style:[F.splash_name,{color:s}],children:e.name}),n==="error"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.Text,{style:F.splash_hint,children:"Kh\xF4ng t\u1EA3i \u0111\u01B0\u1EE3c mini app"}),(0,E.jsx)(b.TouchableOpacity,{activeOpacity:.7,style:[F.retry_button,{backgroundColor:t?"#27272A":"#F4F4F5"}],onPress:o,children:(0,E.jsx)(b.Text,{style:[F.retry_text,{color:s}],children:"Th\u1EED l\u1EA1i"})})]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(b.ActivityIndicator,{style:F.splash_spinner,color:t?"#A1A1AA":"#71717A"}),n==="downloading"&&(0,E.jsxs)(b.Text,{style:F.splash_hint,children:["\u0110ang t\u1EA3i mini app",r?` ${Math.round(r*100)}%`:"\u2026"]})]})]})},cn=(e,t)=>{let n=(0,f.useRef)(t),r=(0,f.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.`))},$n=({container:e,splash:t=nt,is_dark:n=!1,bridge:r,close_on_back:o=!0,opaque_background:s=!0,allow_embedded_miniapps:a=!1,onWebLoadEnd:c})=>{cn("container",e),cn("splash",t);let i=e,p=K(V,u=>u.active_key),y=(0,f.useRef)(p);p&&(y.current=p);let d=K(V,u=>Object.keys(u.instances).join("|")),M=K(V,u=>{var I;return u.active_key?(I=u.instances[u.active_key])==null?void 0:I.app.name:void 0}),A=(0,f.useMemo)(()=>d?d.split("|"):[],[d]),[w,C]=(0,f.useState)({}),T=(0,f.useRef)(kn()).current;(0,f.useEffect)(()=>{if(!p||!o)return;let u=b.BackHandler.addEventListener("hardwareBackPress",()=>(pe(),!0));return()=>u.remove()},[p,o]);let N=(0,f.useCallback)(()=>{let u=V.getState().active_key;u&&C(I=>({...I,[u]:(I[u]||0)+1}))},[]);return A.length?(0,E.jsx)(i,{visible:!!p,title:M!=null?M:"",is_dark:n,close:pe,reload:N,subscribeWebAtTop:T.subscribe,children:A.map(u=>(0,E.jsx)(Dn,{instance_key:u,is_active:p===u,is_front:(p!=null?p:y.current)===u,is_dark:n,reload_tick:w[u]||0,web_at_top:T,splash:t,bridge:r,opaque_background:s,allow_embedded_miniapps:a,onWebLoadEnd:c},u))}):null},F=b.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"}}),ln=f.default.memo($n);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,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});